How to sort combo box alphabetically AZ Here is the code tha
How to sort combo box alphabetically? A-Z
Here is the code that I have:
CityGui
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CityGui extends JFrame {
private JTextField inputField;
private JButton readButton;
private JLabel inputLabel;
private JLabel spacer;
private JLabel selectCity;
private JComboBox<City> cityCombobox;
private JLabel stateLabel = new JLabel();
private JLabel zipLabel = new JLabel();
private JLabel tzLabel = new JLabel();
private Component topPanel;
private JLabel fileReadLabel;
public static void main(String [] args){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new CityGui();
}
});
}
public CityGui() throws HeadlessException {
super(\"Cities\");
setLayout(new BorderLayout());
add(getTopPanel(), BorderLayout.NORTH);
add(getCenterPanel(), BorderLayout.CENTER);
add(getSouthPanel(), BorderLayout.SOUTH);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public JPanel getCenterPanel() {
JPanel jpanel = new JPanel();
jpanel.setLayout(new GridLayout(4, 2, 10, 20));
Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
jpanel.setBorder(padding);
inputField = new JTextField(\"Enter City Information File Path Here\");
readButton = new JButton(\"Read\");
inputLabel = new JLabel(\"Input File\");
spacer = new JLabel(\"\");
fileReadLabel = new JLabel(\"\");
fileReadLabel.setForeground(Color.GREEN);
selectCity = new JLabel(\"Select City\");
cityCombobox = new JComboBox<>();
jpanel.add(inputField);
jpanel.add(readButton);
jpanel.add(inputLabel);
jpanel.add(spacer);
jpanel.add(fileReadLabel);
jpanel.add(new JLabel(\"\"));
jpanel.add(selectCity);
jpanel.add(cityCombobox);
readButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
readCityFile();
}
});
cityCombobox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
updateCity((City) cityCombobox.getSelectedItem());
}
});
return jpanel;
}
private void updateCity(final City selectedItem) {
selectCity.setText(selectedItem.cityName);
stateLabel.setText(selectedItem.state);
zipLabel.setText(Integer.toString(selectedItem.zipcode));
switch (selectedItem.timezone){
case -4:
tzLabel.setText(\"AST\");
break;
case -5:
tzLabel.setText(\"EST\");
break;
case -6:
tzLabel.setText(\"CST\");
break;
case -7:
tzLabel.setText(\"MST\");
break;
case -8:
tzLabel.setText(\"PST\");
break;
case -9:
tzLabel.setText(\"AKST\");
break;
case -10:
tzLabel.setText(\"HST\");
break;
default:
tzLabel.setText(\"No Time Zone Information\");
}
}
public JPanel getSouthPanel() {
JPanel jpanel = new JPanel();
jpanel.setLayout(new GridLayout(3, 2, 20, 20));
Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
jpanel.setBorder(padding);
jpanel.add(new JLabel(\"State:\"));
jpanel.add(stateLabel);
jpanel.add(new JLabel(\"Zip Code:\"));
jpanel.add(zipLabel);
jpanel.add(new JLabel(\"Time Zone:\"));
jpanel.add(tzLabel);
return jpanel;
}
public JPanel getTopPanel() {
JPanel jPanel = new JPanel(new FlowLayout());
Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
jPanel.setBorder(padding);
jPanel.add(new JLabel(\"City Information\"));
return jPanel;
}
public void readCityFile(){
CityGroup cityGroup = new CityGroup();
File file = new File(inputField.getText());
if(!file.exists()){
JOptionPane.showMessageDialog(this, \"The file doesn\'t exist!\", \"Error\", JOptionPane.ERROR_MESSAGE);
return;
/**
* this is the File does not exist compare
* @return ErrorMessage
*/
}
try {
Scanner scanner = new Scanner(file);
scanner.next();
while(scanner.hasNext()){
String line = scanner.nextLine();
Scanner delimeter = new Scanner(line);
delimeter.useDelimiter(\",\");
while(delimeter.hasNext()){
int zip=delimeter.nextInt();
String cName=delimeter.next();
String state=delimeter.next();
double lat=delimeter.nextDouble();
double lon=delimeter.nextDouble();
int zone=delimeter.nextInt();
boolean yesDay=false;
String daylightStr=delimeter.nextLine();
if(daylightStr.charAt(1)==\'1\')
yesDay=true;
City temp=new City(zip,cName,state,lat,lon,zone,yesDay);
cityGroup.addCity(temp);
}
}
} catch (InputMismatchException | FileNotFoundException e) {
JOptionPane.showMessageDialog(this, \"Error while reading the file\", \"Error\", JOptionPane.ERROR_MESSAGE);
return;
/**
* this is the InputMismatchException
* @return FileNotFoundException
*/
}
DefaultComboBoxModel<City> defaultComboBoxModel = new DefaultComboBoxModel<>();
for(City city : cityGroup.cityArray){
defaultComboBoxModel.addElement(city);
}
this.cityCombobox.setModel(defaultComboBoxModel);
this.fileReadLabel.setText(\"The cities have been read\");
updateCity((City) cityCombobox.getSelectedItem());
}
}
public class City
{
/**
* this is main city class
* @return City
*/
int zipcode;
String cityName;
String state;
double latitude;
double longitude;
int timezone;
boolean yesDaylight;
public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight)
{
/**
* this is constructor for City
* @return City()
*/
zipcode = zip;
cityName = cName;
state = st;
latitude = lat;
longitude = lon;
timezone = zone;
yesDaylight = daylight;
}
public String toString()
{
/**
* this is the toString class
* @return cityName + \",\" state;
*/
return cityName;
}
public int compareTo (City otherCity)
{
/**
* this is compareTo class to compare
* @return compareTo;
*/
if (otherCity.latitude == latitude)
return 0;
else if (latitude > otherCity.latitude)
return 1;
else
return -1;
}
}
public class CityGroup
{
/**
* this is main citygroup class
* @return CityGroup
*/
City[] cityArray=new City[100];
int numCities;
public CityGroup()
{
/**
* this sets cities to 0;
* @return numCities
*/
numCities=0;
}
public void addCity(City newCity)
{
/**
* this is returns the cityarray after its added
* @return cityArray[]
*/
cityArray[numCities]=newCity;
numCities++;
}
City findNorthMost()
{
City noa =cityArray[0];
for(int counter=0;counter<numCities;counter++)
{
if(cityArray[counter].compareTo(noa)==1)
noa=cityArray[counter];
}
return noa;
}
}
CityData 2:
Solution
package combo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
public class CityGui extends javax.swing.JFrame {
private CityGroup cityGroup;
/** Creates new form CityGu */
public CityGui() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings(\"unchecked\")
// <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
inputField = new javax.swing.JTextField();
selectCity = new javax.swing.JLabel();
cityCombobox = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
state = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
zipcode = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
timeZone = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText(\"City Information\");
jButton1.setText(\"Read\");
jButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
try {
readCityFile();
} catch (Exception ex) {
}
}
});
jLabel2.setText(\"Input File:\");
inputField.setEditable(false);
selectCity.setText(\"Select City:\");
cityCombobox=new JComboBox<>();
cityCombobox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
updateCity((String) cityCombobox.getSelectedItem());
}
});
jLabel4.setText(\"State:\");
state.setEditable(false);
jLabel5.setText(\"Zip Code:\");
zipcode.setEditable(false);
jLabel6.setText(\"Time Zone:\");
timeZone.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(140, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(182, 182, 182))
.addGroup(layout.createSequentialGroup()
.addGap(149, 149, 149)
.addComponent(jButton1)
.addContainerGap(136, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(selectCity)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(state, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cityCombobox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(inputField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
.addComponent(zipcode, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(timeZone, javax.swing.GroupLayout.Alignment.LEADING))
.addContainerGap(54, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(inputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(selectCity)
.addComponent(cityCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(zipcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(timeZone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate=\"collapsed\" desc=\" Look and feel setting code (optional) \">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (\"Nimbus\".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CityGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CityGui().setVisible(true);
}
});
}
public void readCityFile() throws Exception{
cityGroup = new CityGroup();
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogTitle(\"Choose Directories\");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
inputField.setText(chooser.getSelectedFile().getAbsolutePath());
inputField.setEditable(false);
}
BufferedReader br = new BufferedReader (new FileReader(inputField.getText()));
String line = br.readLine();
int c=0;
String cities=\"\";
while(line != null){
String inp[]=line.split(\",\");
int zip=Integer.parseInt(inp[0]);
String cName=inp[1];
cities=cities+\",\"+cName;
String st=inp[2];
double lat=Double.parseDouble(inp[3]);
double lon=Double.parseDouble(inp[4]);
int zone=Integer.parseInt(inp[5]);
boolean yesDay=false;
int daylightStr=Integer.parseInt(inp[6]);
if(daylightStr == 1)
yesDay=true;
City temp=new City(zip,cName,st,lat,lon,zone,yesDay);
cityGroup.addCity(temp);
line=br.readLine();
}
cities=cities.substring(1);
String allcities[]=cities.split(\",\");
Arrays.sort(allcities);
this.cityCombobox.setModel(new DefaultComboBoxModel(allcities));
updateCity((String)cityCombobox.getSelectedItem());
}
private void updateCity(String selectedItem) {
for(int i=0;i<cityGroup.numCities;i++)
{
if(cityGroup.cityArray[i].cityName.equals(selectedItem))
{
state.setText(cityGroup.cityArray[i].state);
zipcode.setText(Integer.toString(cityGroup.cityArray[i].zipcode));
switch (cityGroup.cityArray[i].timezone){
case -4:
timeZone.setText(\"AST\");
break;
case -5:
timeZone.setText(\"EST\");
break;
case -6:
timeZone.setText(\"CST\");
break;
case -7:
timeZone.setText(\"MST\");
break;
case -8:
timeZone.setText(\"PST\");
break;
case -9:
timeZone.setText(\"AKST\");
break;
case -10:
timeZone.setText(\"HST\");
break;
default:
timeZone.setText(\"No Time Zone Information\");
}
}
}
}
// Variables declaration - do not modify
private javax.swing.JComboBox cityCombobox;
private javax.swing.JTextField inputField;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel selectCity;
private javax.swing.JTextField state;
private javax.swing.JTextField timeZone;
private javax.swing.JTextField zipcode;
// End of variables declaration
}
---------------------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package combo;
/**
*
* @author Gojkid
*/
public class CityGroup
{
/**
* this is main citygroup class
* @return CityGroup
*/
City[] cityArray=new City[100];
int numCities;
public CityGroup()
{
/**
* this sets cities to 0;
* @return numCities
*/
numCities=0;
}
public void addCity(City newCity)
{
/**
* this is returns the cityarray after its added
* @return cityArray[]
*/
if(numCities<100)
cityArray[numCities]=newCity;
numCities++;
}
City findNorthMost()
{
City noa =cityArray[0];
for(int counter=0;counter<numCities;counter++)
{
if(cityArray[counter].compareTo(noa)==1)
noa=cityArray[counter];
}
return noa;
}
public String toString() {
String ret=\"\";
for(int i=0;i<this.numCities;i++)
ret=ret+\" \"+cityArray[i].toString();
return ret;
}
}
---------------------------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package combo;
/**
*
* @author Gojkid
*/
public class City
{
/**
* this is main city class
* @return City
*/
int zipcode;
String cityName;
String state;
double latitude;
double longitude;
int timezone;
boolean yesDaylight;
public City (int zip, String cName, String st, double lat, double lon, int zone, boolean daylight)
{
/**
* this is constructor for City
* @return City()
*/
zipcode = zip;
cityName = cName;
state = st;
latitude = lat;
longitude = lon;
timezone = zone;
yesDaylight = daylight;
}
public String toString() {
return cityName;
}
public int compareTo (City otherCity)
{
/**
* this is compareTo class to compare
* @return compareTo;
*/
if (otherCity.latitude == latitude)
return 0;
else if (latitude > otherCity.latitude)
return 1;
else
return -1;
}
}











