2

I am trying to add buttons to an already-visible jPanel. However, the following code is not working; I can't see the second button.

    ja.addActionListener(new ActionListener () {
        public void actionPerformed(ActionEvent e) {

            klicks++;

            if(klicks == 35) {                  
                panel.add(nein);
                ja.setForeground( Color.red );
                frame.repaint();
                panel.repaint();                    
            }

            if(klicks > 35) {                   
                nein.setText("Beenden");
                ja.setText("FAIL");
            }
        }});
    }

Can anyone help?

Matt
  • 74,352
  • 26
  • 153
  • 180
Lennart Schoch
  • 157
  • 2
  • 3
  • 21

2 Answers2

2

Your question is very vague but it looks like you're modifying a panel that is already visible (that is, has already been added to the hierarchy of a visible container). In this case, you should call

panel.revalidate();
panel.repaint();
sjr
  • 9,769
  • 1
  • 25
  • 36
  • 1
    @Lennart Schoch [see related example](http://stackoverflow.com/questions/6988317/dynamically-add-components-to-a-jdialog/6989230#6989230) for most of JComponents isn't required to call for repaint(), but only for plain JComponents without changes of its properties, revalidate (repaint) is quite hard for CPU an GPU, call that as last code line, once time for all changes in the Swing GUI are done – mKorbel Oct 23 '12 at 20:38
0

It's not clear what you're trying to do from the code you've provided. Could you post the entire code?

You need to create the buttons as new objects, e.g.:

JButton button1 = new JButton("button1");

And then add then to the pane.

James
  • 741
  • 1
  • 11
  • 28