import javax.swing.*;
import java.awt.*;
public class Test1 {
int x = 70;
int y = 70;
public static void main (String[] args) {
Test1 gui = new Test1 ();
gui.go();
}
public void go() {
JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
x++; y++;
drawPanel.repaint();
try { Thread.sleep(50);
} catch(Exception ex) { } }
}// close go() method
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(x,y,40,40);
}
} // close inner class
} // close outer class
根据第2页,圆圈应涂抹在框架中......但实际上,当我跑步时,它只是移动而没有涂抹。那是为什么? 顺便说一句,如果这些代码无法制作涂抹圆圈,我怎么能做一个涂抹的呢?
欢呼答案 0 :(得分:2)
如图所示here,&#34;如果您不尊重opaque property,您可能会 †看到视觉瑕疵。&# 34;实际上,在Mac OS X上使用Java 6运行您的示例会产生一系列看起来被涂抹的圆圈。&#34;
我怎么能弄脏一个?
不依靠painting artifacts获得所需的结果;相反,如下所示呈现List<Shape>
。
使用javax.swing.Timer
来调整动画效果。
在event dispatch thread上构建和操作仅的Swing GUI对象。
覆盖getPreferredSize()
以建立绘图面板的初始几何体。
代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test2 {
public static void main(String[] args) {
EventQueue.invokeLater(new Test2()::display);
}
public void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final MyDrawPanel drawPanel = new MyDrawPanel();
frame.add(drawPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyDrawPanel extends JPanel {
private int x = 30;
private int y = 30;
private final List<Shape> list = new ArrayList<>();
public MyDrawPanel() {
new Timer(50, (new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x++;
y++;
list.add(new Ellipse2D.Double(x, y, 40, 40));
repaint();
}
})).start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.green);
for (Shape s : list) {
g2d.fill(s);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
}
†强调我的。