Friday, April 18, 2008


Display Time in JSpinner : Swing Examples

Spinner allow user to select and type the value from a range of values. It has no drop-down list and this reason it is different to combo box. Here is the example to display time in JSpinner and also edit the time :

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class ShowTimeJSpinner{
public static void main(String[] args) {
ShowTimeJSpinner h = new ShowTimeJSpinner();
}

public ShowTimeJSpinner(){
JFrame frame = new JFrame("JSpinner Time Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm");
spinner.setEditor(de);
frame.add(spinner,BorderLayout.NORTH);
frame.setSize(100,100);
frame.setVisible(true);
}
}


Saturday, March 29, 2008


How to Create Combo Box : Java Swing Example

You will learn how to insert combo-box using Swing in Java. Combox box is used display item in drop down list. It provides option to select an item from the drop down. The basic difference between combo box and list box is that user cannot select multiple item from combo-box but it can be possible in list box.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}

public ComboBox(){
String course[] = {"India","Germany","America","Russia"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}