#JComboBox help with making a drop down menu

1 messages · Page 1 of 1 (latest)

warm mural
#

import javax.swing.;
import java.awt.
;
import java.awt.event.*;

public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");

    JPanel panel = new JPanel();

    JComboBox<String> comboBox = new JComboBox<>(new String[] { "1", "2", "3" });

    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String selectedOption = (String) comboBox.getSelectedItem();
            System.out.println("You selected: " + selectedOption);
            comboBox.setSelectedItem("1");
        }
    });

    panel.add(comboBox);

    frame.add(panel);

    frame.setSize(300, 150);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

This is just some basic code that displays a JComboBox with an array of strings 1,2,3. What ive been trying to figure out is a way so that the combobox has a title of anything, like Test. My goal is that normally when you use a drop box on a website it has a title that then displays some options like a list, like the image i attatched. How can i make this work with comboboxes or with something else?

quick wigeonBOT
#

<@&987246487241105418> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

ew JFrame("JComboBox Example");

    String[] options = {"Option 1", "Option 2", "Option 3", "Option 4"};

    JComboBox<String> comboBox = new JComboBox<>(options);
    comboBox.setSelectedIndex(0);

    JButton button = new JButton("Get Selected Option");

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String selectedOption = (String) comboBox.getSelectedItem();
            JOptionPane.showMessageDialog(frame, "Selected Option: " + selectedOption);
        }
    });

    JPanel panel = new JPanel();
    panel.add(comboBox);
    panel.add(button);

    frame.add(panel);
    
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setVisible(true);
}

}