【发布时间】:2017-10-28 13:04:13
【问题描述】:
我正在练习在Panel中画一个球,并在拖动球时显示球的坐标。
这是我第一次练习绘画练习(?)
这是我的代码。
import java.awt.*;
import java.awt.event.*;
public class MovingBall extends Frame {
Panel ballPanel = new Panel();
Label ballLabel = new Label();
Panel coordinatePanel = new Panel();
Label coordinateLabel = new Label();
int x0=0,y0 =0, x=20,y=30;
int nowX, nowY;
Label nowXcoordinateLabel = new Label("Now X :"+nowX);
Label nowYcoordinateLabel = new Label("Now Y :"+nowY);
MovingBall(){
setLayout(new GridLayout(1,1));
ballPanel.add(ballLabel); coordinatePanel.add(coordinateLabel);
add(ballPanel);
add(coordinatePanel);
ballPanel.setBackground(Color.white);
coordinatePanel.setBackground(Color.LIGHT_GRAY);
nowXcoordinateLabel.setBackground(Color.WHITE);
nowYcoordinateLabel.setBackground(Color.WHITE);
coordinatePanel.add(nowXcoordinateLabel);
coordinatePanel.add(nowYcoordinateLabel);
setVisible(true);
setSize(400,400);
MouseMotionListener ml = new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
Point p = new Point();
nowX = (int) p.getX();
nowY = (int) p.getY();
}
};
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
}
);
}
public void paintComponent(Graphics2D gg){
// super.paintComponents(gg);
ballPanel.paintComponents(gg);
gg.setColor(Color.BLUE);
gg.fillOval(x0, y0, 10, 10);
}
public static void main(String[]arg){
MovingBall mb = new MovingBall();
}
}
我有两个问题
- 我使用
fillOval和paintComponent绘制并显示了一个球,但我在屏幕上看不到它。为什么? - 如果我想使用
mouseDragged移动球,知道如何移动球吗?我需要一些线程吗?
【问题讨论】:
-
您将此标记为 Swing 问题,因此您应该使用 Swing 组件,而不是 AWT 组件。 Swing 组件以
"J"(JButton, JPanel...) 开头;阅读 Swing 教程中关于 [自定义绘画]() 的部分,了解绘画的基础知识。工作代码显示了如何在鼠标事件上更改正方形的位置。修改你处理 mouseDragged 的代码。 -
AWT
Frame没有paintComponent方法,将@Override添加到方法中,会产生编译器错误。这也不是您应该如何进行自定义绘画,ballPanel应该进行绘画,而不是框架。人们在 10 多年前就停止使用 AWT,使用 Swing 或 Java FX 会得到更好的响应 -
我知道我的 mouseDragged 是错误的,但我这样做只是为了检查我的 Label 是否正常工作。
-
@MadProgrammer 谢谢你的好建议!但是我必须学习awt,因为我下周要进行java测试。 . :(
-
@MadProgrammer 你是什么意思“ballPanel 应该在做paintitng,而不是框架。”?你能再解释一下吗?