【发布时间】:2011-11-05 00:06:56
【问题描述】:
我有一个 JFrame,它在 BorderLayout 中包含 2 个 JPanel 子类和 2 个 JLabel。其中一个 JPanel 包含 JButton,另一个用于显示图形。 JLabel 位于南北,按钮 JPanel 在西,显示 JPanel 在中心。
显示JPanel 需要不断刷新,所以我通过swing timer 生成的动作事件调用它的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();
}
}
【问题讨论】:
-
为sscce+1。