I have two buttons added in two different panels, if first button is clicked then it need to take to next panel with the second button in it. But the button was not replaced when I click first button.
/*Java GUI*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestFrame extends JFrame{
private JPanel panel1, panel2;
private JButton but,but2;
public TestFrame()
{
createPanel();
addPanel();
}
private void createPanel()
{
panel1 = new JPanel();
but = new JButton("TestButton");
but.addActionListener(new addButtonListener());
panel2 = new JPanel();
but2 = new JButton("TestButton2");
}
private void addPanel()
{
panel1.add(but);
panel2.add(but2);
add(panel1);
}
class addButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
getContentPane().removeAll();
add(panel2);
repaint();
}
}
public static void main(String args[])
{
JFrame frame = new TestFrame();
frame.setTitle("Test Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
After remowing all from contentPane, try add panel to ContentPane. Second thing is repainting. If you will not update panel content, it will be painted after resize. Here you are example solution:
Oracle docs explains difference beetwen adding to contentPane or to Frame directly.
http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html