你正在創建一個新的DrawingComponent
並將其添加到每個刻度週期的框架。這是很多DrawComponent
s
儘管可以通過移動組件來動畫,但您需要提供更多信息來說明爲什麼要這樣做。首選的方法是使用類似JPanel
的東西,將其添加到使用BorderLayout
的框架並覆蓋面板paintComponent
方法。
嘗試「移動」組件的問題是組件有一個已定義的空間,可以在其中渲染,從您的代碼外觀來看,標籤很可能具有0x0的大小,在所有油漆中......
已更新,例如
所以,下面的例子使用佈局管理器演示WITHIN組件的範圍矩形的畫就是將嘗試大小分量到可用的可用空間。
它還顯示用戶getPreferredSize
向佈局管理器提供有用的大小提示。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CreppyRectangle {
public static void main(String[] args) {
new CreppyRectangle();
}
public CreppyRectangle() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 6));
frame.add(new TestPane(Color.RED));
frame.add(new TestPane(Color.GREEN));
frame.add(new TestPane(Color.BLUE));
frame.add(new TestPane(Color.ORANGE));
frame.add(new TestPane(Color.PINK));
frame.add(new TestPane(Color.MAGENTA));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int yPos;
private int size = 25 + (int)Math.round(Math.random() * 50);
private int yDelta = 5 + (int)Math.round(Math.random() * 10);
public TestPane(Color foreground) {
setForeground(foreground);
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yPos += yDelta;
if (yPos < 0) {
yPos = 0;
yDelta *= -1;
System.out.println(yDelta);
} else if (yPos + size > getHeight()) {
yPos = getHeight() - size;
yDelta *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getForeground());
g2d.drawRect(0, yPos, getWidth() - 1, size);
g2d.dispose();
}
}
}
你正在創建一個新的'DrawingComponent'並將其添加到每個刻度週期的框架。這是很多'DrawComponent's – MadProgrammer 2013-03-05 00:11:33
請參見[this](http://stackoverflow.com/questions/13825515/java-rectangle-collision-detection-confusion/13827649#13827649)類似的答案和它的[變體](http: //stackoverflow.com/questions/13999506/threads-with-key-bindings/14001011#14001011)。並且[this](http://www.daniweb.com/software-development/java/code/444547/game-development-loop-logic-and-collision-detection-java-swing-2d)最後的例子 – 2013-03-05 21:37:03