我有一個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