【发布时间】:2019-05-12 12:26:24
【问题描述】:
我的 JList 有问题。每当我从中删除项目时,列表不会更新它的外观,因此项目会保留在那里并且变得不可检查。
代码如下:
DefaultListModel listModel = new DefaultListModel();
JList figureListBox = new JList(listModel);
figureListBox.setBounds(5, 20, 240, 300);
figureListBox.setBackground(Color.WHITE);
figureListBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
figureListBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
figureListBox.setLayoutOrientation(JList.VERTICAL);
figureListBox.setVisibleRowCount(10);
JButton deleteFigureButton = new JButton("Delete");
deleteFigureButton.setBounds(5, 305, 240, 25);
deleteFigureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(currentFigure != -1) {
listModel.remove(currentFigure);
currentFigure = -1;
}
}
});`
重绘和重新验证不起作用,还有 updateUI()
【问题讨论】:
-
您是否曾经将
currentFigure更新为 >= 0 的值?而整个repaint的东西不应该是必要的 -
currentFigure= 选中的列表框索引。关键是我忘了提到该列表在移动窗口后会更新,并且应该删除的选定项目删除。 -
这段代码是否在 AWT 事件调度线程中运行?见javax.swing 和docs.oracle.com/javase/tutorial/uiswing/concurrency。
-
然后尝试使用
SwingUtilities.invokeLater虽然我不明白为什么它不适合你。对我来说,它按预期工作 -
我在
main()方法中使用invokeLater运行我的应用程序。
标签: java swing user-interface jlist