我正在尝试在添加其他选项时将组件从JLabel
更改为JComboBox
,但由于某种原因,该面板未更新。
SSCCE:
public class SwitchComponent {
public static void main(String[] args) {
JPanel panel = new JPanel();
JComponent component = new JLabel("This is a test");
panel.add(component);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Testing..");
comboBox.addItem("1.. 2.. 3..");
component = comboBox;
// I have tried with only one of the below lines and without any also...
// Doesn't seem to have an effect.
// I've also tried invoking the below methods on the panel instead.
component.revalidate();
component.repaint();
JOptionPane.showConfirmDialog(null, panel, "Test",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE);
}
}
为什么会这样?不应panel
引用component
,以便对component
的任何更改都通过panel
反映出来了吗?
当组件发生变化时,我真的必须完全重新组装面板吗?
答案 0 :(得分:2)
当点击JOptionPane上的YES / NO按钮时,JOptionPane将关闭。
我们需要再次将JComboBox添加到Panel,并使用JOptionPane在您的代码中再次显示Panel。
试试这个:
public class SwitchComponent {
public static void main(String[] args) {
JPanel panel = new JPanel();
JComponent component = new JLabel("This is a test");
panel.add(component);
JOptionPane.showConfirmDialog(null, panel, "Test",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE);
panel.remove(component);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Testing..");
comboBox.addItem("1.. 2.. 3..");
panel.add(comboBox);
// I have tried with only one of the below lines and without any also...
// Doesn't seem to have an effect.
// I've also tried invoking the below methods on the panel instead.
panel.revalidate();
panel.repaint();
JOptionPane.showConfirmDialog(null, panel, "Test",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE);
}
}
答案 1 :(得分:0)
即。标签可能是三个系列中的第二个,当组件更改为组合框时,我希望组合框保持第二。因此,为什么我试图改变参考
使用Card Layout。它将替换同一位置的组件。