Friday 21 February 2014

Java: Display year in a JComboBox

A short example program will compute next 10 years and will display it in a JComboBox

public class JComboBoxExample
{
private JPanel getPanel()
{
JPanel p = new JPanel(new FlowLayout());
JComboBox<String> yearsCbx = new JComboBox<String>();
String[] years = getNextTenYears();
yearsCbx.setModel(new javax.swing.DefaultComboBoxModel<String>(years));

JLabel yearLbl = new JLabel("Select Year");
p.add(yearLbl);
p.add(yearsCbx);

return p;
}

public void createAndShowGUI()
{
JFrame frame = new JFrame("JComoBox Example");
frame.setMinimumSize(new Dimension(500, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(getPanel());
// Display the window.
frame.pack();
frame.setVisible(true);
}

private String[] getNextTenYears()
{
String[] years = new String[10];
Calendar cal = Calendar.getInstance();
int thisYear = cal.get(Calendar.YEAR);
for (int i = 0; i < years.length; i++)
years[i] = Integer.toString(thisYear + i);

return years;
}
}

And the Driver program

public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JComboBoxExample cbx = new JComboBoxExample();
cbx.createAndShowGUI();
}
});
}
}


And here is the output from the program


1 comment:

  1. Thank you very much for your code!

    It came in very handy with the project I am doing at college.

    ReplyDelete