gpt4 book ai didi

JPanel 上的 Java mouseListener 不起作用

转载 作者:行者123 更新时间:2023-12-01 20:08:16 26 4
gpt4 key购买 nike

它是这样的:我想在自定义的 SplashScreen 上添加一个鼠标监听器(鼠标进入、鼠标离开、鼠标单击)。到目前为止我已经有了基本的想法,但我不知道如何让鼠标监听器工作。

如何在只有一个覆盖 PaintComponent 方法的组件的 JFrame 上添加 mouseListenner?

我尝试过,并且确信我做错了什么,但我找不到它是什么,并且我已经尝试了我能想到的所有方法。这是简单的程序(SSCCE):

package GUI.other;

public class SplashScreen2 {

private static final String IMAGE_LOCATION = new File(".").getAbsolutePath() + "/res/splashScreen.png";

public SplashScreen2() {
JFrame frame = new JFrame();
frame.getContentPane().add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);

//The following doesnt work

frame.addMouseListener(new MouseAdapter() {

@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Pressed");
}
});

frame.pack();
frame.setLocationRelativeTo(null);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setVisible(true);

try {

Thread.sleep(5000);
frame.dispose();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SplashScreen2();
}
});
}

@SuppressWarnings("serial")
public class ImagePanel extends JPanel {

BufferedImage img;

public ImagePanel() {
setOpaque(false);
setLayout(new GridBagLayout());
try {
img = ImageIO.read(new File(IMAGE_LOCATION));
} catch (IOException ex) {
ex.printStackTrace();
}

}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(1080 / 2, 720 / 2);
}
}
}

结果如下:

Transparent splash pane

最佳答案

您应该将监听器添加到您的ImagePanel

ImagePanel panel = new ImagePanel();
panel.addMouseListener(new MouseAdapter() {

@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Pressed");
}
});
frame.add(panel);

此外,Thread.sleep(5000);不起作用,因为您这样做了:

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SplashScreen2();
}
});

您在事件调度线程上调用了构造函数,当您阻止它时,鼠标事件将不会被调度。

关于JPanel 上的 Java mouseListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com