Ich habe eine App erstellt, die ein Quadrat enthält, das jedes Mal springt, wenn es eine Kante des Rahmens berührt.Ich habe keine Probleme beim Mittagessen der App, das Problem ist, dass ich nicht weiß, wie man verschiedene Threads erstellen kann Vielfache Quadrate innerhalb des Rahmens. Ich habe mehrere Dinge ausprobiert, aber ich kann nicht herausfinden, wo ich die Threads erstellen soll. Ich bemerkte auch, dass das Quadrat nur sichtbar ist, wenn ich es direkt im Rahmen hinzufüge und nicht, wenn ich es in ein JPanel stecke.Wie Multithread mit 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);
}
}
Ist es normal, dass trotz ich eine Zeit von 2 innerhalb der Timer setzen, die Platz bewegt sich sehr langsam?
Vielen you.I die x_y_rules put() Methode innerhalb des ActionListener.The Problem ist, dass, wenn eine andere Platz schaffen und ich es mit dem Rahmen hinzufügen Letzteres zeigt nur ein Quadrat. Deshalb dachte ich, ich sollte Threads verwenden. – TomCa
Sie sollten die Layout-Manager untersuchen, da Sie Threading nicht zum Lösen eines Layout-Manager-Problems verwenden. JFrame contentPane verwendet BorderLayout, und wenn Sie dem JFrame standardmäßig eine Komponente hinzufügen, wird nur die zuletzt hinzugefügte Komponente angezeigt. –