我有一个类通过计时器重新绘制它来创建动画对象(类似蠕虫的动画)。 另一个有我的Frame和Panel的类。 当我创建此对象的2个(mov和mov2)实例并将其添加到面板时,它们出现在separeted面板中(或看起来像)。这是代码。
public class Movimento extends JComponent{
int t;
int a;
int[][] matriz;
public Movimento(int tamanho, int area){
t = tamanho;
a = area;
gerarMatriz();
gerarPanel();
ActionListener counter = new ActionListener() {
public void actionPerformed(ActionEvent ev){
movimentarMatriz();
repaint();
}
};
new Timer(1, counter).start();
}
public void gerarPanel(){
this.setPreferredSize(new Dimension(a, a));
}
public void gerarMatriz(){
/*
*Generates an array[][] with initial coordinates
*/
}
public void movimentarMatriz(){
/*
* add a new coordinate to the last space of the array
*/
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i < matriz.length; i++){
g.drawRect(matriz[i][0],matriz[i][1],1,1);
}
}
然后我在这里创建新的Movimento对象
public class GeraImg{
JFrame frame = new JFrame("Gera Imagem");
JPanel panel = new JPanel();
Movimento mov = new Movimento(1000,400);
Movimento mov2 = new Movimento(100,400);
public GeraImg(){
fazerFrame();
}
public void fazerFrame(){
panel.setOpaque(true);
panel.setBackground(new Color(150,200,20,255));
panel.add(mov2);
panel.add(mov);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new GeraImg();
}
}
然后我并排获得2个separeted动画面板,而不是同一个面板中的2个蠕虫。
这个概念完全错了吗? 感谢
答案 0 :(得分:2)
panel.add(mov2);
panel.add(mov);
默认情况下,JPanel使用FlowLayout,所以是你的两个组件区域并排添加。
您可以尝试使用:
panel.setLayout(null);
panel.add(mov2);
panel.add(mov);
这将允许组件随机定位在面板内。但现在您负责在组件上使用setSize(...)和setLocation(...),以便可以在面板中正确绘制组件。
但是,更好的方法是创建自己的类来实现自己的绘制方法。类似的东西:
public class Movimento()
{
...
public void paintMe(Graphics g)
{
for(int i = 0; i < matriz.length; i++)
{
g.drawRect(matriz[i][0],matriz[i][1],1,1);
}
}
}
然后,您将创建组件以绘制所有Movimento对象。类似的东西:
public class MovimentoAnimator extends JPanel
{
private List<Movimento> movimentos = new ArrayList<Movimento>();
public void addMovimento(Movimento movimento)
{
movimentos.add( movimento );
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Movimento movimento: movimentos
{
movimento.paintMe( g );
}
}
}
这个班级也负责动画。