【发布时间】:2016-02-11 06:41:21
【问题描述】:
在大学时,我们开始了 Java 编程,并得到了编写一个程序的任务,该程序在鼠标当前所在的位置绘制一条垂直线和一条水平线。我们还应该添加一个显示鼠标坐标的标签。我得到了绘图的东西,但是当我尝试添加标签时,它不会出现?我从一个测试标签开始,但即使它也没有显示在框架内。有人能帮我吗?
public class Coordinates extends JPanel implements MouseListener, MouseMotionListener {
private Point currentPoint = new Point(-50, -50);
public Coordinates(){
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.drawLine(currentPoint.x, currentPoint.y+1000, currentPoint.x, currentPoint.y-1000);
g.drawLine(currentPoint.x+1000, currentPoint.y, currentPoint.x-1000, currentPoint.y);
}
public void mousePressed(MouseEvent e){
currentPoint = e.getPoint();
repaint();
};
static JLabel label = new JLabel();
public static void main(String[] args) {
JFrame frame = new JFrame("Koordinaten");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(label);
JComponent newContentPane = new Coordinaten();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
label.setText(currentPoint.toString());
currentPoint = e.getPoint();
repaint();
}
}
【问题讨论】:
-
抱歉,我在您发布的代码中的任何地方都看不到 JLabel。它在哪里?
-
作为附带建议,在 JPanel 的 paintComponent 方法中进行所有绘制,并确保在您的覆盖中调用 super 的方法,通常在覆盖方法的开头。
-
是的,很抱歉我没有将标签放在代码中,我想你们中的一个可以告诉我如何把它放在里面?
-
如果你不向我们展示你是如何做到的,我们怎么知道你做错了什么?
-
How to create a GUI with Swing 应该向您展示如何创建和添加标签
标签: java swing label coordinates mouse