我想要做的是每当我按下“删除”按钮时它将删除我在JComboBox中选择的项目。因此,一旦我删除了所有项目,我有另一个名为“重置”的按钮,其中所有已删除的项目将再次位于JComboBox中,并且可以使用恢复方法而不必再次重新添加每个模型导致我的实际程序有很多模型
这是我试过的但它没有任何建议如何做到这一点?
public class Testing{
JFrame frame;
JPanel panel;
JButton remove,reset;
JComboBox box;
final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
{
"-","Database System","Computer Fundamentals",
"Computer Maths","Internet Web Tech","Tertiary English 1"
});
public void display()
{
frame = new JFrame();
panel = new JPanel();
box = new JComboBox();
box.setModel(items);
remove = new JButton("Remove");
reset = new JButton("Reset");
remove.addActionListener((ActionEvent e)->{
box.removeItem(box.getSelectedItem());
});
reset.addActionListener((ActionEvent e)->{
System.out.println("Reset");
box.setModel(items);
box.revalidate();
box.repaint();
});
panel.revalidate();
panel.repaint();
panel.add(box);
panel.add(remove);
panel.add(reset);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
}
public static void main(String[] args)
{
TestingProgram te = new TestingProgram();
te.display();
}
}
答案 0 :(得分:0)
我修好了。这是新代码:
public class Test{
JFrame frame;
JPanel panel;
JButton remove,reset;
JComboBox box;
final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
{
"-","Database System","Computer Fundamentals",
"Computer Maths","Internet Web Tech","Tertiary English 1"
});
public DefaultComboBoxModel getClone(DefaultComboBoxModel items) {
DefaultComboBoxModel clone = new DefaultComboBoxModel();
for(int i = 0;i<items.getSize();i++) {
clone.addElement(items.getElementAt(i));
}
return clone;
}
public void display()
{
frame = new JFrame();
panel = new JPanel();
box = new JComboBox();
box.setModel(getClone(items));
remove = new JButton("Remove");
reset = new JButton("Reset");
remove.addActionListener((ActionEvent e)->{
box.removeItem(box.getSelectedItem());
});
reset.addActionListener((ActionEvent e)->{
box.setModel(getClone(items));
});
panel.revalidate();
panel.repaint();
panel.add(box);
panel.add(remove);
panel.add(reset);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
}
public static void main(String[] args)
{
Test te = new Test();
te.display();
}
}
问题在于您使用了相同的DefaultComboBoxModel
,并且每次从JComboBox
删除某个项目时,它实际上都会从您的DefaultComboBoxModel
项目中删除它。这意味着当您重置模型时,您删除的内容也已从DefaultComboBoxModel
中移除,并且它没有做任何事情
此新代码会复制您的DefaultComboBoxModel
并添加,因此当您从中移除内容时,它不会影响final