Results 1 to 2 of 2
  1. #1
    love2java is offline Member
    Join Date
    Feb 2008
    Posts
    1
    Rep Power
    0

    Default Dynamically create a button, but what happened?

    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:

    Java Code:
    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) {
                   [B] JButton newbutton = new JButton("Heeeeeeeee");
                    center.add(newbutton);
                    center.repaint();[/B]
                }
            });
            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.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
        center.add(newbutton);
        // After adding/removing/changing a component you must
        // tell its parent container to do a new layout. We do
        // this with the JComponent method [i]revalidate[/i] or
        // with the older Container method [i]validate[/i].
        center.revalidate();
    //    center.repaint();

Similar Threads

  1. Replies: 1
    Last Post: 04-09-2008, 02:15 AM
  2. Replies: 0
    Last Post: 02-17-2008, 08:57 AM
  3. How to create widgets dynamically
    By sarbuland in forum Advanced Java
    Replies: 0
    Last Post: 02-06-2008, 08:08 PM
  4. dynamically updating clock
    By malakaherath in forum New To Java
    Replies: 2
    Last Post: 08-01-2007, 07:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •