NlightNFotis
NlightNFotis

Reputation: 9805

How to replace JButton in JPanel with another JButton

I am trying the following piece of code in java, but it doesn't seem to work for some strange kind of fashion:

JFrame myFrame = new JFrame("Test Frame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame.setLayout(new GridLayout());

JPanel myPanel = new JPanel();
myPanel.setLayout(new BorderLayout());
myFrame.add(myPanel);

JButton firstButton = new JButton();
myPanel.add(firstButton);

JButton secondButton = new JButton();
myPanel.remove(firstButton);
myPanel.add(secondButton);
myFrame.repaint();

What am I doing wrong?

Upvotes: 4

Views: 3215

Answers (2)

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

You could use getComponents() in order to find the the JButton index, and addComponent(Component component, int index) to add the old one in place, afterwards you could remove the one you want to replace.

Upvotes: 2

mKorbel
mKorbel

Reputation: 109813

don't repaint for JFrame (myFrame.repaint();), you have to (re)validate and repaint the nearest container as JPanel is in your case

JButton secondButton = new JButton();
myPanel.remove(firstButton);
myPanel.add(secondButton);
myPanel.revalidate();
myPanel.repaint();

Upvotes: 3

Related Questions