【发布时间】:2015-12-26 02:43:43
【问题描述】:
PaintComponent 不绘制图形。什么都没有发生,干净的 Jframe 出现了。 我认为列表或我调用方法的方式有问题 List 与 Paint 组件在类中
public class Paint extends JPanel implements ActionListener {
List<Figures> figuresList = new ArrayList<Figures>();
Timer t = new Timer(5, this);
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Figures figure : figuresList) {
figure.drawItself(g, figure.getLocationX(), figure.getLocationY());
}
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
{
for (Figures figure : figuresList) {
if (figure.getLocationX() < 0 || figure.getLocationX() > 540) {
figure.setVelocityX(-figure.getVelocityX());
}
if (figure.getLocationY() < 0 || figure.getLocationX() > 220) {
figure.setVelocityY(-figure.getVelocityY());
}
figure.setLocationX(figure.getLocationX()
+ figure.getVelocityX());
figure.setLocationY(figure.getLocationY()
+ figure.getVelocityY());
}
}
repaint();
}
还有画本身:
public class Circle implements Figures {
public int locationX = 12;
public int locationY = 12;
public int velocityX =1;
public int velocityY =1;
public void drawItself(Graphics g, int locationX, int locationY){
this.locationX = locationX;
this.locationY = locationY;
g.drawOval(locationX, locationY, 40, 40);
g.fillOval(locationX, locationY, 40, 40);
}
主要:
public static void main(String[] args) {
Circle c = new Circle();
Quadrat q = new Quadrat();
Paint p = new Paint();
p.figuresList.add(c);
p.figuresList.add(q);
GUI.Configuration();
}
图形界面
public class GUI {
public static void Configuration(){
JFrame frame = new JFrame("Figures Animation");
frame.setSize(600,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new Paint();
frame.getContentPane().add(BorderLayout.CENTER, panel);
}
【问题讨论】:
-
“不起作用”是什么意思?请多解释一下您的预期以及发生了什么。
-
我希望表单图形出现在 JFrame 上,但什么也没发生。没有错误,只需清理 JFrame。
-
当我将此方法编码为构造函数并在 PaintComponent 方法“new Circle(g, 0,0)”内部写入时,一切都很好,但我需要 ActionPerformed 方法的数字列表,我需要调用获取设置方法。
-
我无法接受您所说的某些内容。我想我们需要看到MCVE。
-
我们绝对需要看到你的minimal reproducible example。此外,您似乎不需要将
figure.getLocationX()和figure.getLocationY()传递到 drawItself 方法,因为您将图形自己的状态字段传递回自身 - 没有意义。该图已经具有这些字段值。
标签: java swing paintcomponent