【发布时间】:2017-12-17 11:59:33
【问题描述】:
我正在尝试实现一个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);
}
});
}
}
【问题讨论】:
-
在
l5.setBounds(p,l,150,50);之后添加repaint();以便容器重新绘制自身及其组件(包括此JLabel)。 -
如果您仍然需要帮助,请考虑改进您的问题:添加一段解释说明您的代码应该做什么以及您的错误的细节以及您尝试调试它的结果.还要删除许多不相关的代码,这些代码与您的问题无关。相反,创建一个新的小程序来编译、运行和说明您的问题,并且不执行任何其他操作,minimal reproducible example。否则您要求我们处理太多代码。
-
我第一次在 Stack..谢谢您的输入将编辑代码并且没有添加重绘也不起作用..
标签: java swing jframe mousemotionlistener