Tôi đã gặp sự cố tương tự và đã khắc phục sự cố bằng cách gọi setVisible (true); JFrame tôi đang sử dụng.
Ví dụ: nếu JFrame của bạn không cập nhật sau khi sử dụng:
jframe.setContentPane(new MyContentPane());
sửa chữa nó với:
jframe.setContentPane(new MyContentPane());
jframe.setVisible(true);
Tôi biết rằng nó có vẻ ngớ ngẩn để làm điều này mặc dù JFrame của bạn là đã có thể nhìn thấy, nhưng đó là cách duy nhất tôi đã tìm thấy cho đến nay để khắc phục vấn đề này (giải pháp được đề xuất ở trên không hiệu quả đối với tôi).
Dưới đây là ví dụ hoàn chỉnh. Chạy nó và sau đó bỏ ghi chú "f.setVisible (true);" hướng dẫn trong các lớp Panel1 và Panel2 và bạn sẽ thấy sự khác biệt. Đừng quên nhập (Ctrl + Shift + O để nhập tự động).
lớp chính:
public class Main {
private static JFrame f;
public static void main(String[] args) {
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new Panel1(f));
f.pack();
f.setVisible(true);
}
}
Panel1 lớp:
public class Panel1 extends JPanel{
private JFrame f;
public Panel1(JFrame frame) {
f = frame;
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
JButton b = new JButton("Panel 1");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.setContentPane(new Panel2(f));
// Uncomment the instruction below to fix GUI "update-on-resize-only" problem
//f.setVisible(true);
}
});
add(b);
}
}
Panel2 lớp:
public class Panel2 extends JPanel{
private JFrame f;
public Panel2(JFrame frame) {
f = frame;
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
JButton b = new JButton("Panel 2");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.setContentPane(new Panel1(f));
// Uncomment the instruction below to fix GUI "update-on-resize-only" problem
//f.setVisible(true);
}
});
add(b);
}
}
Hy vọng rằng sẽ giúp.
Trân trọng.
Cảm ơn John, nó hoạt động hoàn hảo! – nautilusvn
+1 cho đầu vào có giá trị. Chỉ là một gợi ý, không cần phải đặt 'repaint()' gọi bên trong EDT, vì nó an toàn để gọi 'repaint()' từ bất kỳ luồng nào, như được mô tả [ở đây] (http://stackoverflow.com/questions/9786497/safe -to-use-component-repaint-outer-edt/9786598 # 9786598) –
"các lớp con của các thành phần Swing có giao diện người dùng giao diện người dùng ... nên gọi' super.paintComponent() '" - [* Phương thức vẽ *] (http: //java.sun.com/products/jfc/tsc/articles/painting/index.html#callback). – trashgod