I am trying to use a button to essentially replace a JPanel with another JPanel. However, when I run the code below and click on the button in the window, it displays a blank screen instead of "Instructions". I have called revalidate()
and repaint()
after the removeAll()
method, as other people have stated in other forums, and anything I do to the window (i.e. resizing, minimizing, etc.) doesn't work.
I'm sure it's something stupid that I'm missing, but I've run out of ideas.
Thanks.
public class TitlePage extends JPanel{
private static final long serialVersionUID = 0;
private JButton a;
//The code works without me needing to define an extra JPanel instance variable.
public TitlePage(){
setLayout(null);
setBackground(Color.WHITE);
JLabel title = new JLabel("2009 AP(R) Computer Science A Diagnostic Exam");
title.setBounds(175,100,650,50);
title.setFont(new Font("Times New Roman", Font.PLAIN, 30));
setVisible(true);
add(title);
a = new JButton("Start Diagnostic");
a.setBounds(400, 300, 200, 50);
a.setForeground(Color.BLUE);
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
removeAll();
revalidate();
repaint();
add(new Instructions());
revalidate();
repaint();
}
});
setVisible(true);
add(a);
JLabel disclaimer = new JLabel("*AP(R) is a registered trademark of the College Board, which was not involved in the production of, and does not endorse, this product.");
disclaimer.setBounds(150,650,750,50);
disclaimer.setFont(new Font("Times New Roman", Font.PLAIN, 12));
setVisible(true);
add(disclaimer);
}
}
The Instructions class contains a simple JLabel.
public class Instructions extends JPanel {
private static final long serialVersionUID = 0;
public Instructions(){
JLabel instr = new JLabel("Instructions");
instr.setBounds(0,0,100,50);
instr.setForeground(Color.BLACK);
instr.setFont(new Font("Times New Roman", Font.PLAIN, 30));
setVisible(true);
add(instr);
}
}