我已经编写了一个自定义 glasspane 组件并将其设置为我的JFrame
和JDialog
类。我不拦截自定义玻璃窗格中的鼠标事件,因为我不需要,而且因为 GUI 上有许多组件,例如树、弹出窗口等,这使得拦截和转发鼠标事件变得复杂。一切正常 - 除了每当我在框架/对话框中调用getMousePosition()
任何其他组件(例如)时,它都会返回。JPanel
null
在我的JFrame
课堂JDialog
上,我已将玻璃窗格设置为disabled
(but visible
),并且它在大多数情况下都有效。我需要做什么才能使该getMousePosition()
方法返回正确的值,而无需将鼠标事件侦听器添加到 glasspane 组件。
演示问题的示例代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GlassPaneExample
{
private JPanel panel;
private JButton btn;
private JLabel response;
private int counter = 0;
GlassPaneExample()
{
buildUI();
}
private void buildUI()
{
JFrame frame = new JFrame("GlassPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getPanel());
frame.setGlassPane(new MyGlassPane());
frame.getGlassPane().setVisible(true);
frame.getGlassPane().setEnabled(false);
frame.setPreferredSize(new Dimension(200, 220));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel getPanel()
{
panel = new JPanel(new BorderLayout());
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e)
{
}
@Override
public void mouseMoved(MouseEvent e)
{
System.out.println("mousePosition : " + panel.getMousePosition());
System.out.println("mousePosition(true) : " + panel.getMousePosition(true));
}
});
btn = new JButton("Click here...");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
response.setText("Button click number " + getButtonClickCount());
}
});
response = new JLabel();
response.setToolTipText("Response label");
panel.add(btn, BorderLayout.NORTH);
panel.add(response, BorderLayout.SOUTH);
return panel;
}
private int getButtonClickCount()
{
return counter++;
}
public static void main(String[] arg)
{
new GlassPaneExample();
}
class MyGlassPane extends JComponent
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(10,40,120,120);
}
}
}
如果您注释掉与将玻璃窗格添加到框架有关的 3 行,则鼠标位置点将正确打印出来。这是一个说明问题的简单示例,我在上面已经说过,我不想将鼠标侦听器添加到自定义 glasspane 组件,因为它会引入其他复杂性。