[英]How to replace JButton in JPanel with another JButton
我在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();
我究竟做錯了什么?
不要重新繪制JFrame
( myFrame.repaint();
),你必須(re)validate
並repaint
最近的容器,因為JPanel
在你的情況下
JButton secondButton = new JButton();
myPanel.remove(firstButton);
myPanel.add(secondButton);
myPanel.revalidate();
myPanel.repaint();
您可以使用getComponents()
來查找JButton
索引,並使用addComponent(Component component, int index)
來添加舊的addComponent(Component component, int index)
,之后您可以刪除要替換的那個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.