JComboBox对象在java中用于JButton [关闭]

问题描述 投票:0回答:1

enter image description here我想在JButton中使用JComboBox对象,如果我从JComboBox中选择所需的文本并单击按钮图像会出现,是否可能,需要帮助,因为我甚至无法在JButton中制作JCommbo的对象。 enter image description here

java netbeans jbutton jcombobox
1个回答
0
投票

您必须从JComomboBox访问ActionListener才能获得所选文本。您还需要使用正确的方法来获取所选文本,例如JComboBox#getSelectedItem()。考虑这个例子:

JComboBox<String> myComobBox = new JComboBox<String>();
JButton myButton =  new JButton("jButton");
myComboBox.addItem("6.A.M");
// Add button listener
myButton.addActionListener(e -> {
    // Use getSelectedItem instead of getText
    if(((String) myComboBox.getSelectedItem) == "6.A.M") {
         SixAMRoute sam = new SixAMRoute();
         sam.setVisible(true);
         this.dispose();
    }
});

如果您希望您的动作侦听器成为它自己的类,则需要使用access modifiers来使侦听器可以访问JComboBox。

© www.soinside.com 2019 - 2024. All rights reserved.