I am new to Swing GUI, now I have a button1, and I want to create a new button in a panel named centerPanel when I click button1, so my code like this:
public class TestButton extends JFrame {
public static void main(String args[]) {
try {
TestButton frame = new TestButton();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public TestButton() {
super();
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel center = new JPanel();
getContentPane().add(center, BorderLayout.CENTER);
final JPanel south = new JPanel();
getContentPane().add(south, BorderLayout.SOUTH);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
JButton newbutton = new JButton("Heeeeeeeee");
center.add(newbutton);
center.repaint();
}
});
button.setText("Button1");
south.add(button);
}
}
the program can be launched, but when I click the button1, the new button does not be created, it's not appear in center panel. I try my best to find out the reason but failed, please give me a hand. Your answers are appreciated much.