我创建了一个应用程序,它包含一个正方形,每次触及frame的边缘时都会弹出一个正方形。我没有问题发起应用程序,问题是我不知道如何创建各种线程以便拥有框架内的多个正方形。 我尝试了多件事,但我无法弄清楚我应该在哪里创建线程。 我还注意到,只有当我直接将其添加到框架内而不是当我将它放入JPanel内时,该正方形才可见。如何用paintComponent()多线程?
Square.java
public class Square extends JComponent implements ActionListener {
int width = 20;
int height = 20;
double y = Math.random() * 360;
double x = Math.random() * 360;
boolean xMax = false;
boolean yMax = false;
boolean xMin = true;
boolean yMin = true;
Rectangle2D.Double square = new Rectangle2D.Double(x, y, width, height);
public Square() {
Timer t = new Timer(2, this);
t.start();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g2.setColor(Color.BLUE);
g2.fill(square);
x_y_rules();
}
public void x_y_rules() {
if (xMax == true) {
x = x - 0.5;
if (x <= 0) {
xMax = false;
}
} else {
x = x + 0.5;
if (x >= this.getWidth()) {
xMax = true;
}
}
if (yMax == true) {
y = y - 0.5;
if (y <= 0) {
yMax = false;
}
} else {
y = y + 0.5;
if (y >= this.getHeight()) {
yMax = true;
}
}
square.setFrame(x, y, width, height);
}
@Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
}
App.java
public class App extends JFrame {
public static void main(String[] args) {
JFrame jf = new JFrame();
Square sqr = new Square();
jf.setSize(400, 400);
jf.setVisible(true);
jf.add(sqr);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
}
}
这是正常的,尽管我把2时定时器内,广场上移动很慢?
谢谢。我把x_y_rules()方法ActionListener.The问题内部是,如果一个创建另一个正方形,我将它添加到帧,后者只显示一个正方形。这就是为什么我认为我应该使用线程。 – TomCa
由于您不使用线程来解决布局管理器问题,因此您将需要研究布局管理器。 JFrame contentPane使用BorderLayout,并且当您将组件默认添加到JFrame时,只会显示最近添加的组件。 –