gpt4 book ai didi

java - Jlabel 不随鼠标移动监听器移动

转载 作者:行者123 更新时间:2023-11-29 04:28:24 25 4
gpt4 key购买 nike

我正在尝试实现一个 JLabel,它在带有 mouseMotionListener 的容器中随着鼠标指针移动,但是 JLabel 没有出现在屏幕。有什么建议吗?

public class Ships extends JFrame implements ActionListener{

private JPanel contentPane;

int x=418,p=75,l=10;


public static void main(String[] args) {
Ships m = new Ships();

}

JLabel lblNewLabel = new JLabel();

JLabel l5 = new JLabel();

Container container;
/**
* Create the frame.
*/
public Ships() {
Container container= getContentPane();


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1363, 730);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
setVisible(true);

l5.setIcon(new ImageIcon("C:\\Users\\The Wimpster\\Desktop\\images22.png"));
container.add(l5);
l5.setBounds(0, 10, 75, 50);//this label is supposed to move with mouse pointer
container.addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
p = e.getX();
l = e.getY();
l5.setBounds(p,l,150,50);
}
});
}
}

最佳答案

您正在创建 Ships 类的两个实例 - 构造函数调用 setVisible(true) 因此出现两个实例 - 这可能不是我们想要的。

但是问题确实出现了,因为您正在获取表单的内容 Pane ,然后创建一个新面板,将其设置为新的内容 Pane ,然后将标签添加到旧 Pane ,然后将鼠标监听器添加到旧内容 Pane 。

只需删除对现有 Pane 的引用即可。

public Ships() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1363, 730);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
setVisible(true);

l5.setIcon(new ImageIcon("C:\\Users\\The Wimpster\\Desktop\\images22.png"));
//
contentPane .add(l5);
l5.setBounds(0, 10, 75, 50);//this label is supposed to move with mouse pointer
contentPane .addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
p = e.getX();
l = e.getY();
l5.setBounds(p,l,150,50);
}
});
}

关于java - Jlabel 不随鼠标移动监听器移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45068150/

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