JComboBox, ItemListener, ActionListener questions

Hallo,
I have some troubles with a JComboBox:
I add an ActionListener and an ItemListener to it.
1.ActionListener problems: if the combo is editable then entering value in the editor and clicling Enter fires 2 actionEvents
with the combo as source. The difference I noticedbetween them is the actionCommand value:
"comboBoxChanged"(as from normal select) and "comboBoxEdited"(because of changed value in editor)
2. ItemListener problem: everything is OK selecting with mouse but if I type text/editable again/ and press enter only the
ActionListener is called(yes, KeyListener in editor will help). The users also want to point a value with the mouse and press enter on it.
Again only the action is called.
Now the questions:
1.Can I rely on the texts in actionCommand? What should I compare them to if "Yes"/are they localized?/
2. Is there an easier way then adding a KeyListener to the editor and list component of the combo to catch the Enter if ActionListener cannot be used?
Thanks in advance
Mike

About my question 1: in source of JComboBox these text values seem to be hard-coded.
So I will use them for now. But I still would appreciate other ideas.
Thanks
Mike

Similar Messages

  • JComboBox and Actionlistener? Is it possible?

    I want to add Actionlistener to each individual selections inside the JComboBox. How would the code look like? Is this even possible?

    This is your second question about a JComboBox. Did you read:
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html

  • I need advise on JComboBox / ItemListener

    I have 3 JComboBoxes which act as date fields (month, day and year). I want to monitor the boxes so the user does not enter a date which is below a certain minimum, or over a certain maximum.
    The ItemListener is causing me some confusion though, whenever I adjust a JComboBox, two ItemListenerEvents are triggered back to back, and I'm guessing the first is a DESELECT event and the second is a SELECT event.
    The thing is, the JComboBox will return the same index from getSelectedIndex() during each of these events, so I can't tell what was the old selected index was. I figured the DESELECT event would not change the selectedIndex on my combobox, but it looks like it did. Any better way to find out the old selected index so I can revert to it if I find out the new value is no good?

    Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/events/itemlistener.html]How to Write an Item Listener

  • JComboBox Strange Problem

    Hi,
    I am writting a program involving a JComboBox.
    My Question is:
    How can jComboBox1.getSelectedIndex() return 1 if the previous line was jComboBox1.setSelectedIndex(0).
    My code:
    File f=null;
    int at=0;
    boolean dontdoit=false;
        @SuppressWarnings("static-access")
    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
    System.out.println(jComboBox1.getSelectedIndex()+" "+dontdoit);
            if(jComboBox1.getSelectedIndex()==1 && at!=1 && !dontdoit) {
        at=1;
        JFileChooser jfc=new JFileChooser();
        int i=jfc.showOpenDialog(null);
        f=jfc.getSelectedFile();
    if(i==jfc.CANCEL_OPTION) {System.out.println("H");
        f=null;
        at=0;
        dontdoit=true;
        jComboBox1.setSelectedIndex(0);
        System.out.println(jComboBox1.getSelectedIndex());
        jComboBox1ItemStateChanged(null);
       return;
        try {
        SimpleAudioPlayer sap=new SimpleAudioPlayer(f.toURI().toURL().getPath());
        sap.audioPlayer.close();
        }catch(Exception e) {
            JOptionPane.showConfirmDialog(null,"This file is not a valid audio file.\nPlease select another.","Invalid",-1);
            jComboBox1ItemStateChanged(null);
    else {
        f=null;
        at=0;
    dontdoit=false;
    }I can't get it to work. Please Help

    Sorry:
    (Part 1)
    * Options.java
    * Created on May 19, 2009, 3:28 PM
    package chatx;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    * @author  Michael
    public class Options extends javax.swing.JFrame {
        /** Creates new form Options */
        public Options() {
            initComponents();
            if(!new File("C:\\ChatX\\Options\\RINGLEN.txt").exists()) {
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream("C:\\ChatX\\Options\\RINGLEN.txt");
                    fos.write("20".getBytes());
                    fos.close();
                } catch (Exception ex) {
            else {
                FileInputStream fos = null;
                try {
                    fos = new FileInputStream("C:\\ChatX\\Options\\RINGLEN.txt");
                    byte[] b = new byte[fos.available()];
                    fos.read(b);
                    jSpinner1.setValue(Integer.parseInt(new String(b)));
                    fos.close();
                } catch (Exception ex) {
                    Logger.getLogger(Options.class.getName()).log(Level.SEVERE, null, ex);
            if(new File("C:\\ChatX\\Options\\RINGTONE").exists()) {
                jComboBox1.setSelectedIndex(1);
                at=1;
        public void copyFile(File in, File out) throws Exception {
            FileInputStream fis  = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);
            byte[] buf = new byte[1024];
            int i = 0;
            while((i=fis.read(buf))!=-1) {
                fos.write(buf, 0, i);
            fis.close();
            fos.close();
        /** 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() {
            jPanel1 = new javax.swing.JPanel();
            jTabbedPane1 = new javax.swing.JTabbedPane();
            jPanel2 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jSpinner1 = new javax.swing.JSpinner();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jComboBox1 = new javax.swing.JComboBox();
            jLabel4 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Options", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
            jLabel1.setText("Ring Length:");
            jSpinner1.setValue(new Integer(20));
            jLabel2.setText("seconds");
            jLabel3.setText("Ring Tone:");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Standard Ringing", "Custom" }));
            jComboBox1.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    jComboBox1ItemStateChanged(evt);
            jLabel4.setText("IP Address:");
            jTextField1.setEditable(false);
            jTextField1.setText("YOURIP");
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTextField1)
                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jSpinner1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addContainerGap(158, Short.MAX_VALUE))
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(155, Short.MAX_VALUE))
            );

  • 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

  • Jcombobox listener

    I would like to set a listener on a jcombobox (either actionlistener or itemlistener). However, at the same time, I want to know that the combobox item was changed via the user's mouse or keyboard input, and not triggered via the application loading data from the database and changing the combo box. I know I can add the listener after the data has been loaded onto the page, but I was hoping that Swing would provide a mechanism to know what input method was used to change the combo box. Anybody have any ideas?
    It would be greatly appreciated. Thanks!

    That's certainly one of the work-arounds I had in mind, but the overall gui component that holds the JComboBox implements an interface that is inherited by several objects. In order to set a marker variable, I would have to implement the method in the super-class which does nothing for the other sub-classes and override it in the sub-class I'm interested in. Definitely do-able. But, I was hoping some Swing guru could tell me if I could get my hands on how the change item event was triggered. Sounds like it is not possible.
    Thank you.

  • JComboBox with Custon Renderer Problem

    Hi, I am using a JComboBox with a custom ListCellRenderer that changes the colors of the strings on the list depending on some circunstances. The problem is that the changes only work on the list, but when one item is finally selected, and the list is no longer visible, the selected item has the default format (no colors)
    Thanks in advance

    I am not exactly sure what you mean, but here is something I wrote that sounds similar. It allows items in the dropdown list to be highlighted (text in red). The highlighted state is maintained when the dropdown list disappears, though in this implementation a selected item has highlighting turned off (the idea was that the items are things the user needed to see, once the user had selected a item, it no longer needed to be highlighted).
    For this to work all the items in your list must implement HighlightingComboBox.Highlightable.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * An extension to JComboBox that allows items to be "highlighted"
    * (if they implement the HighlightingComboBox.Highlightable interface).
    * Highlighted items are shown in red. Highlighting is turned off when
    * the item is first selected. Items not impleneting that interface are
    * displayed normally. The drop-down list is rendered the same
    * regardless of the font property of the components, it is therefore
    * possible to set that property to, say, a huge, fancy font without the
    * drop-down panel being affected.
    public class HighlightingComboBox extends JComboBox
                                      implements ActionListener {
        public HighlightingComboBox() {
            super();
            addActionListener(this);
            setRenderer(new FancyRenderer());
        public HighlightingComboBox(Object[] os) {
            super(os);
            this.addActionListener(this);
            setRenderer(new FancyRenderer());
        public void actionPerformed(java.awt.event.ActionEvent ae) {
            if (getSelectedItem() instanceof Highlightable)
                ((Highlightable)getSelectedItem()).setHighlighted(false);
        private static class FancyRenderer extends JLabel
                                           implements ListCellRenderer {
            public java.awt.Component getListCellRendererComponent(
                    javax.swing.JList list,
                    Object value,
                    int index,
                    boolean isSelected,
                    boolean cellHasFocus) {
                setText(value.toString());
                if ((value instanceof Highlightable)
                           && (((Highlightable)value).isHighlighted())) {
                    setForeground(Color.red);
                } else {
                    setForeground(Color.black);
                setBackground(isSelected ? Color.yellow : Color.white);
                setForeground(Color.black);
                return this;
         * Objects that implement this interface can be
         * highlighted on a HighlightingComboBox.
        public interface Highlightable {
            public boolean isHighlighted();
            public void setHighlighted(boolean flag);
    }

  • Update the testfield when setSelectedItem() for editable JComboBox

    Hi,
    I am having problem with setSelectedItem() and setSelectedIndex() methods of editable JComboBox.
    I extended JComboBox with default dataModel. When I enter some string in the textfield of the combobox, I call insertItemAt() method to dynamically grow the list. The application requires to clear the textfield everytime I enter something and press "return" key. To make it work, I insert an empty string to the list at the very beginning and call the setSelectedItem("") method in the actionPerformed().
    Now the problem is that I know the setSelectedItem("") is called since the getActionCommand() returns "comboBoxChanged" everytime I enter something in the textfield, but the testfield is not cleared. And if I select one item from the list and press "enter" key, the textfield is cleared. To make things more interesting, after I enter the first string and press "enter", the textfield really get cleared, but not for all other later input. Is this a bug? Can anyone please help me? Thanks a lot. Below is my code snippet.
    public class MyComboBox extends JComboBox implements ActionListener
    public GsISCommComboBox()
    jbInit();
    private void jbInit() throws Exception
    this.setEditable(true);
    this.addActionListener(this);
    insertItemAt("",0);
    public void actionPerformed(ActionEvent e)
    String str=null;
    String strrr=e.getActionCommand();
    System.out.println("getActionCommand: "+strrr);
    if(strrr.equalsIgnoreCase("comboBoxChanged"))
    str=(String)this.getSelectedItem();
    return;
    else
    str=strrr;
    // other stuff to process the string and do things
    setSelectedItem("");
    repaint();
    hidePopup();
    insertItemAt(str,0);

    Try inserting your string first and then, try clearing the combobox's textfield.
    insertItemAt(str,0);
    setSelectedItem("");
    hidePopup();
    repaint();
    Since you add the "" string at the begining, it will have the index 0. Perhaps, you want to insert your string this way:
    // insert string at the end
    insertItemAt(str, this.getItemCount());
    //Then use the
    setSelectedIndex(0);
    But you need to remember that if you add an item at the begining, index 0 may not be your '' '' string after that.
    I hope that it helps.

  • JComboBox selection actions on mouse and enter only

    I am driving some processing off of selections in a JComboBox.
    The ItemListener goes into action when the user mouse clicks on an item (this is good), but also when an item is arrowed through (bad).
    I want to wait until the person hits enter before starting my processing.
    Ideally the JComboBox popup could close before the start of my processing.
    The direction I am currently headed: I notice that when the mouse clicks, and when enter is hit, the JComboBox popup closes. Since these are the 2 user events I want to respond to, this fact interests me greatly. Is there any way to see and use the event of the popup closing?
    Note: I don't care so much about the direction I am thinking now as much as a solution to the overall problem.

    Try to register a KeyListener to the JComboBox or to its editor (if its editable) and react to the keyReleased Event. In the corresponding listener method you have to query the key typed and react to the ENTER key being pressed. Also get away from the ItemListener as the JComboBox / ItemListene combination is not the best the guys at sun farbricated...

  • Gathering data

    i would like to get my radio buttons to display below, a string of text, how would i go about doing that?
    * swingMakeup.java requires no other files.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class swingMakeup implements ItemListener, ActionListener{
        JPanel cards; //a panel that uses CardLayout
        final static String BUTTONPANEL = "Meats";
        final static String TEXTPANEL = "Name Of Customer";
        final static String TEXTPANEL2 = "Number of Subs";
        final static String CHECKPANEL = "Fixins'";
        JRadioButton beef, turkey, sheep;
        JTextField name, number;
        public void addComponentToPane(Container pane) {
            //Put the JComboBox in a JPanel to get a nicer look.
            JPanel comboBoxPane = new JPanel(); //use FlowLayout
            String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL, TEXTPANEL2, CHECKPANEL };
            JComboBox cb = new JComboBox(comboBoxItems);
            cb.setEditable(false);
            cb.addItemListener(this);
            name.addActionListener(this);
            number.addActionListener(this);
            comboBoxPane.add(cb);
            //Create the "cards".
            JPanel card1 = new JPanel();
            card1.add(beef=new JRadioButton("Beef Lips -- $5.00"));
            card1.add(turkey=new JRadioButton("Turkey Liver -- $4.00"));
            card1.add(sheep=new JRadioButton("Sheep Stomach -- $6.00"));
            JPanel card2 = new JPanel();
            card2.add(name=new JTextField("", 20));
            JPanel card3 = new JPanel();
            card3.add(number=new JTextField("", 20));
            JPanel card4 = new JPanel();
            card4.add(new JCheckBox("Lettuce"));
            card4.add(new JCheckBox("Tomato"));
            card4.add(new JCheckBox("Onion"));
            card4.add(new JButton("Submit Order"));
            //Create the panel that contains the "cards".
            cards = new JPanel(new CardLayout());
            cards.add(card1, BUTTONPANEL);
            cards.add(card2, TEXTPANEL);
            cards.add(card3, TEXTPANEL2);
            cards.add(card4, CHECKPANEL);
            pane.add(comboBoxPane, BorderLayout.PAGE_START);
            pane.add(cards, BorderLayout.CENTER);
        public void itemStateChanged(ItemEvent evt) {
            CardLayout cl = (CardLayout)(cards.getLayout());
            cl.show(cards, (String)evt.getItem());
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("swingMakeup");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            swingMakeup demo = new swingMakeup();
            demo.addComponentToPane(frame.getContentPane());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    1) I don't understand the question
    2) The code doesn't compile, so I can't see what you are trying to do
    3) Read the Swing tutorial on "Using Radio Button". You where given a link to the tutorial in your last posting.

  • 2 Problems w/ 2 Programs

    // Mortgage Program w/ graphical interface & set year and rate inputs
    // By : 2/05
    import javax.swing.*;
    import java.awt.*;
    public class MortgageGui2 extends JFrame {
    MortgageGui2Support mortgageSupport = new MortgageGui2Support(this);
    // Row 1
    JPanel row1 = new JPanel();
    JLabel Amount = new JLabel("Amount $", JLabel.LEFT);
    JTextField txtAmount = new JTextField(10);
    JLabel Selection = new JLabel("Select Term/Rate", JLabel.LEFT);
    JLabel Payment = new JLabel ("Monthly Payment is:");
    JTextField paymentValueBox = new JTextField (10);
    JComboBox comboTermInterest = new JComboBox();
    // Row2
    JPanel row2 = new JPanel();
    JLabel Month = new JLabel("\nPayment", JLabel.LEFT);
    JLabel IntBalance = new JLabel("Interest Paid", JLabel.CENTER);
    JLabel Remaining = new JLabel("Balance", JLabel.RIGHT);
    // Row 3
    JPanel row3 = new JPanel();
    JTextArea txtResults = new JTextArea(10, 35);
    // Row 4
    JPanel row4 = new JPanel();
    JButton calculateButton = new JButton("Calculate");
    JButton clearButton = new JButton("Reset");
    JButton exitButton = new JButton("Exit");
    public MortgageGui2() {
         super("Mortgage Calculator Week 2");
         setSize(655, 350);
         setLocation(250, 60);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         FlowLayout layout = new FlowLayout();
         Container pane = getContentPane();
         pane.setLayout(layout);
         // Buttons
         calculateButton.addActionListener(mortgageSupport);
         clearButton.addActionListener(mortgageSupport);
         comboTermInterest.addItemListener(mortgageSupport);
         exitButton.addActionListener(mortgageSupport);
         // Row 1
         FlowLayout flow1 = new FlowLayout();
         row1.setLayout(flow1);
         row1.add(Amount);
         row1.add(txtAmount);
         row1.add(Selection);
         row1.add(comboTermInterest);
         comboTermInterest.setEnabled(true);
         comboTermInterest.addItem(" Choose One ");
         comboTermInterest.addItem("7 years at 5.35% ");
         comboTermInterest.addItem("15 years at 5.5% ");
         comboTermInterest.addItem("30 years at 5.75% ");
         row1.add (Payment);
         row1.add (paymentValueBox);
         pane.add(row1);
         // Row 2
         GridLayout flow2 = new GridLayout(1, 4, 5, 1);
         row2.setLayout(flow2);
         row2.add(Month);
         row2.add(IntBalance);
         row2.add(Remaining);
         pane.add(row2);
         // Row 3
         txtResults.setLineWrap(true);
         JScrollPane textPane = new JScrollPane(txtResults,
              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
              JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         row3.add(textPane);
         pane.add(row3);
         // Row 4
         GridLayout flow5 = new GridLayout (1,5,85,1);
         row4.setLayout(flow5);
         row4.add(calculateButton);
         calculateButton.setEnabled(false);
         row4.add(clearButton);
         clearButton.setEnabled(false);
         row4.add(exitButton);
         pane.add(row4);
    public static void main(String[] args) {
         MortgageGui2 guiFrame = new MortgageGui2();
         guiFrame.setVisible(true);
    // Support section of program.
    import java.text.NumberFormat;
    import java.awt.event.*;
    import java.math.*;
    public class MortgageGui2Support implements ItemListener, ActionListener {
         MortgageGui2 gui;
         int array;
         double [] arrayMonths = {0,84,180,360};
         int c = 1;
         double [] arrayInterest = {0,5.35,5.5,5.75};
         int i = 1;
              public MortgageGui2Support (MortgageGui2 in) {
                   gui = in;
    public static void main(String[] arguments) {
    public void itemStateChanged(ItemEvent arg0) {
         Object button = gui.comboTermInterest.getSelectedItem();
         String buttonPress = button.toString();
              if (buttonPress == "7 years at 5.35% ") {
                   array = 1;
                   gui.calculateButton.setEnabled(true);
                   gui.clearButton.setEnabled(true);
              if (buttonPress == "15 years at 5.5% ") {
                   array = 2;
                   gui.calculateButton.setEnabled(true);
                   gui.clearButton.setEnabled(true);
              if (buttonPress == "30 years at 5.75% ") {
                   array = 3;
                   gui.calculateButton.setEnabled(true);
                   gui.clearButton.setEnabled(true);
    public void actionPerformed(ActionEvent event) {
         String buttonClicked = event.getActionCommand();
              if (buttonClicked == "Calculate") {
                   clearResults();
                   funcCalculate();
              if (buttonClicked == "Reset")
                   setNull();
              if (buttonClicked == "Exit")
                   System.exit(0);
         void funcCalculate()     {
              do {
                   NumberFormat fmt = NumberFormat.getInstance();
                   fmt.setGroupingUsed (true);
                   fmt.setMaximumFractionDigits(2);
                   fmt.setMinimumFractionDigits(2);
                   String txtInitialAmount = gui.txtAmount.getText();
                   gui.comboTermInterest.setEnabled(true);
                   gui.calculateButton.setEnabled(true);
                   // Calculations
                   double initBalance = Double.parseDouble(txtInitialAmount);
                   double loanRateMonth = (arrayInterest[array] / 1200);
                   for(int i = 1; i <= arrayMonths[array]; i++) {
                        double monthInterest = arrayInterest[array] / (1200);
                        double monthPayment = (initBalance *( loanRateMonth) / (1 -(1/ Math.pow((1 + loanRateMonth),( arrayMonths[array])))));
                        double Interest = (initBalance * monthInterest);
                        double totalamount = (Interest + initBalance);
                        double remaining = (totalamount - monthPayment);
                        initBalance = (totalamount - monthPayment);
                        // Output
                        gui.txtResults.append("\t " + i + "\t$"
                             + fmt.format (Interest) + "\t$"
                             + fmt.format (remaining) + "\t\n");
                             c++;
              } while (c <= arrayMonths[array]);
         void setNull() {
              gui.txtAmount.setText (null);
              gui.comboTermInterest.setSelectedItem("Select Option");
              gui.txtResults.setText(null);
              i = 1;
         void clearResults() {
              gui.txtResults.setText(null);
    These two programs work together and I am getting the wrong balance in the output and I need to know how to input the monthly mortgage output to the box at the end of line 1. Thanks

    I didn't go thru all of it, but these things are common mistakes:
    if (buttonPress == "7 years at 5.35% ")Always use the String.equals method to compare, not the == operator, which only compares object references, not values.
    You really should only post specific questions, not whole progs with the "question" basically "please fix it for me".

  • JTree Inserting Problem

    Please help me ..
    i have write a code ..which is when the user clicks the button...
    a jtree table will come and the values inside the jtree will be filled by the contents of the selected items in the form...
    but my problem is jtree only is comming
    i created the object class ... but ...
    the initialisation is not happening...
    plz check the code below .. this is my class
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Reservation extends JFrame implements ItemListener,ActionListener{
         JComboBox fromCity = null;
         JComboBox toCity = null;
         JComboBox dDay = null;
         JComboBox dMonth = null;
         JComboBox dYear = null;
         JComboBox rDay = null;
         JComboBox rMonth = null;
         JComboBox rYear = null;
         JComboBox adult = null;
         JComboBox Cabin = null;
         JFrame table;
         public Reservation()
              setSize(600,400);
              JPanel p = new JPanel();
              //getContentPane().setLayout(new BorderLayout());
              GridBagLayout gbl = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              p.setLayout(gbl);
              String []cities = {"New York","Chicago","Miami","Pittsburgh","Memphis","New Orleans"};
              String [] days={"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","27","28","29","30","31"};
              String [] months = {"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
              String [] year = {"2006","2007"};
              String [] adt = {"1","2","3","4"};
              String [] cab = {"Buisness","Economy"};
              fromCity = new JComboBox(cities);
              fromCity.setSelectedIndex(0);
              toCity = new JComboBox(cities);
              toCity.setSelectedIndex(0);
              dDay = new JComboBox(days);
              dMonth = new JComboBox(months);
              dYear = new JComboBox(year);
              rDay = new JComboBox(days);
              rMonth = new JComboBox(months);
              rYear = new JComboBox(year);
              adult = new JComboBox(adt);
              Cabin = new JComboBox(cab);
              JLabel frmCity = new JLabel("From");
              frmCity.setLabelFor(fromCity);
              JLabel tCity = new JLabel("To");
              tCity.setLabelFor(tCity);
              JLabel dDate = new JLabel("Departure Date");
              dDate.setLabelFor(dDate);
              JLabel rDate = new JLabel("Return Date");
              rDate.setLabelFor(rDate);
              JLabel Psg = new JLabel("Pasengers");
              Psg.setLabelFor(Psg);
              JLabel Adults = new JLabel("Adults");
              Adults.setLabelFor(Adults);
              JLabel cabin = new JLabel("Cabin");
              cabin.setLabelFor(cabin);
              JLabel search = new JLabel("Search By");
              search.setLabelFor(search);
              JRadioButton ROneWay = new JRadioButton("One Way");
              JRadioButton RRoundTrip = new JRadioButton("Round Trip");
              JButton searchbutton = new JButton("Date");
              ButtonGroup group = new ButtonGroup();
              group.add(ROneWay);
              group.add(RRoundTrip);
              gbc.gridx = 0;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(frmCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(fromCity,gbc);
              gbc.gridx =0;
              gbc.gridy = 1;
              gbc.insets = new Insets(0,30,0,0);
              p.add(tCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 1;
              gbc.insets = new Insets(10,30,0,0);
              p.add(toCity,gbc);
              gbc.gridx = 0;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,50,0,0);
              p.add(ROneWay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,30,0,0);
              p.add(RRoundTrip,gbc);
              gbc.gridx = 1;
              gbc.gridy = 3;
              gbc.insets = new Insets(0,0,0,0);
              p.add(dDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 4;
              p.add(dDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 4;
              p.add(dMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 4;
              p.add(dYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 5;
              gbc.insets = new Insets(0,0,0,0);
              p.add(rDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 6;
              p.add(rDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 6;
              p.add(rMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 6;
              p.add(rYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 7;
              p.add(Psg,gbc);
              gbc.gridx = 0;
              gbc.gridy = 8;
              p.add(Adults,gbc);
              gbc.gridx = 1;
              gbc.gridy = 8;
              p.add(adult,gbc);
              gbc.gridx = 0;
              gbc.gridy = 9;
              p.add(cabin,gbc);
              gbc.gridx = 1;
              gbc.gridy = 9;
              gbc.insets = new Insets(10,0,0,0);
              p.add(Cabin,gbc);
              gbc.gridx = 0;
              gbc.gridy = 10;
              p.add(search,gbc);
              gbc.gridx = 1;
              gbc.gridy = 10;
              gbc.insets = new Insets(10,0,0,0);
              p.add(searchbutton,gbc);
              getContentPane().add(p);
              fromCity.addItemListener(this);
              toCity.addItemListener(this);
              dDay.addItemListener( this);
              dMonth.addItemListener( this);
              dYear.addItemListener(this);
              adult.addItemListener(this);
              Cabin.addItemListener(this);
              searchbutton.addActionListener(this);
              //Jtable form
              table = new JFrame();
              Container container;
              container = table.getContentPane();
              JPanel jpanel = new JPanel(new GridLayout(2,1));
              container.setLayout(new GridLayout(2,1));
              JLabel l1 = new JLabel("Departure Journey");
              l1.setLabelFor(l1);
              container.add(l1);
              final String[] colHeads = {"","Flightno","Date","Departure Time","Arrival Time","Flight","Duration","Fare"};
              final Object[ ][ ] data = new Object[10][10];
              JTable table = new JTable(data,colHeads);
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;     
              int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
              JScrollPane jsp = new JScrollPane(table,v,h);
              container.add(jsp,BorderLayout.CENTER);
         String ffcity,ttcity,dday,dmon,dyear,adt,cab;
         public void itemStateChanged(ItemEvent e)
              ffcity = (String)fromCity.getSelectedItem();
              ttcity = (String)toCity.getSelectedItem();
              dday = (String)dDay.getSelectedItem();
              dmon = (String)dMonth.getSelectedItem();
              dyear = (String)dYear.getSelectedItem();
              adt = (String)adult.getSelectedItem();
              cab = (String)Cabin.getSelectedItem();
         public void actionPerformed(ActionEvent ae)
         if(ae.getActionCommand() == "Date")
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con = DriverManager.getConnection("jdbc:odbc:ds","sa", "");
              PreparedStatement stmt = con.prepareStatement("select ifno,vdtime,vatime,vdate1,vdate2,vdate3,efare from airways where fcity = ? and tcity = ? and vdate1 = ? and vdate2 = ? and vdate3 = ?");
              stmt.setString(1,ffcity);
              stmt.setString(2,ttcity);
              stmt.setString(3,dday);
              stmt.setString(4,dmon);
              stmt.setString(5,dyear);
              ResultSet d = stmt.executeQuery();
              /* int count=0;
              while(d.next())
              {count++;
              int i = 0;*/
              while(d.next())
              /*for(int j =1;j<=7;j++)
              data[i][j] = rs.getString(j);
              System.out.println(" " + data[i][j]);
              }i++;*/
              System.out.println(d.getInt(1));
              System.out.println(d.getDouble(2));
              catch(Exception ex)
                   System.out.println("Error occurred");
                   System.out.println("Error:"+ex);
              table.setVisible(true);
              table.setSize(300,200);
         private static void createAndShowGUI()
              JFrame.setDefaultLookAndFeelDecorated(true);
              Reservation r=new Reservation();
              JFrame frame = new JFrame("Reservation Form");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //r.pack();
              r.setVisible(true);
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){
                   public void run()
                        createAndShowGUI();
    in this object creation is not happening
    when i run this code ...
    only jtree is comming..
    how can i make it the values of seceted items to come in table
    i commented the parts that having error..
    when u uncomment it u will get the problem of this code

    please anyone

  • What's wrong with my code? please help....

    when display button is clicked it must diplay the remarks but it didn't happen...
    what's wrong with my code? please help
    here is my code.....
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Area extends Applet implements ItemListener,ActionListener
         {Label arlbl = new Label("AREA");
          Choice archc = new Choice();
          Label extlbl = new Label("EXPENDITURE TYPE");
          CheckboxGroup extchk = new CheckboxGroup();
              Checkbox fchk = new Checkbox("FOOD",extchk,true);
              Checkbox schk = new Checkbox("SHELTER",extchk,false);
              Checkbox echk = new Checkbox("EDUCATION",extchk,false);
              Checkbox uchk = new Checkbox("UTILITIES",extchk,false);
          Label exalbl = new Label("EXPENDITURE AMOUNT");
          TextField exatf = new TextField("",20);
          Label remlbl = new Label("REMARKS");
          TextField remtf = new TextField("",30);
          Button disbtn = new Button("DISPLAY");
          Button resbtn = new Button("RESET");
          String display;
          public void init()
              {add(arlbl);
               archc.add("MANILA");
               archc.add("MAKATI");
               archc.add("QUEZON");
               archc.add("PASAY");
               add(archc);
               archc.addItemListener(this);
               add(extlbl);
               add(fchk);
               fchk.addItemListener(this);
               add(schk);
               schk.addItemListener(this);     
               add(echk);
               echk.addItemListener(this);
               add(uchk);
               uchk.addItemListener(this);
               add(exalbl);
               add(exatf);
               add(remlbl);
               add(remtf);
               add(disbtn);
               disbtn.addActionListener(this);
               add(resbtn);
               resbtn.addActionListener(this);
         public void itemStateChanged(ItemEvent ex)
              {int n = archc.getSelectedIndex();
               if(n==0)
                   {if(fchk.getState())
                         {exatf.setText("10000.00");
                         display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("8500.00");
                        display = archc.getSelectedItem();
              if(n==1)
                   {if(fchk.getState())
                        {exatf.setText("5000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("11000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("7500.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
              if(n==2)
                   {if(fchk.getState())
                        {exatf.setText("13000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("7000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("27000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
              if(n==3)
                   {if(fchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("9000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("19000.00");
                        display = archc.getSelectedItem();
         public void actionPerformed(ActionEvent e)
              {if(e.getSource() == disbtn)
                    {String amtstr = exatf.getText();
                     int amt = Integer.parseInt(amtstr);
                        {if(amt > 8000)
                             {remtf.setText(display + " IS ABOVE BUDGET");
                        else
                             {remtf.setText(display + " IS BELOW BUDGET");
              if(e.getSource() == resbtn)
                   {archc.select(0);
                   fchk.setState(true);
                   schk.setState(false);
                   echk.setState(false);
                   uchk.setState(false);
                   exatf.setText("");
                   remtf.setText("");
    Edited by: lovely23 on Feb 28, 2009 11:24 PM

    Edit: thanks for cross-posting this question on another forum. I now see that I wasted my time trying to study your code in the java-forums to help you with an answer that had already been answered elsewhere (here). Do you realize that we are volunteers, that our time is as valuable as yours? Apparently not. Cross-post again and many here will not help you again. I know that I won't.

  • Event Handling Help needed please.

    Hi,
    I am writing a program to simulate a supermarket checkout. I have done the GUI and now i am trying to do the event handling. I have come up against a problem.
    I have a JCombobox called prodList and i have added an string array to it called prods . I have also created 2 more arrays with numbers in them.
    I want to write the code for if an item is selected from the combo box that the name from the array is shown in a textfield tf1, and also the price and stock no which correspond to the seclected item (both initialised in the other arrays) are also added to the textfield tf1.
    I have started writng the code but i am really stuck. Could someone please help me with this please. The code i have done so far is as follows(just the event handling code shown)
              public void ItemStateChange(ItemEvent ie){
              if(ie.getItemSelected()== prodList)
                   changeOutput();
              public void changeOutput()
                   if(ItemSelected ==0)
                        tf1.setText("You have selected" +a +b +c);
         }

    Do you say this because i missed the d of ItemStateChanged ?
    I have amended that but still i am getting the same errors class or enum expected. 4 of them relating to the itemStateChanged method.
    i will post my whole code if it helps
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Observer;  //new
    import java.util.Observable;//new
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    public class MySuperMktPro
         public MySuperMktPro()
              CheckoutView Check1 = new CheckoutView(1,0,0);
              CheckoutView Check2 = new CheckoutView(2,300,0);
              CheckoutView Check3 = new CheckoutView(3,600,0);
              CheckoutView Check4 = new CheckoutView(4,0,350);
              CheckoutView Check5 = new CheckoutView(5,600,350);
              OfficeView off111 = new OfficeView();
        public static void main(String[] args) {
             // TODO, add your application code
             System.out.println("Starting My Supermarket Project...");
             MySuperMktPro startup = new MySuperMktPro();
        class CheckoutView implements ItemListener , ActionListener
        private OfficeView off1;
         private JFrame chk1;
         private Container cont1;
         private Dimension screensize,tempDim;
         private JPanel pan1,pan2,pan3,pan4,pan5;
         private JButton buyBut,prodCode;
         private JButton purchase,cashBack,manual,remove,disCo;
         private JButton but1,but2,finaLi1,but4,but5,but6;
         private JTextArea tArea1,tArea2;
         private JTextField tf1,tf2,tf3,list2;
         private JComboBox prodList;
         private JLabel lab1,lab2,lab3,lab4,lab5,lab6,lab7;
         private int checkoutID; //New private int for all methods of this class
         private int passedX,passedY;
         private String prods[];
         private JButton rb1,rb2,rb3,rb4;
         private double price[];
         private int code[];
         public CheckoutView(int passedInteger,int passedX,int passedY)
              checkoutID = passedInteger; //Store the int passed into the method
            this.passedX = passedX;
            this.passedY = passedY;
              drawCheckoutGui();
         public void drawCheckoutGui()
              prods= new String[20];
              prods[0] = "Beans";
              prods[1] = "Eggs";
              prods[2] = "bread";
              prods[3] = "Jam";
              prods[4] = "Butter";
              prods[5] = "Cream";
              prods[6] = "Sugar";
              prods[7] = "Peas";
              prods[8] = "Milk";
              prods[9] = "Bacon";
              prods[10] = "Spaghetti";
              prods[11] = "Corn Flakes";
              prods[12] = "Carrots";
              prods[13] = "Oranges";
              prods[14] = "Bananas";
              prods[15] = "Snickers";
              prods[16] = "Wine";
              prods[17] = "Beer";
              prods[18] = "Lager";
              prods[19] = "Cheese";
              for(i=0; i<prods.length;i++);
              code = new int [20];
              code[0] = 1;
              code[1] = 2;
              code[2] = 3;
              code[3] = 4;
              code[4] = 5;
              code[5] = 6;
              code[6] = 7;
              code[7] = 8;
              code[8] = 9;
              code[9] = 10;
              code[10] = 11;
              code[11] = 12;
              code[12] = 13;
              code[13] = 14;
              code[14] = 15;
              code[15] = 16;
              code[16] = 17;
              code[17] = 18;
              code[18] = 19;
              code[19] = 20;
              for(b=0; b<code.length; b++);
              price = new double [20];
              price[0] = 0.65;
              price[1] = 0.84;
              price[2] = 0.98;
              price[3] = 0.75;
              price[4] = 0.45;
              price[5] = 0.65;
              price[6] = 1.78;
              price[7] = 1.14;
              price[8] = 0.98;
              price[9] = 0.99;
              price[10] = 0.98;
              price[11] = 0.65;
              price[12] = 1.69;
              price[13] = 2.99;
              price[14] = 0.99;
              price[15] = 2.68;
              price[16] = 0.89;
              price[17] = 5.99;
              price[18] = 1.54;
              price[19] = 2.99;
              for(c=0; c<code.length; c++);
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              chk1 = new JFrame();
              chk1.setTitle("Checkout #" + checkoutID); //Use the new stored int
              chk1.setSize(300,350);
              chk1.setLocation(passedX,passedY);
              chk1.setLayout(new GridLayout(5,1));
              //chk1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont1 = chk1.getContentPane();
              //chk1.setLayout(new BorderLayout());
                 pan1 = new JPanel();
                 pan2 = new JPanel();
              pan3 = new JPanel();
              pan4 = new JPanel();
              pan5 = new JPanel();
              //panel 1
              pan1.setLayout(new FlowLayout());
              pan1.setBackground(Color.black);          
              prodList = new JComboBox(prods);
              prodList.setMaximumRowCount(2);
              prodList.addItemListener(this);
              but1 = new JButton("Buy");
              but1.addActionListener(this);
              lab1 = new JLabel("Products");
              lab1.setForeground(Color.white);
              lab1.setBorder(BorderFactory.createLineBorder(Color.white));
              pan1.add(lab1);
              pan1.add(prodList);          
              pan1.add(but1);
              //panel 2
              pan2 = new JPanel();
              pan2.setLayout(new BorderLayout());
              pan2.setBackground(Color.black);
              lab3 = new JLabel("                                Enter Product Code");
              lab3.setForeground(Color.white);
              tArea2 = new JTextArea(8,10);
              tArea2.setBorder(BorderFactory.createLineBorder(Color.white));
              lab5 = new JLabel("  Tesco's   ");
              lab5.setForeground(Color.white);
              lab5.setBorder(BorderFactory.createLineBorder(Color.white));
              lab6 = new JLabel("Checkout");
              lab6.setForeground(Color.white);
              lab6.setBorder(BorderFactory.createLineBorder(Color.white));
              lab7 = new JLabel("You  selected                      ");
              lab7.setForeground(Color.cyan);
              //lab7.setBorder(BorderFactory.createLineBorder(Color.white));
              pan2.add(lab7,"North");
              pan2.add(lab6,"East");
              pan2.add(tArea2,"Center");
              pan2.add(lab5,"West");
              pan2.add(lab3,"South");
              //panel 3
              pan3 = new JPanel();
              pan3.setLayout(new FlowLayout());
              pan3.setBackground(Color.black);
              manual = new JButton("Manual");
              manual.addActionListener(this);
              manual.setBorder(BorderFactory.createLineBorder(Color.white));
              remove = new JButton("Remove");
              remove.addActionListener(this);
              remove.setBorder(BorderFactory.createLineBorder(Color.white));
              tf1 = new JTextField(5);
              pan3.add(manual);
              pan3.add(tf1);
              pan3.add(remove);
              //panel 4
              pan4 = new JPanel();
              pan4.setLayout(new FlowLayout());
              pan4.setBackground(Color.black);
              finaLi1 = new JButton("Finalise");
         //     finaLi1.addActionListener(this);
              cashBack = new JButton("Cashback");
              JTextField list2 = new JTextField(5);
              but4 = new JButton(" Sum Total");
              but4.addActionListener(this);
              but4.setBorder(BorderFactory.createLineBorder(Color.white));
              cashBack.setBorder(BorderFactory.createLineBorder(Color.white));
              pan4.add(cashBack);
              pan4.add(list2);
              pan4.add(but4);
              //panel 5
              pan5 = new JPanel();
              pan5.setLayout(new GridLayout(2,3));
              pan5.setBackground(Color.black);
              disCo = new JButton("Discount");
              disCo.addActionListener(this);
              disCo.setBorder(BorderFactory.createLineBorder(Color.black));
              but6 = new JButton("Finalise");
              but6.addActionListener(this);
              but6.setBorder(BorderFactory.createLineBorder(Color.black));
              rb1 = new JButton("Cash");
              rb1.addActionListener(this);
              rb1.setBorder(BorderFactory.createLineBorder(Color.black));
              rb2 = new JButton("Card");
              rb2.addActionListener(this);
              rb2.setBorder(BorderFactory.createLineBorder(Color.black));
              rb3 = new JButton("Cheque");
              rb3.addActionListener(this);
              rb3.setBorder(BorderFactory.createLineBorder(Color.black));
              rb4 = new JButton("Voucher");
              rb4.addActionListener(this);
              rb4.setBorder(BorderFactory.createLineBorder(Color.black));
              pan5.add(disCo);
              pan5.add(but6);
              pan5.add(rb1);
              pan5.add(rb2);
              pan5.add(rb3);
              pan5.add(rb4);
              //add the panels to the container        
              cont1.add(pan1);
              cont1.add(pan4);     
              cont1.add(pan2);
              cont1.add(pan3);          
              cont1.add(pan5);          
              chk1.setContentPane(cont1);
              chk1.setVisible(true);     
    class OfficeView
         private OfficeView off111;
         private JFrame offMod1;
         private JPanel pane1;
         private JButton refill;
         private Container cont11;
         private Dimension screensize;
         private JTextField tf11,tf12;
         public OfficeView()
              drawOfficeGUI();
         public void drawOfficeGUI()
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              offMod1 = new JFrame("Office Control");
              int frameWidth = 300;
              int frameHeight = 250;
              offMod1.setSize(frameWidth,frameHeight);
              offMod1.setLocation(300,350);
              offMod1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont11 = offMod1.getContentPane();
              pane1 = new JPanel();
              pane1.setBackground(Color.cyan);
              refill = new JButton("Refill");
              tf11 = new JTextField(25);
              tf12 = new JTextField(25);
              pane1.add(tf11);
              pane1.add(refill);
              pane1.add(tf12);
              cont11.add(pane1);
              offMod1.setContentPane(cont11);
              offMod1.setVisible(true);
              public void ItemStateChanged(ItemEvent ie)
                        if(ie.getItemSelected()== prodList)
                                  changeOutput();
              public void changeOutput()
                        if(ItemSelected ==0)
                                  tf1.setText("You have selected", +a +b +c);
                   }Message was edited by:
    fowlergod09

  • Gathering the data

    how do i make it so that when the radio button is clicked, a string of text is displayed below it? everytime i make an action listener for one of the radio buttons, my application won't run
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class swingMakeup implements ItemListener{
        JPanel cards; //a panel that uses CardLayout
        final static String BUTTONPANEL = "Meats";
        final static String TEXTPANEL = "Name Of Customer";
        final static String TEXTPANEL2 = "Number of Subs";
        final static String CHECKPANEL = "Fixins'";
        JRadioButton beef, turkey, sheep;
        JTextField name, number;
        public void addComponentToPane(Container pane) {
            //Put the JComboBox in a JPanel
            JPanel comboBoxPane = new JPanel();
            String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL, TEXTPANEL2, CHECKPANEL };
            JComboBox cb = new JComboBox(comboBoxItems);
            cb.setEditable(false);
            cb.addItemListener(this);
            comboBoxPane.add(cb);
            //Create the cards
            JPanel card1 = new JPanel();
            card1.add(beef=new JRadioButton("Beef Lips -- $5.00"));
            card1.add(turkey=new JRadioButton("Turkey Liver -- $4.00"));
            card1.add(sheep=new JRadioButton("Sheep Stomach -- $6.00"));
            JPanel card2 = new JPanel();
            card2.add(name=new JTextField("", 20));
            JPanel card3 = new JPanel();
            card3.add(number=new JTextField("", 20));
            JPanel card4 = new JPanel();
            card4.add(new JCheckBox("Lettuce"));
            card4.add(new JCheckBox("Tomato"));
            card4.add(new JCheckBox("Onion"));
            card4.add(new JButton("Submit Order"));
            //Create the panel that contains the cards
            cards = new JPanel(new CardLayout());
            cards.add(card1, BUTTONPANEL);
            cards.add(card2, TEXTPANEL);
            cards.add(card3, TEXTPANEL2);
            cards.add(card4, CHECKPANEL);
            pane.add(comboBoxPane, BorderLayout.PAGE_START);
            pane.add(cards, BorderLayout.CENTER);
        public void itemStateChanged(ItemEvent evt) {
            CardLayout cl = (CardLayout)(cards.getLayout());
            cl.show(cards, (String)evt.getItem());
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("swingMakeup");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            swingMakeup demo = new swingMakeup();
            demo.addComponentToPane(frame.getContentPane());
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    * Matthew Tye
    * Makeup Lab
    * 12-7-06
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class swingMakeup implements ItemListener, ActionListener{
        JPanel cards; //a panel that uses CardLayout
        final static String BUTTONPANEL = "Meats";
        final static String TEXTPANEL = "Name Of Customer";
        final static String TEXTPANEL2 = "Number of Subs";
        final static String CHECKPANEL = "Fixins'";
        JRadioButton beef, turkey, sheep;
        JTextField name, number;
        public void addComponentToPane(Container pane) {
            //Put the JComboBox in a JPanel
            JPanel comboBoxPane = new JPanel();
            String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL, TEXTPANEL2, CHECKPANEL };
            JComboBox cb = new JComboBox(comboBoxItems);
            cb.setEditable(false);
            cb.addItemListener(this);
            beef.addActionListener(this);
            comboBoxPane.add(cb);
            //Create the cards
            JPanel card1 = new JPanel();
            card1.add(beef=new JRadioButton
            ("Beef Lips -- $5.00"));
            card1.add(turkey=new JRadioButton
            ("Turkey Liver -- $4.00"));
            card1.add(sheep=new JRadioButton
            ("Sheep Stomach -- $6.00"));
            JPanel card2 = new JPanel();
            card2.add(name=new JTextField("", 20));
            JPanel card3 = new JPanel();
            card3.add(number=new JTextField("", 20));
            JPanel card4 = new JPanel();
            card4.add(new JCheckBox("Lettuce"));
            card4.add(new JCheckBox("Tomato"));
            card4.add(new JCheckBox("Onion"));
            card4.add(new JButton("Submit Order"));
            //Create the panel that contains the cards
            cards = new JPanel(new CardLayout());
            cards.add(card1, BUTTONPANEL);
            cards.add(card2, TEXTPANEL);
            cards.add(card3, TEXTPANEL2);
            cards.add(card4, CHECKPANEL);
            pane.add(comboBoxPane, BorderLayout.PAGE_START);
            pane.add(cards, BorderLayout.CENTER);
        public void actionPerformed (ActionEvent e)
        if(e.getSource()==beef){
        public void itemStateChanged(ItemEvent evt) {
            CardLayout cl = (CardLayout)(cards.getLayout());
            cl.show(cards, (String)evt.getItem());
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("swingMakeup");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            swingMakeup demo = new swingMakeup();
            demo.addComponentToPane(frame.getContentPane());
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

Maybe you are looking for