Swing Jcombobox set first element as default selected - java

String[] bookArray={"a","b","c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.setSelectedIndex(0);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb= (JComboBox) e.getSource();
bookNameSelected=(String) cb.getSelectedItem();
System.out.println("book name selected:"+bookNameSelected);
}
});
First element of drop down is shown as default but not passed as default selected value if user does not select any value.

Move bookComboBox.setSelectedIndex(0); after the registration of the ActionListener, this allows the ActionListener to be triggered and sets the bookNameSelected
String[] bookArray = {"a", "b", "c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
bookNameSelected = (String) cb.getSelectedItem();
System.out.println("book name selected:" + bookNameSelected);
}
});
bookComboBox.setSelectedIndex(0);

Related

Return the value from JOptionPane

I have made a JOptionPane which contains a JPanel. The panel contains one button and one Jtable.
JPanel p = atomicAttack.getPanel(); //make the panel and return it
JOptionPane.showOptionDialog(null, p,"Atomic Attacks",
JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,
null, new Object[]{}, null);
and inside the JButton i have:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
selectedId=jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
}
I need to when the user clicks on the button, the JOption get closed and the selectedId get return from the JOptionPane?
I have seen this, but it is not exactly what i am looking for.
Because the button does not return the value for me.
Focus on the models and things will be easier.
public static void main(String[] args) {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Selection", new Object[] { "A", "B", "C" });
JTable table = new JTable(tableModel);
ListSelectionModel selectionModel = table.getSelectionModel();
JPanel p = new JPanel(new BorderLayout());
p.add(table, BorderLayout.CENTER);
int option = JOptionPane.showConfirmDialog(null, p, "Atomic Attacks", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.OK_OPTION == option) {
printSelection(selectionModel, tableModel);
} else {
selectionModel.clearSelection();
}
}
private static void printSelection(ListSelectionModel selectionModel, TableModel tableModel) {
for (int i = selectionModel.getMinSelectionIndex(); i <= selectionModel.getMaxSelectionIndex(); i++) {
if (selectionModel.isSelectedIndex(i)) {
Object selectedValue = tableModel.getValueAt(i, 0);
System.out.println(selectedValue);
}
}
}
If you now select multiple rows
and press the ok button the result will be
A
C
If you want a single selection you can just set
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

making sure JCombo actions only execute on initial selection?

I need to use a JCombo box and at the moment I am just printing messages to screen for testing. When I make a selection it works as expected, however when I then re-click the combo box to change selection I get the same message box before it lets me make another selection. How would I get it so that the action is only performed on initial selection?
String[] positions={"1","2","3","4"};
JComboBox combo = new JComboBox<String>(positions);
combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae ){
//Display selected stuff
JOptionPane.showMessageDialog(null, combo.getSelectedItem());
}
});
Use a boolean to know if it has already been checked or not.
Solution
String[] positions={"1","2","3","4"};
JComboBox combo = new JComboBox<String>(positions);
combo.addActionListener(new ActionListener(){
boolean comboAlreadyChecked = false;
#Override
public void actionPerformed(ActionEvent ae ){
//Display selected stuff
if (!comboAlreadyChecked){
JOptionPane.showMessageDialog(null, combo.getSelectedItem());
comboAlreadyChecked = true;
}
}
});
PS : The name of your boolean may be a little easier than this one. This is just to clarify.
After taking onboard the answers provided and through modifying the solution given in the aforementioned tutorial, I came up with the following solution:
String labels[] = {"", "A", "B", "C", "D", "E", "F"};
JComboBox comboBox = new JComboBox(labels);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
ItemSelectable is = itemEvent.getItemSelectable();
if (selectedString(is) == "A" & state == ItemEvent.SELECTED) {
System.out.println("A");
}
}
};
comboBox.addItemListener(itemListener);
Please try this
public static void main(String args[]) {
JComboBox comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
System.err.println("new item: " + e.getItem());
}
});
}

Trouble with listener in Java. I have a drop down box not passing the users selection like I need

I have a project for class due this Wednesday and am having trouble with a few things: I have two if else statements that control the values presented in two different drop down menus. To me, it appears I'm not getting the information of of the previous drop down(there are two drop downs in which affects the values presented in the next).
Here's my code thus far:
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
int number = Integer.parseInt((String) selection);
if(number>2)
{
style=(style2);
}
else
{
style=(style1);
}
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
roomtype_string=(String) room_type.getSelectedItem();
room_type.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Room Style Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection2 = (String) room_type.getSelectedItem();
if(selection2.equals("Cabin"))
{
room_number=(cabin_string);
}
else
{
room_number=(suite_string);
}
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
roomselected = (String) room_list.getSelectedItem();
room_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection3 = (String) room_list.getSelectedItem();
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
dining_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection4 = (String) dining_list.getSelectedItem();
NOTE: I have since rewritten my code, still no dice:
` //Creates subPanel2 with Occupancy, Room Type, Room, and Dining Time request
JPanel subpanel = new JPanel();
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
Occupancy_Listener occupancy = new Occupancy_Listener();
occupancy_list.addActionListener(occupancy);
//updateStyle(occupancy_string[occupancy_list.getSelectedIndex()]);
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
Style_Listener styleListen = new Style_Listener();
room_type.addActionListener(styleListen);
//updateNumber(style[room_type.getSelectedIndex()]);
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
Room_Listener room = new Room_Listener();
room_list.addActionListener(room);
//updateRoom(room_number[room_list.getSelectedIndex()]);
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
Din_Listener dining = new Din_Listener();
dining_list.addActionListener(dining);
//updateDin(dining_string[dining_list.getSelectedIndex()]);
...
...
...
...
...
}
private class Occupancy_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
System.out.println(selection);
System.out.println(style[0]);
System.out.println(room_number[0]);
updateStyle(selection);
}
}
private class Style_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateNumber(selection);
}
}
private class Room_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateRoom(selection);
}
}
private class Din_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateDin(selection);
}
}
protected void updateStyle(String pick)
{
String[] style1 ={"Cabin", "Suite"};
String[] style2 ={"Suite"};
//ocu_string=pick;
number = Integer.parseInt(pick);
if(number>2)
{
style=style2;
}
else
{
style=style1;
}
}
protected void updateNumber(String pick)
{
String[] cabin_string = {"11-1","11-2","11-3","11-4","11-5","11-6","11-7","11-8","11-9","11-10"};
String[] suite_string = {"11-S1","11-S2"};
type=pick;
if(type.equals("cabin"))
{
room_number=cabin_string;
}
else
{
room_number=suite_string;
}
}
protected void updateRoom(String pick)
{
room_num=pick;
}
protected void updateDin(String pick)
{
din_time=pick;
}
//public String getPopulation()
{
//return ocu_string;
}
This might be what your are asking. You select an item from the first combo box and it populates items in a second combo box:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You may be confused by the fact that code inside anonymous classes (or local classes) is not executed at the same time as the code around it.
So in a code that looks like:
A a = new A();
a.setSomething( new B() {
public void bMethod() {
// Run stuff
}
} );
C c = a.getSomething();
The "Run stuff" part is not ran now. An object is created, with a method that can be used later inside it, and that object is passed into a. The method is not going to run until something specifically calls it. When you get to the getSomething(), the "Run stuff" part has not run.
So in your code:
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
You create the occupancy list, you create an action listener for it, and store that action listener inside your occupancy list. But none of the stuff written inside the actionPerformed() method is going to run until the GUI is displayed, the user selects something, and the event is fired.
GUI programming is different than console programming where you call "scan()" and then the program just stops and waits for something to be entered. You first prepare the GUI, and when you display it, the various listeners are called based on what the user does.
So your code jumps straight to the occupancy_list.getSelectedItem() before the list has even been added to the GUI, and of course, nothing is selected, nothing is displayed, yet, so the other drop-down lists are created way before the user even sees the GUI.
This is true for all the action listeners in the code.
The proper way to write an action listener is to think what will be the conditions when the GUI is already running. Your action listeners merely set values in local variables that are going to be discarded. Instead, they should do the things that you want to do when the user makes a selection, right inside the action listener.
This means that the action listener for this combo box will have to create the other lists and add them to the GUI, revalidate and repaint it. Or it may simply modify the other lists which will be created already, depending on what you think is best. But they will have to access those lists, and therefore the lists have to be defined as fields of the surrounding class, and accessed inside the action listener. Note that you can also define a method that does this and call it from inside the action listener.
My suggestion would be to create a simple GUI first with just the first combo box and make it change something simple based on the selection. You can follow the Oracle Tutorial, for example. After you understand how to write an action listener that changes something simple, expand your program to add the other lists and manipulate them from the action listener.

ComboBox with ActionListener and if-statement

I'm trying to add an ActionListener to my ComboBox. I want to open a form when a item is selected from the box. I successfully implemented it on a JButton but I can't figure out how to do it in a combobox. Can someone please help me out?
JComboBox<String> valBox = new JComboBox<>();
valBox.addItem("Apparat");
valBox.addItem("Smycke");
valBox.addItem("Aktie");
södra.add(valBox);
valBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (valBox.getSelectedIndex() == 0)
nyLyss.ApparatForm.form1();
}
});
The code that I wan't to execute when the first item is selected is this one:
class nyLyss implements ActionListener{
public void actionPerformed(ActionEvent ae) {
try{
ApparatForm form1 = new ApparatForm();
int svar = JOptionPane.showConfirmDialog(Layout.this, form1);
if(svar != JOptionPane.OK_OPTION)
return;
String namn = form1.getNamn();
int inköpspris = form1.getPris();
int slitage = form1.getPris();
// saker ap = new saker(namn, inköpspris, slitage);
// alla.add(ap);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(Layout.this, "Felaktig indata!");
}
}
}
Thanks! :)
I would solve the problem with a ItemStateChanged listener on my combobox. Here a short example with a combobox called "mycombobox".
private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(mycombobox.getSelectedItem());
}
The result is, that the application is printing out the selected item after every change of the selected item in the combobox "mycombobox".

How do I load a JComboBox with values from an Array or ArrayList?

I need to put the following array into a JComboBox and then store the selected value when the "Submit" button is clicked.
listOfDepartments = new String[5];
listOfDepartments[0] = "Mens Clothing";
listOfDepartments[1] = "Womens Clothing";
listOfDepartments[2] = "Childrens Clothing";
listOfDepartments[3] = "Electronics";
listOfDepartments[4] = "Toys";
//Department: ComboBox that loads from array
// Store values
JButton buttonSubmit = new JButton();
buttonSubmit.setText("Submit");
container.add(buttonSubmit);
buttonSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//store value from combobox in a variable
}
});
First, create a model...
DefaultComboBoxModel model = new DefaultComboBoxModel(listOfDepartments);
comboBox.setModel(model);
Second, get the selected value when the actionPerformed event is raised...
String value = (String)comboBox.getSelectedItem();
Take a look at How to Use Combo Boxes for more details.

Categories