我想將一個對象添加到JPanel,然後在重新限制JPanel並添加新對象之後重新繪製一個對象。如何正確添加組件並用組件重新繪製JPanel?
package papProject;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Animation extends JPanel{
private static boolean loop = true;
private static int frameTimeInMillis = 10;
public static void main(String[] args){
JPanel Ani = new JPanel();
Ani.getParent();
setup(Ani);
while (loop) {
Ani.repaint();
try {
Thread.sleep(frameTimeInMillis);
} catch (InterruptedException e) {
}
}
}
public static void setup(JPanel Panel)
{
Circle circle[] = new Circle[10];
JFrame jf = new JFrame();
jf.setTitle("Falling Shapes Animation");
Panel.setLayout(new BorderLayout());
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(Panel);
for(int i = 0; i < circle.length; i++)
{
Panel.add(circle[i] = new Circle());
}
}
}
此代碼繪製JPanels和圓對象添加到它,並假定重繪該組件,然後添加新的對象。我相信我的問題是與main()方法。
@SuppressWarnings("serial")
public class Circle extends Animation implements ActionListener
{
int ranNum = 0;
int y = 0;
int x = (int) Math.random();
int velY = 2;
Circle()
{
x = getRanNum();
}
public int getRanNum() {
Random rand = new Random();
for (int j = 0; j<10; j++)
ranNum = rand.nextInt(300);
return ranNum;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
}
public void actionPerformed(ActionEvent e)
{
if (y>370){
velY =-velY;
}
y = y + velY;
}
}
此代碼從隨機的x位置繪製Cirlce對象並將其移動到y方向。 感謝您給予的任何幫助。
我加了'jf = new JFrame();',否則會拋出一個空點異常。 – reporter
這是正確的,因爲我沒有放置整個代碼,所以我在方法「setup」中放入了「jf = new JFrame()」。謝謝。 – zicrox