JComboBox 事件 - Swing

如何确保 Item 是JCombobox从用户而不是其他方法更改的?

因为我也有改变项目的方法。但是当用户更改了项目时,事件必须做一些事情。


交互式爱情
浏览 149回答 2
2回答

撒科打诨

最好的想法是用布尔标志标记您自己的事件,正如@LucA 所提议的那样。但如果由于某些原因你不能这样做,你可以尝试检查事件的发起者。如果发起者是您的组合框 - 事件由用户触发。这是一个例子:import java.awt.EventQueue;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import java.util.Objects;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.WindowConstants;import javax.swing.plaf.basic.ComboPopup;/**&nbsp;* <code>JComboText</code>.&nbsp;*/public class JComboText {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String[] items = new String[] {"First", "Second", "Third", "Fourth"};&nbsp; &nbsp; &nbsp; &nbsp; JComboBox<String> combo = new JComboBox<>(items);&nbsp; &nbsp; &nbsp; &nbsp; combo.addActionListener(new ActionListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean byUser = isTriggeredByUser(combo);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Changed by: " + (byUser ? "user" : "program"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; JButton button = new JButton("Clear selection");&nbsp; &nbsp; &nbsp; &nbsp; button.addActionListener(e -> combo.setSelectedItem(null));&nbsp; &nbsp; &nbsp; &nbsp; JFrame frm = new JFrame("Combo test");&nbsp; &nbsp; &nbsp; &nbsp; frm.setLayout(new FlowLayout());&nbsp; &nbsp; &nbsp; &nbsp; frm.add(combo);&nbsp; &nbsp; &nbsp; &nbsp; frm.add(button);&nbsp; &nbsp; &nbsp; &nbsp; frm.pack();&nbsp; &nbsp; &nbsp; &nbsp; frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);&nbsp; &nbsp; &nbsp; &nbsp; frm.setLocationRelativeTo(null);&nbsp; &nbsp; &nbsp; &nbsp; frm.setVisible(true);&nbsp; &nbsp; }&nbsp; &nbsp; private static boolean isTriggeredByUser(JComboBox<?> combo) {&nbsp; &nbsp; &nbsp; &nbsp; // check whether the change was triggered by another component&nbsp; &nbsp; &nbsp; &nbsp; final ComboPopup popup = (ComboPopup) combo.getUI().getAccessibleChild(combo, 0);&nbsp; &nbsp; &nbsp; &nbsp; final JList<?> list = popup.getList();&nbsp; &nbsp; &nbsp; &nbsp; if (EventQueue.getCurrentEvent() instanceof InputEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Objects.equals(EventQueue.getCurrentEvent().getSource(), combo)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || Objects.equals(EventQueue.getCurrentEvent().getSource(), list);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}您可以复制该方法isTriggeredByUser并在您的程序中使用它。

拉风的咖菲猫

这可能有效:声明一个布尔值,意思是“组合框正在被程序更改,而不是用户”每次您的代码更改所选值时都将其设置为 true,之后再次设置为 false。在您的 actionPerformed 事件中,如果您的布尔值为真,则不执行任何操作。如果为假,则意味着用户正在更改它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java