Ho avuto lo stesso problema e l'ho risolto con la chiamata setVisible (true); il JFrame che stavo usando.
Esempio: se la JFrame non viene aggiornato dopo l'uso:
jframe.setContentPane(new MyContentPane());
fissarlo con:
jframe.setContentPane(new MyContentPane());
jframe.setVisible(true);
So che suona stupido per fare questo anche se il JFrame è già visibile, ma questo è l'unico modo che ho trovato finora per risolvere questo problema (la soluzione sopra proposta non ha funzionato per me).
Ecco un esempio completo. Esegui e decommenta "f.setVisible (true);" istruzioni nelle classi Panel1 e Panel2 e vedrai la differenza. Non dimenticare le importazioni (Ctrl + Shift + O per le importazioni automatiche).
Classe principale:
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 classe:
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 classe:
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);
}
}
Speranza che aiuta.
Saluti.
Grazie John, funziona perfettamente! – nautilusvn
+1 per il prezioso input. Solo un suggerimento, non c'è bisogno di mettere la chiamata 'repaint()' dentro EDT, dato che è sicuro chiamare 'repaint()' da qualsiasi thread, come descritto [qui] (http://stackoverflow.com/questions/9786497/safe -to-use-component-repaint-outside-edt/9786598 # 9786598) –
"sottoclassi di componenti Swing che hanno un delegato UI ... dovrebbe invocare' super.paintComponent() '" - [* The Paint Methods *] (http: //java.sun.com/products/jfc/tsc/articles/painting/index.html#callback). – trashgod