Miałem ten sam problem i naprawiłem go przez wywołanie setVisible (true); JFrame, którego używałem.
Przykład: jeśli JFrame nie aktualizuje po użyciu:
jframe.setContentPane(new MyContentPane());
Fix z:
jframe.setContentPane(new MyContentPane());
jframe.setVisible(true);
Wiem, że to brzmi głupio, aby to zrobić, mimo że JFrame jest już widoczny, ale to jedyny sposób, jaki znalazłem do tej pory, aby rozwiązać ten problem (rozwiązanie zaproponowane powyżej nie działało dla mnie).
Oto pełny przykład. Uruchom go, a następnie odkomentuj "f.setVisible (true);" instrukcje w klasach Panel1 i Panel2, a zobaczysz różnicę. Nie zapomnij o importach (Ctrl + Shift + O dla importów automatycznych).
główne klasy:
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 klasa:
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 klasa:
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);
}
}
nadzieję, że pomoże.
Pozdrawiam.
Dziękuję John, działa idealnie! – nautilusvn
+1 za wartościowy wkład. Tylko sugestia, nie ma potrzeby wprowadzania wywołania 'repaint()' wewnątrz EDT, ponieważ można bezpiecznie wywoływać 'repaint()' z dowolnego wątku, jak opisano [tutaj] (http://stackoverflow.com/questions/9786497/safe -to-use-component-repaint-outside-edt/9786598 # 9786598) –
"podklasy komponentów Swing, które mają delegata UI ... powinny wywoływać' super.paintComponent() '" - [* The Paint Methods *] (http: //java.sun.com/products/jfc/tsc/articles/painting/index.html#callback). – trashgod