Tôi có một JFrame chứa 2 phân lớp JPanel và 2 JLabel trong BorderLayout. Một trong những JPanel chứa JButtons và cái kia được sử dụng để hiển thị đồ họa. Các JLabels ở phía bắc và phía nam, nút JPanel ở phía tây và màn hình hiển thị JPanel ở giữa.JPanel repaint issue
Màn hình JPanel yêu cầu làm mới liên tục, vì vậy tôi gọi phương thức repaint() của nó thông qua sự kiện hành động được tạo bởi bộ hẹn giờ xoay. Tôi cũng ghi đè lên phương thức paintComponent() của nó để vẽ các bản vẽ của tôi.
Thay vì hiển thị những gì tôi đã vẽ, "nội dung của JFrame" đang được vẽ lên màn hình hiển thị JPanel. Tôi biết rằng tôi có thể chỉ đơn giản là "xóa" hiển thị JPanel bằng cách sử dụng g.fillRect() hoặc super.paintComponent() trước khi thực hiện các bản vẽ của tôi.
Tôi chỉ tò mò tại sao điều này xảy ra.
Tôi đang sử dụng jdk 1.6u27. dưới đây là mã của tôi:
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 cho [sscce] (http://sscce.org/). – trashgod