gpt4 book ai didi

java - 选择时的组合框

转载 作者:行者123 更新时间:2023-12-01 19:54:58 25 4
gpt4 key购买 nike

我试图在选择一个选项时获取组合框,它会执行诸如打印一些文本之类的操作,但经过数小时的尝试后我不知道该怎么做。我知道它与事件监听器。刚接触java。如有任何帮助,我们将不胜感激。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComboBox;

public class Frame extends JFrame
{
//Instance Variables.
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 400;


public Frame()
{
Venue1();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}

private void Venue1()
{
//String [] Venues = {"Elvis","Gorillaz", "Imagine Dragons","Michael Jackson"};

JComboBox DropMenu = new JComboBox();
DropMenu.addItem("Elvis");
DropMenu.addItem("Gorillaz");
DropMenu.addItem("Imagine Dragons");
DropMenu.addItem("Michael Jackson");
DropMenu.setEditable(false);
DropMenu.setVisible(true);

JPanel panel = new JPanel();
JLabel label = new JLabel("Pick a venue");

add(panel);
panel.add(label);
panel.add(DropMenu);

ActionListener listener = new listener();
DropMenu.addActionListener(listener);

}//End of Venue Method.
}//End of class.

//Button Listeners

class listener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{

}
}

enter code here

最佳答案

  • 要从 JComboBox 中获取选定的值,就这么简单:

DropMenu.getSelectedValue();

  • 更改选择时获取选择:

    MyItemListener actionListener = new MyItemListener();
    DropMenu.addItemListener(actionListener);

    class MyItemListener implements ItemListener {
    // This method is called only if a new item has been selected.
    public void itemStateChanged(ItemEvent evt) {
    JComboBox DropMenu = (JComboBox) evt.getSource();
    Object item = evt.getItem();
    if (evt.getStateChange() == ItemEvent.SELECTED) {
    // Item was just selected
    } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
    // Item is no longer selected
    }
    }
    }

关于java - 选择时的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49919784/

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