If I choose a city FROM: JComboBox
then it shouldn't appear in TO: combo box. How can I code the ActionListener
of this action listener?
public class CityFromTo {
public static void main(String[] args) {
String[] cFrom = {"Choose", "Istanbul", "New York", "London", "Milano", "Tokyo", "Paris", "Moscow", "Elâzığ"};
String[] cTo = {"Choose", "Istanbul", "New York", "London", "Milano", "Tokyo", "Paris", "Moscow", "Elâzığ"};
JLabel from = new JLabel("FROM : ");
JLabel to = new JLabel(" TO : ");
JComboBox comboFrom = new JComboBox(cFrom);
JComboBox comboTo = new JComboBox(cTo);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.add(from);
frame.add(comboFrom);
frame.add(to);
frame.add(comboTo);
frame.setSize(400, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I reworked your code to get away from static. You only need one list of cities for your from and to JComboBoxes
.
You use an ActionListener
to listen for changes in the from JComboBox
, and remove the city from the to JComboBox
. We remove the city by removing all the cities and adding them back, one at a time. This allows the user to change his mind about the from city.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CityFromTo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CityFromTo());
}
private JComboBox<String> comboFrom;
private JComboBox<String> comboTo;
private String[] cities = {"Choose", "Istanbul", "New York", "London",
"Milano", "Tokyo", "Paris", "Moscow", "Elâzığ"};
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.setPreferredSize(new Dimension(400, 350));
JLabel from = new JLabel("FROM : ");
panel.add(from);
comboFrom = new JComboBox<>(cities);
comboFrom.addActionListener(new FromListener());
panel.add(comboFrom);
JLabel to = new JLabel(" TO : ");
panel.add(to);
comboTo = new JComboBox<>(cities);
panel.add(comboTo);
return panel;
}
public class FromListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
String city = (String) comboFrom.getSelectedItem();
comboTo.removeAllItems();
for (String s : cities) {
if (!s.equals(city)) {
comboTo.addItem(s);
}
}
}
}
}