我有一个JFrame在BorderLayout中包含2个JPanel子类和2个JLabel。其中一个JPanel包含JButton,另一个用于显示图形。 JLabels位于北部和南部,西部的按钮JPanel和中央的显示器JPanel。JPanel重绘问题
显示器JPanel需要不断刷新,所以我通过swing定时器生成的动作事件调用repaint()方法。我也重写它的paintComponent()方法来完成我的绘图。
而不是显示我画的内容,“JFrame的内容”正被绘制到显示器JPanel上。我知道在执行绘图之前,我可以通过使用g.fillRect()或super.paintComponent()来简单地“清除”显示JPanel。
我只是好奇为什么会发生这种情况。
我使用jdk 1.6u27。下面是我的代码:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Main {
public static void main(String[] args) {
Simulation sim = new Simulation();
}
}
class Simulation extends JFrame {
public JLabel state;
private JLabel id;
private ButtonPanel control;
private Display display;
public Simulation() {
id = new JLabel("Test");
state = new JLabel("Test");
control = new ButtonPanel();
display = new Display(this);
this.setLayout(new BorderLayout());
this.add(id, BorderLayout.NORTH);
this.add(control, BorderLayout.WEST);
this.add(display, BorderLayout.CENTER);
this.add(state, BorderLayout.SOUTH);
this.setSize(500, 600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public ButtonPanel getControl() {
return this.control;
}
}
class ButtonPanel extends JPanel implements ActionListener {
public JButton b[] = new JButton[8];
public boolean bp[] = new boolean[8];
public ButtonPanel() {
this.setLayout(new GridLayout(8, 1));
for (int i = 0; i < b.length; i++) {
b[i] = new JButton(""+i);
b[i].addActionListener(this);
bp[i] = false;
this.add(b[i]);
}
}
public void actionPerformed(ActionEvent e) {
//do something
}
}
class Display extends JPanel implements ActionListener {
private Timer tm;
private int yco;
private Simulation sim;
public Display(Simulation sim) {
tm = new Timer(100, this);
tm.start();
yco = 0;
this.sim = sim;
}
@Override
public void paintComponent(Graphics g) {
//draw something
g.drawLine(0, yco, 100, 100);
}
public void actionPerformed(ActionEvent e) {
yco ++;
this.repaint();
}
}
1为[SSCCE](http://sscce.org/)。 – trashgod