How to Scatter JComboBox ?

Hi, i am working on a simple example to learn the Swing API. I have a small program that uses 6 different combo boxes. there should be 2 sets of 3 Combo boxes (day, month, year). My problem is that I cannot seem to get them to seperate. They always line up right next to each other. I posted some code below. sorry the tabbing is a bit screwy. if you paste it to an editor it will make more sense. anyways, i use 2 different jpanels, with a GridLayout of only one column (inserting Jpanels into a gridlayout of only 1 column), but still it aligns them together on the same line! i can't figure it out. any help will be appreciated. thanks
ps-you should be able to just cut and paste this code and compile if you want to see what i mean.
import javax.swing.*;
import java.awt.*;
import java.lang.*;
public class DateFinder {
     public static void main(String[] args) {
          JFrame           myFrame           = new JFrame("How many days since your birthday?");
          Container      myContentPane      = myFrame.getContentPane();
          JPanel           buttonPanel      = new JPanel(new GridLayout(1,2));
          JPanel          comboPanel          = new JPanel(new GridLayout(1,4));
          JPanel          comboPanel1          = new JPanel(new GridLayout(1,4));
          JPanel          rootPanel          = new JPanel(new GridLayout(8,1));
          JButton      Calculate           = new JButton("Calculate");
          JButton          Reset               = new JButton("Reset");
          JLabel          yourBday          = new JLabel("Your Birthday");
          JLabel          Today               = new JLabel("Today");
          int           yearCounter          = 0;
          int           i;
          String[]     DaysList          = {"1","2","3","4","5","6","7","8","9","10",
                                             "11","12","13","14","15","16","17","18",
                                             "19","20","21","22","23","24","25","26",
                                             "27","28","29","30","31"};
          String[]     MonthsList          = {"January","February","March","April","May",
                                             "June","July","August","September","October",
                                             "November","December"};
          String[] YearsList = new String[120];
          for(i=0;i<120;i++) {
               YearsList[i] = String.valueOf(2005 - i);
          }//end for
JComboBox DaysCombo     = new JComboBox(DaysList);
JComboBox MonthsCombo     = new JComboBox(MonthsList);
JComboBox YearsCombo     = new JComboBox(YearsList);
JComboBox DaysCombo1     = new JComboBox(DaysList);
JComboBox MonthsCombo1= new JComboBox(MonthsList);
JComboBox YearsCombo1     = new JComboBox(YearsList);
          buttonPanel.add(Calculate);
          buttonPanel.add(Reset);
          comboPanel.add(yourBday);
          comboPanel.add(DaysCombo);
          comboPanel.add(MonthsCombo);
          comboPanel.add(YearsCombo);
          comboPanel1.add(Today);
          comboPanel1.add(DaysCombo1);
          comboPanel1.add(MonthsCombo1);
          comboPanel1.add(YearsCombo1);
          rootPanel.add(comboPanel);
          rootPanel.add(comboPanel1);
          rootPanel.add(buttonPanel);
          comboPanel.add(DaysCombo1);
          comboPanel.add(MonthsCombo1);
          comboPanel.add(YearsCombo1);
          myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          myContentPane.add(rootPanel);
          //myContentPane.add(buttonPanel, BorderLayout.SOUTH);
          //myContentPane.add(comboPanel, BorderLayout.EAST);
          //myContentPane.add(comboPanel1,BorderLayout.NORTH);
          myFrame.setSize(500,200);
          myFrame.setVisible(true);
     }//end main
}//end class definition

OK.. I guess I now understood your problem and debugged ur code...
You have three lines of unnecessary code. (Repeated twice).
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Temp {
     public static void main(String[] args) {
          JFrame myFrame = new JFrame("How many days since your birthday?");
          Container myContentPane = myFrame.getContentPane();
          JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
          JPanel comboPanel = new JPanel(new GridLayout(1, 4));
          JPanel comboPanel1 = new JPanel(new GridLayout(1, 4));
          JPanel rootPanel = new JPanel(new GridLayout(3, 1));
          JButton Calculate = new JButton("Calculate");
          JButton Reset = new JButton("Reset");
          JLabel yourBday = new JLabel("Your Birthday");
          JLabel Today = new JLabel("Today");
          int yearCounter = 0;
          int i;
          String[] DaysList =
                    "1",
                    "2",
                    "3",
                    "4",
                    "5",
                    "6",
                    "7",
                    "8",
                    "9",
                    "10",
                    "11",
                    "12",
                    "13",
                    "14",
                    "15",
                    "16",
                    "17",
                    "18",
                    "19",
                    "20",
                    "21",
                    "22",
                    "23",
                    "24",
                    "25",
                    "26",
                    "27",
                    "28",
                    "29",
                    "30",
                    "31" };
          String[] MonthsList =
                    "January",
                    "February",
                    "March",
                    "April",
                    "May",
                    "June",
                    "July",
                    "August",
                    "September",
                    "October",
                    "November",
                    "December" };
          String[] YearsList = new String[120];
          for (i = 0; i < 120; i++) {
               YearsList = String.valueOf(2005 - i);
          } //end for
          JComboBox DaysCombo = new JComboBox(DaysList);
          JComboBox MonthsCombo = new JComboBox(MonthsList);
          JComboBox YearsCombo = new JComboBox(YearsList);
          JComboBox DaysCombo1 = new JComboBox(DaysList);
          JComboBox MonthsCombo1 = new JComboBox(MonthsList);
          JComboBox YearsCombo1 = new JComboBox(YearsList);
          buttonPanel.add(Calculate);
          buttonPanel.add(Reset);
          comboPanel.add(yourBday);
          comboPanel.add(DaysCombo);
          comboPanel.add(MonthsCombo);
          comboPanel.add(YearsCombo);
          comboPanel1.add(Today);
          comboPanel1.add(DaysCombo1);
          comboPanel1.add(MonthsCombo1);
          comboPanel1.add(YearsCombo1);
          rootPanel.add(comboPanel);
          rootPanel.add(comboPanel1);
          rootPanel.add(buttonPanel);
          //YOU DO NOT NEED THE FOLLOWING THREE LINES.
//          comboPanel.add(DaysCombo1);
//          comboPanel.add(MonthsCombo1);
//          comboPanel.add(YearsCombo1);
          myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          myContentPane.add(rootPanel, BorderLayout.CENTER);
          //myContentPane.add(buttonPanel, BorderLayout.SOUTH);
          //myContentPane.add(comboPanel, BorderLayout.EAST);
          //myContentPane.add(comboPanel1,BorderLayout.NORTH);
          myFrame.setSize(500, 200);
          myFrame.setVisible(true);
     } //end main
} //end class definition
Run this progam and I guess you will see what you have been wanting to.
Sai Pullabhotla.

Similar Messages

  • How to store JcomboBox n textfield into textfile? Urgent!!!

    How to store JcomboBox n textfield into textfile?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    import java.io.*;
    public class RecordMenu extends JPanel implements ActionListener {
        private JComboBox monthSelection;
        private JButton buttonOk;
        double amtToTrack;
        private JTextField amtField;
        private static final String[] Months =
         new String[] {
             "January",
             "February",
             "March",
             "April",
             "May",
             "June",
             "July",
             "August",
             "September",
             "October",
             "November",
             "December"
        public RecordMenu() {      
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new GridLayout(4,2));
            mainPanel.setBorder(new TitledBorder("Record Expenses"));
            JLabel monthLabel = new JLabel("Select month");      
            monthSelection = new JComboBox(Months);      
            monthSelection.addActionListener(this);
            JLabel label2 = new JLabel("Amount to track:");       
            JTextField amtField = new JTextField(5);
            amtField.addActionListener(this);
            JLabel nothing1 = new JLabel("nothing");
            nothing1.setVisible(false);
            JLabel nothing2 = new JLabel("nothing");
            nothing2.setVisible(false);
            JLabel nothing3 = new JLabel("nothing");
            nothing3.setVisible(false);
            JLabel nothing4 = new JLabel("nothing");
            nothing4.setVisible(false);
            JLabel nothing5 = new JLabel("nothing");
            nothing5.setVisible(false);
            JLabel nothing6 = new JLabel("nothing");
            nothing6.setVisible(false);
            JLabel nothing7 = new JLabel("nothing");
            nothing7.setVisible(false);
            JLabel nothing8 = new JLabel("nothing");
            nothing8.setVisible(false);
            mainPanel.add(monthLabel);
            mainPanel.add(monthSelection);
            mainPanel.add(nothing1); 
            mainPanel.add(label2);
            mainPanel.add(amtField);
            mainPanel.add(nothing2);
            mainPanel.add(nothing3);
            mainPanel.add(nothing4);
            mainPanel.add(nothing5);
            mainPanel.add(nothing6);
            mainPanel.add(nothing7);
            JButton buttonOk = new JButton("OK");     
            buttonOk.addActionListener(this);
            mainPanel.add(buttonOk);
            add(mainPanel);      
            setSize(400,300);
            setVisible(true);
        public void actionPerformed(ActionEvent e) {                
             if (e.getSource() == buttonOk) {
             double amtToTrack = 0.0;
             try {
             if (!amtField.getText().equals(""))
                   amtToTrack = Double.parseDouble(amtField.getText());
             catch (NumberFormatException numberFormatException) {
                  JOptionPane.showMessageDialog(this, "You must enter numbers","Invalid Number Format", JOptionPane.ERROR_MESSAGE);
                         try{               
                             BufferedWriter out = new BufferedWriter(new FileWriter("mySaved.txt",true));
                             out.write("For Month "+Months);
                             out.newLine();
                             if (!amtField.getText().equals("")) {     
                             amtToTrack = Double.parseDouble(amtField.getText());
                             out.write("Amount to track = "+amtToTrack);   
                             out.newLine();     
                             out.close();
                             JOptionPane.showMessageDialog(this, "Saved!");                         
                            catch(IOException ex) {   
                            ex.printStackTrace(System.err);
        public static void main(String[] args) {
            JPanel p = new RecordMenu();
            JFrame f = new JFrame();
            Container c = f.getContentPane();
            c.add(p);
            f.pack();
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              f.setVisible(true);
    }

    i had save e month at mySavedTotal
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    import java.io.*;
    public class RecordMenu extends JPanel implements ActionListener {
        private JComboBox monthSelection;
        private JButton buttonOk;
        double amtToTrack;
        private JTextField amtField;
        private static final String[] Months =
         new String[] {
             "January",
             "February",
             "March",
             "April",
             "May",
             "June",
             "July",
             "August",
             "September",
             "October",
             "November",
             "December"
        public RecordMenu() {      
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new GridLayout(4,2));
            mainPanel.setBorder(new TitledBorder("Record Expenses"));
            JLabel monthLabel = new JLabel("Select month");      
            monthSelection = new JComboBox(Months);      
            monthSelection.addActionListener(this);
            JLabel label2 = new JLabel("Amount to track:");       
            amtField = new JTextField(5);
            amtField.addActionListener(this);
            JLabel nothing1 = new JLabel("nothing");
            nothing1.setVisible(false);
            JLabel nothing2 = new JLabel("nothing");
            nothing2.setVisible(false);
            JLabel nothing3 = new JLabel("nothing");
            nothing3.setVisible(false);
            JLabel nothing4 = new JLabel("nothing");
            nothing4.setVisible(false);
            JLabel nothing5 = new JLabel("nothing");
            nothing5.setVisible(false);
            JLabel nothing6 = new JLabel("nothing");
            nothing6.setVisible(false);
            JLabel nothing7 = new JLabel("nothing");
            nothing7.setVisible(false);
            JLabel nothing8 = new JLabel("nothing");
            nothing8.setVisible(false);
            mainPanel.add(monthLabel);
            mainPanel.add(monthSelection);
            mainPanel.add(nothing1); 
            mainPanel.add(label2);
            mainPanel.add(amtField);
            mainPanel.add(nothing2);
            mainPanel.add(nothing3);
            mainPanel.add(nothing4);
            mainPanel.add(nothing5);
            mainPanel.add(nothing6);
            mainPanel.add(nothing7);
            buttonOk = new JButton("OK");     
            buttonOk.addActionListener(this);
            mainPanel.add(buttonOk);
            add(mainPanel);      
            setSize(400,300);
            setVisible(true);
        public void actionPerformed(ActionEvent e) {                
             if (e.getSource() == buttonOk) {
             double amtToTrack = 0.0;
             try {
             if (!amtField.getText().equals(""))
                   amtToTrack = Double.parseDouble(amtField.getText());
             catch (NumberFormatException numberFormatException) {
                  JOptionPane.showMessageDialog(this, "You must enter numbers","Invalid Number Format", JOptionPane.ERROR_MESSAGE);
                         try{               
                             BufferedWriter out = new BufferedWriter(new FileWriter("mySavedTotal.txt",true));
                             out.write("For Month "+monthSelection.getSelectedItem());
                             out.newLine();
                             if (!amtField.getText().equals("")) {     
                             amtToTrack = Double.parseDouble(amtField.getText());
                             out.write("Amount to track = "+amtToTrack);   
                             out.newLine();     
                             out.close();
                             JOptionPane.showMessageDialog(this, "Saved!");
                             JPanel p = new CheckBox();         
                             JFrame f = new JFrame();         
                             Container c = f.getContentPane();         
                             c.add(p);         
                             f.pack();         
                             f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);         
                             f.setVisible(true);                              
                            catch(IOException ex) {   
                            ex.printStackTrace(System.err);
        public static void main(String[] args) {
            JPanel p = new RecordMenu();
            JFrame f = new JFrame();
            Container c = f.getContentPane();
            c.add(p);
            f.pack();
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              f.setVisible(true);
    }then i save data from other file in mySavedTotal again
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    import java.io.*;
    public class CheckBox extends JPanel implements ItemListener, ActionListener {
         private JPanel checkPanel, buttonPanel;
         private JCheckBox transport, bills, food, gifts, leisure, others;
         private JTextField transportField, billsField, foodField, giftsField,leisureField,
                        othersField, totalField;
         double transportAmt, billsAmt, foodAmt, giftsAmt, leisureAmt, othersAmt, totalAmt;
         private JButton buttonTotal, saveButton, dontSaveButton;
         private JLabel showTotal;
         public CheckBox() {          
              //create a panel for diaplaying the checkboxs and buttons
              checkPanel = new JPanel();
              checkPanel.setLayout(new GridLayout(7,3));
              //Create the check boxes.
              transport = new JCheckBox("Transport");
              transport.setSelected(false);
              transport.setBounds(10,30,80,30);
              transportField = new JTextField();
              transportField.setEditable(false);
              transportField.setBounds(100,35,45,20);
              bills = new JCheckBox("Bills");
              bills.setSelected(false);
              bills.setBounds(10,60,80,30);
              billsField = new JTextField(5);
              billsField.setEditable(false);
              billsField.setBounds(100,65,45,20);
              food = new JCheckBox("Food");
              food.setSelected(false);
              food.setBounds(10,90,80,30);
              foodField = new JTextField(5);
              foodField.setEditable(false);
              foodField.setBounds(100,95,45,20);
              gifts = new JCheckBox("Gifts");
              gifts.setSelected(false);
              gifts.setBounds(200,30,80,30);
              giftsField = new JTextField(5);
              giftsField.setEditable(false);
              giftsField.setBounds(300,35,45,20);
              leisure = new JCheckBox("Leisure");
              leisure.setSelected(false);
              leisure.setBounds(200,60,80,30);
              leisureField = new JTextField(5);
              leisureField.setEditable(false);
              leisureField.setBounds(300,65,45,20);
              others = new JCheckBox("Others");
              others.setSelected(false);
              others.setBounds(200,90,80,30);
              othersField = new JTextField(5);
              othersField.setEditable(false);
              othersField.setBounds(300,95,45,20);
              JLabel nothing1 = new JLabel("nothing");
            nothing1.setVisible(false);
            JLabel nothing2 = new JLabel("nothing");
            nothing2.setVisible(false);
            JLabel nothing3 = new JLabel("nothing");
            nothing3.setVisible(false);
            JLabel nothing4 = new JLabel("nothing");
            nothing4.setVisible(false);
            JLabel nothing5 = new JLabel("nothing");
            nothing5.setVisible(false);
            JLabel nothing6 = new JLabel("nothing");
            nothing6.setVisible(false);
            JLabel nothing7 = new JLabel("nothing");
            nothing7.setVisible(false);
            JLabel nothing8 = new JLabel("nothing");
            nothing8.setVisible(false);
            JLabel nothing9 = new JLabel("nothing");
            nothing9.setVisible(false);
            JLabel nothing10 = new JLabel("nothing");
            nothing10.setVisible(false);
            JLabel nothing11 = new JLabel("nothing");
            nothing11.setVisible(false);
              //Register a listener for the check boxes.
              transport.addItemListener(this);
              bills.addItemListener(this);
              food.addItemListener(this);
              gifts.addItemListener(this);
              leisure.addItemListener(this);
              others.addItemListener(this);
              transportField.addActionListener(this);
              billsField.addActionListener(this);
              foodField.addActionListener(this);
              giftsField.addActionListener(this);
              leisureField.addActionListener(this);
              othersField.addActionListener(this);
              checkPanel.add(transport);
              checkPanel.add(transportField);
              checkPanel.add(bills);
              checkPanel.add(billsField);
              checkPanel.add(food);
              checkPanel.add(foodField);
              checkPanel.add(gifts);
              checkPanel.add(giftsField);
              checkPanel.add(leisure);
              checkPanel.add(leisureField);
              checkPanel.add(others);
              checkPanel.add(othersField);
              checkPanel.setBounds(1,1,390,180);
              checkPanel.setBorder(new TitledBorder("Check the amount you want to track"));
              buttonTotal = new JButton("Calculate Total");
              buttonTotal.setBounds(150,140,130,30);
              buttonTotal.addActionListener(this);
              showTotal = new JLabel(" = __");
              showTotal.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              showTotal.setBounds(290,140,100,30);
              checkPanel.add(nothing1);
              checkPanel.add(nothing2);
              checkPanel.add(nothing3);
              checkPanel.add(nothing4);
              checkPanel.add(nothing5);
              checkPanel.add(nothing6);
              checkPanel.add(buttonTotal);
              checkPanel.add(showTotal);
              checkPanel.add(nothing7);
              checkPanel.add(nothing8);
              checkPanel.add(nothing9);
              checkPanel.add(nothing10);
              checkPanel.add(nothing11);
              saveButton = new JButton("Save");
              saveButton.setBounds(90,190,100,30);
              saveButton.addActionListener(this);
              dontSaveButton = new JButton("Don't Save");
              dontSaveButton.setBounds(200,190,100,30);
              dontSaveButton.addActionListener(this);
              checkPanel.add(saveButton);
             checkPanel.add(dontSaveButton);
            add(checkPanel);       
              setSize(400,260);
              setVisible(true);
              /** Listens to the check boxes. */
              public void itemStateChanged(ItemEvent e) {
              if (e.getSource() == transport)
              if (e.getStateChange() == ItemEvent.SELECTED)          
              transportField.setEditable(true);
              else
              transportField.setEditable(false);
              if (e.getSource() == bills)
              if (e.getStateChange() == ItemEvent.SELECTED)
              billsField.setEditable(true);
              else
              billsField.setEditable(false);
              if (e.getSource() == food)
              if (e.getStateChange() == ItemEvent.SELECTED)
              foodField.setEditable(true);
              else
              foodField.setEditable(false);
              if (e.getSource() == gifts)
              if (e.getStateChange() == ItemEvent.SELECTED)
              giftsField.setEditable(true);
              else
              giftsField.setEditable(false);
              if (e.getSource() == leisure)
              if (e.getStateChange() == ItemEvent.SELECTED)
              leisureField.setEditable(true);
              else
              leisureField.setEditable(false);
              if (e.getSource() == others)
              if (e.getStateChange() == ItemEvent.SELECTED)
              othersField.setEditable(true);
              else
              othersField.setEditable(false);
              public void actionPerformed(ActionEvent event) {
              try {     
             if (event.getSource() == buttonTotal) {
                  double transportAmt=0.0, billsAmt=0.0, foodAmt=0.0, giftsAmt=0.0,leisureAmt=0.0, othersAmt=0.0, totalAmt=0.0;
                   if (!transportField.getText().equals(""))
                   transportAmt = Double.parseDouble(transportField.getText());
                   if(!billsField.getText().equals(""))
                   billsAmt = Double.parseDouble(billsField.getText());
                   if(!foodField.getText().equals(""))
                   foodAmt = Double.parseDouble(foodField.getText());
                   if(!giftsField.getText().equals(""))
                   giftsAmt = Double.parseDouble(giftsField.getText());
                   if(!leisureField.getText().equals(""))
                   leisureAmt = Double.parseDouble(leisureField.getText());
                   if(!othersField.getText().equals(""))
                   othersAmt = Double.parseDouble(othersField.getText());
                   totalAmt = transportAmt + billsAmt + foodAmt + giftsAmt + leisureAmt + othersAmt;
                   showTotal.setText("= $" + totalAmt);
              catch (NumberFormatException numberFormatException ) {
                        JOptionPane.showMessageDialog(this, "You must enter numbers!","Invalid Number Format", JOptionPane.ERROR_MESSAGE);
                   if (event.getSource() == dontSaveButton) {
                        System.exit(0);
                        if(event.getSource() ==saveButton){     
                        double transportAmt=0.0, billsAmt=0.0, foodAmt=0.0, giftsAmt=0.0,leisureAmt=0.0, othersAmt=0.0, totalAmt=0.0;      
                        try{
                             BufferedWriter out = new BufferedWriter(new FileWriter("mySavedTotal.txt",true));
                             if (!transportField.getText().equals("")) {     
                             transportAmt = Double.parseDouble(transportField.getText());
                             out.write("Transport = "+transportAmt);   
                             out.newLine();     
                             if(!billsField.getText().equals("")) {     
                             billsAmt = Double.parseDouble(billsField.getText());     
                             out.write("Bills = "+billsAmt);     
                             out.newLine();     
                             if(!foodField.getText().equals("")) {     
                             foodAmt = Double.parseDouble(foodField.getText());     
                             out.write("Food = "+foodAmt);     
                             out.newLine();     
                             if(!giftsField.getText().equals("")){     
                             giftsAmt = Double.parseDouble(giftsField.getText());     
                             out.write("Gifts = "+giftsAmt);     
                             out.newLine();
                             if(!leisureField.getText().equals("")){     
                             leisureAmt = Double.parseDouble(leisureField.getText());     
                             out.write("Leisure = "+leisureAmt);     
                             out.newLine();     
                             if(!othersField.getText().equals("")) {     
                             othersAmt = Double.parseDouble(othersField.getText());     
                             out.write("Others = "+othersAmt);     
                             out.newLine();     
                             out.write("Total amount "+showTotal.getText());
                        out.newLine();                              
                             out.close();
                             JOptionPane.showMessageDialog(this, "Everything is saved!");
                             catch(IOException e){
                                  JOptionPane.showMessageDialog(this, "You must enter integers!","Invalid Number Format",JOptionPane.ERROR_MESSAGE);
                        public static void main(String[] args) {                         
                             JPanel p = new CheckBox();
                        JFrame f = new JFrame();
                        Container c = f.getContentPane();
                        c.add(p);
                        f.pack();
                        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                          f.setVisible(true);
                        }urgent... how to rerieve saved data? i got try b4 but didnt work out

  • How to fire JComboBox itemStateChanged event manually?

    hello:
    I want to know how to fire JComboBox itemStateChanged event manually.
    thank you
    -Daniel

    Call setSelectedIndex or setSelectedItem.

  • How to use JCombobox (using ComboboxModel) in JTable?

    I have a question first, let imagine that i have 2 tables: Location(IDLocation, Place), Employee(ID, Name, Location)
    And I get all data in Location table into ArrayList, then setup a model (that extends ComboboxModel) and use this arraylist.
    After that i get all data in Employee table into Arraylist, then setup a MyTableModel (that extends AbstractTableModel) and use this arraylist.
    I could setup combobox in Location column, but i just wonder that how do i know how many comboboxes i need?. And if i use one model for all of these comboboxed and when i change selected item in one combobox, it will change data in other comboboxes in other rows. :(
    Anybody helps me, please?

    you just need only one combobox as the editor for all cell in location column.
    because, initially, all the cell in location column is "rendered" as non-combobox, the combobox appears only when you edit one cell, so you use only one combobox for every edition of a cell (in location column).
    The way to do this is to setCellEditor of your JTable to (new DefaultCellEditor(editComboBox)), so that every time you click on a cell (in location column), the combobox appears and your selected value will be the new value in that cell, all you have to do is just set the CellEditor as combobox, java 's done the rest for you.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox : perfect in this situation
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    public class TableComboBox extends javax.swing.JFrame {
        public TableComboBox() {
         initComponents();
        private void initComponents() {
            scrollPane = new javax.swing.JScrollPane();
            myTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            // create a table
            myTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {"E01", "John Bolton", "Boston"},
                    {"E02", "Vannessa", "Ohio"},
                    {"E03", "Hellboy", "Alaska"}
                new String [] {
                    "ID", "Name", "Location"
            // create a combobox which model will be created from the database as the editor
            JComboBox locations = new JComboBox(new String[]{"Boston", "Ohio", "Alaska"});
            // create a default cell editor
            DefaultCellEditor editor = new DefaultCellEditor(locations);
            // set that cell editor as the location column cells editor (column number 2 is location column), then use setCellEditor() method
            myTable.getColumnModel().getColumn(2).setCellEditor(editor);
            scrollPane.setViewportView(myTable);
            getContentPane().add(scrollPane);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-380)/2, (screenSize.height-117)/2, 380, 117);
        public static void main(String args[]) {
         java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
              new TableComboBox().setVisible(true);
        private javax.swing.JTable myTable;
        private javax.swing.JScrollPane scrollPane;
    }Edited by: bobbi2004 on Oct 28, 2008 9:59 AM

  • How to cause JComboBox to open to preselected item?

    If you initialize a JComboBox to an item (using setSelectedIndex, for instance), the first time that the comboBox is opened, it will open at the top of the list, not at the selected item. For example:
    JComboBox jComboBoxHourPicker = new JComboBox();
    // Add comboBox items here
    jComboBoxHourPicker.setSelectedIndex(22);
    The comboBox will correctly show the 23rd item selected. When the user opens the comboBox, however, it will open at the first item, not at the 23rd. If the user closes the comboBox without changing the selection, though, the next time that the comboBox is opened it will have scrolled to the selected item.
    The JList class has the ensureIndexIsVisible() method. Does anyone know how to get the same behavior for the JComboBox class?

    This is a known bug that has been fixed in v1.4. Check out the thread below, by me, for all the details. You're following in my footsteps.
    If you need a workaround for 1.3, follow the link into the bug database and there's a pretty decent one there.
    http://developer.java.sun.com/developer/bugParade/bugs/4337516.html

  • How to update JComboBox automaticly

    Hi I need help
    I have a JComboBox which has month from Jan to Dec.
    How do I make the JComboBox to show the month from the databases Example I retreive data that has the January in it but the JComboBox is showing March how do I make JComboBox to show January automaticly
    Thank You

    JComboBox.setSelectedItem or setSelectedIndex depending on how it is set up in your database. Pass the method the value of the month from the database (remember Jan index will be 0 in combo box)

  • How to use JComboBox

    I have an array of objects called procedures. These objects have the attribute int code which I'd like for the JComboBox to display. But instead it displays some other information, such as the directory where these objects were imported from. How do I get it to display only a certain part of the objects in the array that I populate the JComboBox with? Thanks in advance to anyone with an answer.
    Joe

    You should override public String toString() method in the object instances of what you have in an array.
    Just add
    public String toString() {
        return String.valueOf(intValue);
    }and you'll see those intValues in bundled JcomboBox.

  • How to filtering jcombobox  iterm

    Hi
    If there is any possible to filtering JComboBox Item based on entering my character basis in jcomboBox editing area .
    ( i.e ) Suppose I want enter ‘A’ character in jcombobox Field , it filtering all item start with 'A' or highlights the ‘A’ character from combobox Item like that , if it is possible give me a solution to how to solve it.

    This just might be a record.
    You've made 15 posts on this forum. Not once have you replied to any of the post to thank people for the help you've received.
    I for one can't be bothered to help anyone who doesn't appreciate the help they have received.
    Not only that, you didn't even bother to search the web, because this question has been asked and answered several times before.
    As far as I'm concerned you are on your own.

  • How to add JCombobox to panels and Paness to frames

    we added different items to combobox and that combobox to panels that panels is added to Jame, then we added listener to this combobox , then if we click on this combobox the list of items is appering in the back of the screen . How can i solve this probles ??.

    JComboBox box = new JComboBox();
    Container cont = getContentPane();
    box.addItem("option1");
    box.addItem("option2");
    box.addItem("option3");
    box.addItem("option4");
    box.addItem("option5");
    cont.add(box);
    setContentPane(cont);
    I hope that answers your question.
    Dunk

  • How to use JComboBox as VB DataCombo?

    I wan't to know if it is possible to use a JComboBox as VB6 DataCombo.
    There are 3 main properties of the VB6 DataCombo component: BoundColumn, ListField and RowSource.
    For example I can set the rowsource of this component to be a recordset containing for the first field a country code and the second field the corresponding country name. Therefore the BoundColumn will be the country code and the list field the country name. This component will display the country name and I am able to retrieve the corresponding country name. Also when I set to country code to this component, the corresponding country name is displayed.
    Is it possible to have the same behaviour with a JComboBox or do I have to use another component?
    Thanks for your help.

    Hi, you are probably long gone ...but I would like to set the record straight.
    After coming back and reading this post again I realized I my memory was a bit foggy about what a VB bound column property was doing. In fact, you DON'T need a CellRenderer to do this, because a CellRenderer is used to manipulate the visible aspect of the cell, and that has nothing to do with the VB bound column concept. I went into Access and reminded myself what VB is using the bound value for ...which is to store an additional value for each cell in the combo, apart from the value that will be displayed in each cell. This value is used to 'bind' the combo to a database query where the invisible 'bound column' value is a primary key value that is used to lookup the rest of the row for that selection. Of course in VB this all happens behind the scenes when you choose to fill the combo from a database query.
    In Java, unless you want to build an entire wizard to match the one in VB, you don't really approach the problem that way. You are going to have to do your own JDBC routine to fill the combo ...then listen for selections on that combo ...and query new values from the database each time the selection changes. However, you could give yourself a bit of leverage by considering the following two approaches.
    First off, you could ...as you read in the combo values from the db ...just add your own special data object into the combo that holds TWO values instead of just putting in the single visual object into the combo.
    //Loop through db results getting both the primaryKey
    //column values and the visible column values...
    mycombo.addItem( (Object) new MySpecialDataObject(primaryKey,visibleValue) );Your class for MySpecialDataObject could be something like this:
    public class MySpecialDataObject {
      private String primaryKey;
      private String visibleValue;
      public MySpecialDataObject(String primKey, String visVal) {
        primaryKey = primKey;
        visibleValue = visVal;
      public String getPrimaryKey() { return primaryKey; }
      public String getVisibleValue() { return visibleValue; }
    }And then when you get the selected object just cast it back into your special type, and then you can access both the primaryKey and the visibleValue for the selection. You can then requery the db using the primaryKey instead of having to use only the visible combo cell value.
    //Inside your action event for the combobox...
    MySpecialDataObject dao = (MySpecialDataObject) mycombo.getSelectedItem();
    String sql = "SELECT * FROM a_table WHERE primKey = " + dao.getPrimaryKey();However, this kind of forces the work onto the application developer to make this one (or possibly many of these) little data capsules each time they are using the combo. Another alternative could be to go to the data model for the combo, and create your own custom subclass that adds the characteristics you are looking for to the combobox itself, relieving the app developer of this minor nuisance. It might be a bit more work up front ...but it will streamline your development in the future by providing a customized combo class for your dev's to use.
    Here is an example of doing just that. The comments cover most of what I have done and why ...I did this over the weekend as my penance for giving you bad advice regarding the Cell renderer. As a bonus, I threw in an example of defining a custom cell renderer as well. Cheers ...silly old GumB.
    P.S. I am sure there are other approaches as well, good luck.
    * BoundJComboBoxModel.java
    * Created on May 23, 2003, 10:51 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    * @author  gum
    public class BoundJComboBoxModel extends javax.swing.DefaultComboBoxModel {
      private ArrayList boundObjects = new ArrayList();
       * Above, is an ArrayList for storing the bound values for each element.
       * Below, I have overriden all three constructors from DefaultComboBoxModel.
       * Notice how the second two just create default 'bound values' equal to a
       * string representation of the elements array index integer.  This may
       * work as a default if your primary keys in the database agreed (which
       * they quite possibly could).  However, the model is not really intended
       * to be filled this way.  Instead, use the overloaded addElement method
       * (below) and provide each item and corresponding bound value as a pair.
      public BoundJComboBoxModel() {
        super();
      public BoundJComboBoxModel(Object[] items) {
        super(items);
        for(int i=0; i<items.length; i++) {
          boundObjects.add(String.valueOf(i));
      public BoundJComboBoxModel(java.util.Vector v) {
        super(v);
        for(int i=0; i<v.size(); i++) {
          boundObjects.add(String.valueOf(i));
       * This method overloads its counterpart from DefaultComboBoxModel.
       * This provides a way to add a complete element, by providing values
       * for both the display value and the bound value all at once.
      public void addElement(Object item, Object boundValue) {
        boundObjects.add(boundValue);
        super.addElement(item);
       * Here are the new methods that 'decorate' the original DefaultComboBoxModel.
       * They provide ways to set and get the bound value for a specific element.
       * The method setBoundValueAt is called from the gui when we fill the combo.
       * The method getBoundValueAt is called from the BoundJComboBox class that
       * we are going to build next. It could be called directly on the model, but
       * making a special JComboBox class that used this model seemed a little nicer.
       * You will see the JComboBox class that uses this model next in the example.
      public void setBoundValueAt(int index, Object boundValue) {
        boundObjects.set(index, boundValue);
      public Object getBoundValueAt(int index) {
        return boundObjects.get(index);
      public Object getBoundValueForItem(Object item) {
        int index = getIndexOf(item);
        return boundObjects.get(index);
       * These methods override thier counterparts from DefaultComboBoxModel.
       * They are overriden so we can keep the bound value list in sync.
       * For example, consider the original addElement method from the superclass.
       * Used when no bound value is provided, the method will add a bound value
       * equal to a string representation of the elements array index integer.
       * The other two overriden methods are self explanatory.
      public void addElement(Object item) {
        int idNum = boundObjects.size();
        boundObjects.add(String.valueOf(idNum));
        super.addElement(item);
      public void removeElement(Object item) {
        int index = super.getIndexOf(item);
        boundObjects.remove(index);
        super.removeElement(item);
      public void removeAll() {
        boundObjects = new ArrayList();
        super.removeAllElements();
    * BoundJComboBox.java
    * Created on May 23, 2003, 10:00 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    import com.gumbtech.ui.BoundJComboBoxModel;
    * @author  gum
    public class BoundJComboBox extends javax.swing.JComboBox {
       * Here, I have overriden all three constructors from JComboBox.
       * We will 'force' our custom JComboBox to use the BoundJComboBoxModel.
      public BoundJComboBox() {
        super(new BoundJComboBoxModel());
      public BoundJComboBox(Object[] items) {
        super(new BoundJComboBoxModel(items));
      public BoundJComboBox(java.util.Vector v) {
        super(new BoundJComboBoxModel(v));
       * These are the new methods that 'decorate' the original JComboBox
       * class.  We have added methods that match the two methods JComboBox
       * provides for finding elements in the models list, except that our
       * new methods access the bound value list instead of the item list.
       * I only use the getSelectedBoundValue method in this example.  I
       * provided the other because together the two make a complete match
       * to the way the original class lets you query the original model.
      public Object getSelectedBoundValue() {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(getSelectedIndex());
      public Object getBoundValueAt(int index) {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(index);
    * BoundComboTest.java
    * Created on May 24, 2003, 12:18 PM
    package com;
    import java.awt.Color;
    import com.gumbtech.ui.BoundJComboBox;
    import com.gumbtech.ui.BoundJComboBoxModel;
    import com.gumbtech.ui.MyCustomCellRenderer;
    * This is a test gui that lets us demonstrate the custom
    * BoundJComboBox that we have created.  We are going to
    * emulate the 'bound column' characteristic of a VB bound
    * combo box object.
    * @author  gum
    public class BoundComboTest extends javax.swing.JFrame {
      public final static String T = "    ";
      private BoundJComboBox boundJComboBox;
      private javax.swing.JLabel msgLbl;
       * The constructor just calls methods that
       * build the gui and then fill the combo box.
      public BoundComboTest() {
        initComponents();
        fillCityComboByProvince("Alberta");
       * This method just sets up the gui components for our example.
      private void initComponents() {
      //Create an instance of BoundJComboBox (our customized JComboBox).
        boundJComboBox = new BoundJComboBox();
      //Plug in a custom renderer for the element cells visual appearance.
      //I put this here so you can see what a CellRenderer does, but this
      //actually plays no part in creating our VB like bound column combobox.
      //Out of interest, you can look at the MyCustomCellRenderer class later on.
        boundJComboBox.setRenderer(new MyCustomCellRenderer(new Color(40,100,60)));
      //Listen for change events on the combo box with an action listener.
      //Inside this action (see the comboActionPerformed method below) lies
      //the real reason for needing the bound column value.  The action needs
      //to translate the combo selection into a database query that retrieves
      //the values to be used on the form that this combo box is controlling.
        boundJComboBox.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboActionPerformed(evt);
      //Create other stuff to host our combo box in (irrelevent to our example).
        msgLbl = new javax.swing.JLabel();
        setTitle("Bound Combo Example");
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
          public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        getContentPane().add(boundJComboBox, java.awt.BorderLayout.NORTH);
        getContentPane().add(msgLbl, java.awt.BorderLayout.CENTER);
        pack();
        java.awt.Dimension screenSize =
           java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setSize(new java.awt.Dimension(400, 200));
        setLocation((screenSize.width-400)/2,(screenSize.height-200)/2);
       * So, your 'bound' combo box needs a visual label that will be
       * displayed in the combo box, here we use city names from a db.
       * Your VB like 'bound column' is going to be the city_ID number, which is
       * the primary key we need to use to look up this cities values in other
       * tables.  Being different from the visible text label ...this value needs
       * to be stored in the special 'bound column' area of our combo box model.
      private void fillCityComboByProvince(String province) {
      //We can get the model out of our JComboBox, notice that the model is of
      //type BoundJComboBoxModel ...which is our own customized ComboBoxModel.
        BoundJComboBoxModel model = (BoundJComboBoxModel) boundJComboBox.getModel();
      //Clear out the combo so we can load it fresh  See how the methods we are
      //used to using in a regular ComboBoxModel now seamlessly handle our
      //parallel list of 'bound column' values.  That's because we over-rode
      //them appropriately in our customized BoundJComboBoxModel.
        model.removeAll();
      //Pretend this is the query we would use to get the values...
      //If we were selecting all the rows in the table, we might not need a bound
      //column bacause they may have a linear set of incrementing primary keys.
      //However, we are selecting a filtered set of cities ...only those from Alberta
      //...so the primary keys will not follow any regular pattern.  This is why the
      //'bound column' concept is used ...to hold a non-visible list of primary keys
      //that match each label in the combo box.  Even though we choose the value
      //'Calgary' in the combo ...we need to use '54' to look it up in the database.
        String sql = "SELECT name, city_ID FROM cities WHERE province = "+ province;
      //Pretend this is the results from our query to the db.
        final Object[] cityNames = {"Calgary", "Edmonton", "Lethbridge", "Red Deer"};
        final Object[] primaryKeys = {"54", "89", "101", "193"};
      //Use the overloaded addElement method we created in BoundJComboBoxModel to
      //fill the combo with both the visual text value, and the 'bound' value.
        for(int i=0; i<cityNames.length && i<primaryKeys.length; i++) {
            model.addElement(cityNames, primaryKeys[i]);
    //See, the combo box now has a 'bound column' for each visual element in
    //its list, which we will use to query the db each time the selection changes.
    //This is all your 'bound column' is doing in your VB wizard ...except you
    //never see the code for it. In Java, you just write the code to give your
    //JComboBox this behaviour ...and more if you so choose (which is really
    //the whole the point here!)
    * The next method handles the selection change event for our combo box.
    * This is where you use the 'bound value'. You use it to requery
    * the db so you can fill in your form with new values each time
    * the combobox selection is changed by the user.
    * This method is your action event for the combo ...and it is doing
    * the same thing that your VB program will do with your 'bound column'
    * in your VB combo box. In VB you just can't see the code, that's all.
    private void comboActionPerformed(java.awt.event.ActionEvent evt) {
    //Get the combobox that performed the action event...
    boundJComboBox = (BoundJComboBox) evt.getSource();
    //If we had a database here for real, we would query for our new form
    // values using the 'bound column' value as the primary key in the query.
    //This is what it means to use the 'bound column' of a VB combobox or list.
    //Its just a value for each element in the combo box that is different from
    //the value that will be displayed in the combo list. That's all it means.
    //VB just uses the bound value to query the database, so we can do that too.
    String sql =
    "SELECT * FROM cities WHERE city_ID = " +
    boundJComboBox.getSelectedBoundValue();
    //Since we don't really have a db, I'll just show the values for the element.
    String msg = "<html><font color=#006666>"+
    T +"Index Selected : "+ boundJComboBox.getSelectedIndex() +"<br>"+
    T +"Value Selected : "+ boundJComboBox.getSelectedItem() +"<br>"+
    T +"Bound Column Value: "+ boundJComboBox.getSelectedBoundValue() +"<br>"+
    T +"</font><font color=#dd3366>"+ sql +"</font></html>";
    msgLbl.setText(msg);
    public static void main(String args[]) {
    new BoundComboTest().show();
    * MyCustomCellRenderer.java
    * Created on May 23, 2003, 9:21 PM
    package com.gumbtech.ui;
    import java.awt.Color;
    import javax.swing.JList;
    import javax.swing.DefaultListCellRenderer;
    * usage:
    * String[] data = {"one", "two", "free", "four"};
    * JList dataList = new JList(data);
    * dataList.setCellRenderer(new MyCustomCellRenderer());
    * @author  I think this structure and the comments are a variation of
    *          David Flanagans example from Java Examples 2. (O'Reilly)
    public class MyCustomCellRenderer extends DefaultListCellRenderer {
      private static Color selectedColor = new Color(240,99,99);
      private static Color selectedBG = new Color(163,186,168);
      public MyCustomCellRenderer() {
      public MyCustomCellRenderer(Color selectedColor) {
        this.selectedColor = selectedColor;
       * This is the only method defined by ListCellRenderer.
       * We just reconfigure the Jlabel each time we're called.
      public java.awt.Component getListCellRendererComponent(
             JList list,
             Object value,   // value to display
             int index,      // cell index
             boolean iss,    // is the cell selected
             boolean chf)    // the list and the cell have the focus
         * The DefaultListCellRenderer class will take care of
         * the JLabels text property, it's foreground and background
         * colors, and so on.
        super.getListCellRendererComponent(list, value, index, iss, chf);
         * We additionally set the JLabels color properties here,
         * but only for the cell that is currently selected (highlighted).
        if(iss) {
          setForeground(selectedColor);
          this.setBackground(selectedBG);
        return this;

  • How to make JComboBox display an item not in list?

    hi,
    i'd like a gui component which is basically a jcombobox that presents a list A,B,C,D.
    The combobox is paired with another gui component which allows choosing sets of items. A etc.. represent preselected sets of items, so the user can click on A and a particular set would be selected.
    My problem is what to have the JComboBox do when the user selects a set of items that is not in the preselected defaults list. It would be nice to have the JComboBox just say "Other" at the top or something, but I can't figure out a way of doing this without putting the String "Other" in the list of items..
    does anyone have any idea of how to approach this? (I looked at making the JComboBox editable but this seems a little complicated?)
    thanks,
    asjf

    Your best option and cleanest design is to have a
    dummy data item in your list for "none of the above". thanks for the reply - this is what I'm doing at the moment. The problem is that I'm expecting testers to legitimately complain that selecting "None of the above" doesn't do anything, and doesn't really make sense ( it could make a random selection :o) )
    i think i agree that adding functionality to do this "properly" is likely to be more work/pain than its worth..
    Only an editable combobox can display something not in the list.this might help - if I could block mouse clicks to the editable area, and write to it programmatically but think this is probably quite difficult (?)
    asjf

  • How to set JComboBox index

    How can I set the JComboBox index if just know the value of it?
    Like:
    combo.addItem("red");
    combo.addItem("blue");
    combo.addItem("white");
    combo.addItem("green");
    combo.addItem("yellow");
    combo.addItem("gray");Then I want the combo shows (selects when loaded the values) the value "green", assuming I dont know the index of if.
    How to do that?

    Sorry, I did not make myself clear here.
    Let's say I have this:
    combo.addItem("green - 1");
    combo.addItem("red - 2");
    combo.addItem("yellow  - 3");
    combo.addItem("black - 4");
    combo.addItem("blue - 5");
    combo.addItem("pink  - 6");Then I have SELECT returning some code, let's say code 5 (which is blue in the list).
    Now I want to select the color blue.

  • How to make jcombobox display all by itlself?

    Hello all -
    Is there a way to make a jcombobox object display its column of items implicitly?
    For example, suppose a program has a combobox filled up with names. And, suppose the first item says "toggle sort", which affects how the items are sorted in the combobox (eg, pressing it should cause the list to sort the displayed names based on first name, another press bases the sort on the last name...). The behavior I am aiming for is that when the user presses the "toggle sort" item, the combobox displays its items again awaiting further selection from the user (but not the first item). Know how to fire such an event?
    private void namesComboBoxActionPerformed(ActionEvent evt) {
       int selected = namesComboBox.getSelectedIndex();
       if (selected == 0) {
          // some code should result in the namesComboBox displaying its items again. What is it please?
    }

    Here is a simple code, I don't know if its the correct way to do this sort of thing but it works:
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.*;
    * Sorting Combobox....
    * @author talha
    public class ComboSort extends JFrame{
        ArrayList<ComboData> data;
        JComboBox combo;
        public ComboSort() {
            super("Combo Sorting");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            populateData();
            Collections.sort(data);
            // I don't know how much of the combobox model should be overridden!
            combo=new JComboBox(new DefaultComboBoxModel() {
                @Override
                public Object getElementAt(int index) {
                    return (index==0)?"Toggle Sort":data.get(index-1);
                @Override
                public int getSize() {
                    return data.size()+1;
                @Override
                public int getIndexOf(Object anObject) {
                    return (anObject instanceof String)?0:data.indexOf(anObject)+1;
            combo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(combo.getSelectedIndex()==0){
                        ComboData.toggleSort();
                        Collections.sort(data);
                        //edited to make the pop up visible....
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                combo.setPopupVisible(true);
            combo.setRenderer(new DefaultListCellRenderer() {
                @Override
                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    Component renderer=super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                    if(value instanceof String){
                        renderer.setForeground(Color.BLUE);
                        renderer.setBackground(Color.YELLOW);
                    return renderer;
            // you can remove following....
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    combo.setSelectedIndex(0);
            getContentPane().setLayout(new FlowLayout());
            getContentPane().add(new JLabel("Heads of State:"));
            getContentPane().add(combo);
            setSize(300, 300);
            setLocationRelativeTo(null);
        private void populateData() {
            data=new ArrayList<ComboData>();
            data.add(new ComboData("Barak", "Obama"));
            data.add(new ComboData("Gordon", "Brown"));
            data.add(new ComboData("Nicolas", "Sarkozy"));
            data.add(new ComboData("Angela", "Merkel"));
            data.add(new ComboData("Wen", "Jiabao"));
            data.add(new ComboData("Taro", "Aso"));
            data.add(new ComboData("Manmohan", "Singh"));
            data.add(new ComboData("Asif", "Zardari"));
            data.add(new ComboData("Mahmoud", "Ahmedinejad"));
            data.add(new ComboData("Hugo", "Chavez"));
            data.add(new ComboData("Raul", "Castro"));
        public static void main(String args[]){
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new ComboSort().setVisible(true);
    class ComboData implements Comparable{
        String firstname;
        String lastname;
        static boolean sortFirstName;
        public ComboData(String firstname, String lastname) {
            this.firstname = firstname;
            this.lastname = lastname;
        @Override
        public String toString() {
            return firstname+" "+lastname;
        public static void toggleSort(){
            sortFirstName=!sortFirstName;
        public int compareTo(Object o) {
            ComboData other=(ComboData)o;
            if(sortFirstName)return firstname.compareTo(other.firstname);
            else return lastname.compareTo(other.lastname);
    }Thanks!
    Edit: Reread your original post and made few editions... but I still don't think that this is what you need (but now its much better) :-)
    Edited by: T.B.M on Apr 19, 2009 1:16 PM

  • How to make JComboBoxes transparent

    For some reason "setOpaque(false)" doesn't seem to work for JComboBoxes. I'm using java 1.4
    Below is some code. If you compile and run it you should get a window with a button and a combo box, the button is transparent, the combo box is not.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Area;
    * test transparent swing components
    class TransTest
    public static void main(String args[])
         JFrame theFrame = new JFrame("transparency test");
         JComponent contentPane = new JComponent()
              public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              Area s = new Area((Shape)new Rectangle(0, 0, getWidth(), getHeight()));
              g2.setPaint(new GradientPaint(0f, 0f, Color.GRAY, 150f, 100f, Color.WHITE, true));
              g2.fill(s);
              super.paintChildren(g);
         theFrame.setContentPane(contentPane);
         theFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
         JButton button = new JButton("button");
         button.setOpaque(false);          // this works
         JComboBox combo = new JComboBox();
         combo.addItem("combo");
         combo.setOpaque(false);               // this doesn't seem to work
         JPanel pnl = new JPanel();
         pnl.setOpaque(false);
         pnl.add(button);
         pnl.add(combo);
         contentPane.setLayout(new BorderLayout());
         contentPane.add(pnl, BorderLayout.CENTER);
         theFrame.pack();
         theFrame.setVisible(true);

    Try setOpaque(true) and setBackground(new Color(r,g,b,a)) where r, g and b are respectively the values of red, green and blue and a the alpha value (0 means totaly transparent, 255 totaly opaque). Sometimes a component should be opaque with a transparent background to make the transcparency works.
    But I have to ask you a question : have you bugs with the display ? Indeed, I made an app that doesn't use a gradient paint like you, but the JFrame have a ContentPane that display a picture. I made every JComponent transparent in order to see the background picture. The display is very dirty with JButton, JTextArea, JTextField and JList. Indeed, when moving cursor over JButton, the JButton displays the top lecft corner of the JFrame instead of the underlaying part of the picture as expected with transparency. With JTextField and JTextArea, when typing text the same problem occured. With JList, the problem appear when scrolling. only a full update(Graphics g) can clean the display, that is I must call it with every mouseMoved, mouseClicked, etc. events. The problem appears only with JDK > 1.2.2 (JDK1.3 and later)

  • How to give JComboBox JButton effects(urgent)

    hi,
    After selecting item in the JComboBox,when i perform action on the selected item, i am drawing a rectangle around the JComboBox. I want this rectangle to stay back till the operation is under processing, but i am not able to get it.
    i have used the following code for drawing rectangle around the combo
    private void drawRectangle(Graphics g,Insets inset,int width,int height)
    int top = inset.top;
    int bottom = inset.bottom;
    int left = inset.left;
    int right = inset.right;
    width = width - left - right;
    height = height - top - bottom;
    java.awt.Color col = g.getColor();
    g.setColor(java.awt.Color.black);
    BasicGraphicsUtils.drawDashedRect(g,2,2,width-20,height-2);
    try
    java.lang.Thread.currentThread().sleep(400);
    catch(InterruptedException ie)
    System.out.println("Catching Exception");
    g.setColor(col);
    }

    Don't use drawing, add a border instead

Maybe you are looking for

  • Connecting MacBook to Sony Bravia via DVI-HDMI!

    Hi I am having major issues with my Macbook connecting to my Sony Bravia KDL-32V4000 I now have 2 different DVI-HDMI leads as well as the Apple Mini-DVI-DVI and still have absolutely no luck. The Macbook is picking up the Television absolutely no bot

  • Material PO text not copying to Purchase Requisition

    Any assistance would be gratly appreciated... When creating a Purchase Requisition (ME51N) text from the Material Master - Material PO Text automatically copies to the Material PO Text of the Purchase Requisition line item - as expected However, when

  • How to choose Application layout in flex?

    Hi Everyone ....! I have confused to select the layout in flex 3.0.There are three type of layout having absolute,horizontal and vertical. Which one is best? and How to choose layout? and please Explain about layout???/... Thanks in advance.........

  • Any Content-Type attribute is interpreted as "charset"

              WL 6.1 sp 2           I have a servlet that set the Content-Type of the response to something like "application/*;name=blabla".           According to the http/1.1 spec that should be fine.           However, WL seems to interpret any Conte

  • Access the form of Item master

    I want to add a text box in the form of item master.Is it possible to access it thorugh .net. I access the newly created forms as, SBO_Application.Forms.ActiveForm