我应该编写一个GUI。此GUI中的每个组件都必须能够动态调整大小。
到目前为止,我使用了GlassPane和ContentPane,添加了一个JPanel并在其上添加了一个按钮。当单击GlassPane时,将获取事件,分析基础组件,为此特殊组件创建新的句柄并将其处理到所述组件。我添加了一个按钮,该按钮应自动更改其大小。像我想要的那样工作。但是:当我更改框架的大小并立即单击按钮时,什么也没有发生。GlassPane能够识别按钮,但似乎有些问题…
这是拦截GlassPane并将事件提供给组件的代码:
private void resendEvent(MouseEvent e) { //Point p = SwingUtilities.convertPoint(content.getGlassPane(), e.getPoint(), content.getContentPane()); Point p = e.getPoint(); Component component = SwingUtilities.getDeepestComponentAt(content.getContentPane(), p.x, p.y); System.out.println(component.toString()); Point p2 = component.getLocation(); MouseEvent event = new MouseEvent(component, e.getID(), e.getWhen(), e.getModifiers(), p2.x, p2.y, e.getClickCount(), e.isPopupTrigger()); //following lines have the same effects Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event); //component.dispatchEvent(event); }
感谢您的帮助/建议
好的,这里还有更多代码:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import resize.ResizablePanel; public class ExampleProblem extends JFrame { public ExampleProblem () { JPanel glassPane = new JPanel(); glassPane.setOpaque(false); glassPane.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent e) { resendEvent(e); } @Override public void mouseReleased(MouseEvent e) { resendEvent(e); } }); this.setGlassPane(glassPane); glassPane.setVisible(true); JButton b = new JButton("Test"); b.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Button clicked"); }}); JPanel p = new JPanel(); p.add(b); setContentPane(p); pack(); setVisible(true); } private void resendEvent(MouseEvent e) {//Point p = SwingUtilities.convertPoint(content.getGlassPane(), e.getPoint(), content.getContentPane()); Point p = e.getPoint(); Component component = SwingUtilities.getDeepestComponentAt(this.getContentPane(), p.x, p.y); System.out.println(component.toString()); Point p2 = component.getLocation(); MouseEvent event = new MouseEvent(component, e.getID(), e.getWhen(), e.getModifiers(), p2.x, p2.y, e.getClickCount(), e.isPopupTrigger()); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event); } public static void main(String[] args) { new ExampleProblem(); } }
希望问题现在已经清楚了。是否有可能我不应该使用setContentPane()?但是我们必须覆盖JContentPane才能调整其组件的大小。
您必须从坐标确定分量点。使用它而不是p2来创建事件:
Point p2 = SwingUtilities.convertPoint(this.getGlassPane(), p, component);