4

私はJavaで次のコードを試していますが、奇妙な種類の方法では機能しないようです。

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();

私は何が間違っているのですか?

4

2 に答える 2

3

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();
于 2012-06-19T08:25:54.017 に答える
2

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.

于 2012-06-19T08:26:07.573 に答える