//Using two combo boxes in a GUI screen
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class ComboSampleTwoComboBoxes extends JFrame implements ActionListener
{
private static final int boxW = 800;
private static final int boxH = 450;
private static final int box_X_o = 180;
private static final int box_Y_o = 200;
private JButton cancelButton;
private JButton confirmButton;
private JComboBox jumpStudent;
private JComboBox jumpStudent2;
String[] studentNamesVector = {"a", "b", "c"};
String[] studentNamesVector2 = {"d", "e", "f"};
String n1, n2;
public ComboSampleTwoComboBoxes()
{
setTitle ("Combo sample that can be moved");
setSize (boxW ,boxH);
setLocation (box_X_o , box_Y_o);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.white);
contentPane.setLayout(null);
//---JComboBox---
jumpStudent = new JComboBox(studentNamesVector);
jumpStudent.setBounds(100, 100, 100, 30);
jumpStudent.addActionListener(this);
contentPane.add(jumpStudent);
addToComboBox(); //Add student names to the vector and to the JComboBox
//---JComboBox---
jumpStudent2 = new JComboBox(studentNamesVector2);
jumpStudent2.setBounds(100, 150, 100, 30);
jumpStudent2.addActionListener(this);
contentPane.add(jumpStudent2);
addToComboBox(); //Add student names to the vector and to the JComboBox
confirmButton = new JButton("Confirm");
confirmButton.setBounds(610, 375, 80, 30);
contentPane.add(confirmButton);
confirmButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.setBounds(695, 375, 80, 30);
contentPane.add(cancelButton);
cancelButton.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() instanceof JButton)
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
String dedicationsRaw;
if (buttonText == "Confirm")
{
JOptionPane.showMessageDialog(null, "Nothing to do yet");
}
if (buttonText == "Cancel")
{
this.setVisible(false);
}
}
if(event.getSource() instanceof JComboBox)
{
JComboBox cb = (JComboBox) event.getSource();
String s = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(null, "You picked " + s );
for (int d = 0; d < studentNamesVector.length; d++)
{
if (studentNamesVector[d].equals(s))
{
n1 = s;
}
}
for (int d = 0; d < studentNamesVector.length; d++)
{
if (studentNamesVector2[d].equals(s))
{
n2 = s;
}
}
}
System.out.println(n1 + ", " + n2);
}
public void addToComboBox()
{
}
public static void main(String[] args)
{
ComboSampleTwoComboBoxes frame = new ComboSampleTwoComboBoxes();
frame.setVisible(true);
}
}