gpt4 book ai didi

Java swing下拉选择监听器

转载 作者:行者123 更新时间:2023-12-01 20:22:01 26 4
gpt4 key购买 nike

我有一个 JCombobox,其中包含大量项目。选择一个项目后,我需要完成一些事情。我尝试使用 actionListener 和 itemListner

myComboBox.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String selection = (String)myComboBox.getSelectedItem();
System.out.println("Selected: "+selection ) ;
}
}
});

使用 Action 监听器,我尝试了同样的事情

我面临的问题是这样的当用户滚动打开的下拉菜单时,他会无意中继续选择他不需要的每个项目。 (或者如果使用鼠标滚轮等...)。
因此,我希望能够仅捕获用户所做的选择。如何做呢 ?

最佳答案

The problem, I am facing is this When user rolls through the open drop down he inadvertently keep selecting each item he does not need.

您可以使用以下方法阻止监听器触发:

comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);

例如:

/*
This works on non editable combo boxes
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.*;

public class ComboBoxAction extends JFrame implements ActionListener
{
public ComboBoxAction()
{
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener( this );

comboBox.addItem( "Item 1" );
comboBox.addItem( "Item 2" );
comboBox.addItem( "Item 3" );
comboBox.addItem( "Item 4" );

// This prevents action events from being fired when the
// up/down arrow keys are used on the dropdown menu

comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);

getContentPane().add( comboBox );
getContentPane().add( new JTextField(), BorderLayout.SOUTH );
}

public void actionPerformed(ActionEvent e)
{
System.out.println( e.getModifiers() );

JComboBox comboBox = (JComboBox)e.getSource();
System.out.println( comboBox.getSelectedItem() );

// make sure popup is closed when 'isTableCellEditor' is used

// comboBox.hidePopup();
}

public static void main(String[] args)
{
ComboBoxAction frame = new ComboBoxAction();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}

关于Java swing下拉选择监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44574901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com