I have to make a small paint program using the GUI. I need to know how to use the combo box. I know I have to make an array with the list of colors but I don't know how to add it to an action listener and choose the items. I have one combo box for the color of the background and another for the color of the pencil/brush/whatever it's called.

I have searched for a way to do it, but all the sites, books and so on assume I'm writing everything from scratch instead of using the IDE

Can I get any help here?

you can use getSelectedItem() method of combo box to get what color user have choosen and set that color as background color.

I have to make a small paint program using the GUI. I need to know how to use the combo box. I know I have to make an array with the list of colors but I don't know how to add it to an action listener and choose the items. I have one combo box for the color of the background and another for the color of the pencil/brush/whatever it's called.

I have searched for a way to do it, but all the sites, books and so on assume I'm writing everything from scratch instead of using the IDE

Can I get any help here?

Take a look here:http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html however i must add if your using netbeans GUI builder, you could simple right click the combobox, Events->Action->Action Performed. Note this will create the action listener for you, and it will direct you to the method in which it will execute when an action is performed, in their you could put your code and viola. but if you're doing it by hand its a slight bit different, check the link it will help you both ways

you can use getSelectedItem() method of combo box to get what color user have choosen and set that color as background color.

And how would I do that? To set a background, for the panel, the parameter has to be a Color object. And also for the getSelectedItem() function, what object type should the variable that holds the result of getSelectedItem()?

And how would I do that? To set a background, for the panel, the parameter has to be a Color object. And also for the getSelectedItem() function, what object type should the variable that holds the result of getSelectedItem()?

It should be a String object look at the link i gave.

So instead of having

Color background_color[] =  {Color.white, Color.blue, Color. red, Color.green, Color.orange, Color.black, Color.yellow, Color.pink};

I should have

String background_color[] = {white, blue, red, green, orange, black, yellow, pink};

?

Well setBackground() accepts only a Color object, as well as getSelectedItem(). I see tehy use a String there but I'm not totally sure why.

So instead of having

Color background_color[] =  {Color.white, Color.blue, Color. red, Color.green, Color.orange, Color.black, Color.yellow, Color.pink};

I should have

String background_color[] = {white, blue, red, green, orange, black, yellow, pink};

?

That looks right if that whats being used in the combobox, but i cant be sure without seeing your code

import java.awt.Color;


public class PaintTool extends javax.swing.JFrame {

    /** Creates new form PaintTool */
    public PaintTool() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        Area = new javax.swing.JPanel();
        Settings = new javax.swing.JPanel();
        ToolCombo = new javax.swing.JComboBox();
        PanelCombo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Area.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout AreaLayout = new javax.swing.GroupLayout(Area);
        Area.setLayout(AreaLayout);
        AreaLayout.setHorizontalGroup(
            AreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 545, Short.MAX_VALUE)
        );
        AreaLayout.setVerticalGroup(
            AreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 283, Short.MAX_VALUE)
        );

        Settings.setBorder(javax.swing.BorderFactory.createTitledBorder("Settings"));

        ToolCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Black", "Blue", "Red", "Green", "Orange", "White", "Yellow", "Pink" }));
        ToolCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ComboBoxChange(evt);
            }
        });

        PanelCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "White", "Blue", "Red", "Green", "Orange", "Black", "Yellow", "Pink" }));
        PanelCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PanelComboActionPerformed(evt);
            }
        });

        jLabel1.setText("Tool Color");

        jLabel2.setText("PanelCombo");

        javax.swing.GroupLayout SettingsLayout = new javax.swing.GroupLayout(Settings);
        Settings.setLayout(SettingsLayout);
        SettingsLayout.setHorizontalGroup(
            SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ToolCombo, 0, 118, Short.MAX_VALUE)
                    .addComponent(PanelCombo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        SettingsLayout.setVerticalGroup(
            SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(SettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ToolCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(34, 34, 34)
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PanelCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(219, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Area, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Settings, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addComponent(Area, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(128, Short.MAX_VALUE)
                        .addComponent(Settings, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(30, 30, 30))
        );

        pack();
    }// </editor-fold>

private void ComboBoxChange(java.awt.event.ItemEvent evt) {                                
// TODO add your handling code here:
    
}                               

private void PanelComboActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaintTool().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel Area;
    private javax.swing.JComboBox PanelCombo;
    private javax.swing.JPanel Settings;
    private javax.swing.JComboBox ToolCombo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
    
    Color paint[] = {Color.BLACK, Color.BLUE, Color. RED, Color.GREEN, Color.ORANGE, Color.WHITE, Color.YELLOW, Color.PINK};
    Color background_color[] =  {Color.white, Color.blue, Color. red, Color.green, Color.orange, Color.black, Color.yellow, Color.pink};
    Object background = PanelCombo.getSelectedItem();
}

This is the code that I have. Most of it is generated by the IDE and I cannot edit such as everything in private void initComponents.
The last lines are where I have initialized the items for the Combo Box. I don't really understand how they can be used in the program if they are at the end, but it works. The Color paint[] is what I will use for the foreground color later on.

import java.awt.Color;


public class PaintTool extends javax.swing.JFrame {

    /** Creates new form PaintTool */
    public PaintTool() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        Area = new javax.swing.JPanel();
        Settings = new javax.swing.JPanel();
        ToolCombo = new javax.swing.JComboBox();
        PanelCombo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Area.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout AreaLayout = new javax.swing.GroupLayout(Area);
        Area.setLayout(AreaLayout);
        AreaLayout.setHorizontalGroup(
            AreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 545, Short.MAX_VALUE)
        );
        AreaLayout.setVerticalGroup(
            AreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 283, Short.MAX_VALUE)
        );

        Settings.setBorder(javax.swing.BorderFactory.createTitledBorder("Settings"));

        ToolCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Black", "Blue", "Red", "Green", "Orange", "White", "Yellow", "Pink" }));
        ToolCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ComboBoxChange(evt);
            }
        });

        PanelCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "White", "Blue", "Red", "Green", "Orange", "Black", "Yellow", "Pink" }));
        PanelCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PanelComboActionPerformed(evt);
            }
        });

        jLabel1.setText("Tool Color");

        jLabel2.setText("PanelCombo");

        javax.swing.GroupLayout SettingsLayout = new javax.swing.GroupLayout(Settings);
        Settings.setLayout(SettingsLayout);
        SettingsLayout.setHorizontalGroup(
            SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ToolCombo, 0, 118, Short.MAX_VALUE)
                    .addComponent(PanelCombo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        SettingsLayout.setVerticalGroup(
            SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(SettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ToolCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(34, 34, 34)
                .addGroup(SettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PanelCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(219, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Area, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Settings, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addComponent(Area, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(128, Short.MAX_VALUE)
                        .addComponent(Settings, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(30, 30, 30))
        );

        pack();
    }// </editor-fold>

private void ComboBoxChange(java.awt.event.ItemEvent evt) {                                
// TODO add your handling code here:
    
}                               

private void PanelComboActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaintTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaintTool().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel Area;
    private javax.swing.JComboBox PanelCombo;
    private javax.swing.JPanel Settings;
    private javax.swing.JComboBox ToolCombo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
    
    Color paint[] = {Color.BLACK, Color.BLUE, Color. RED, Color.GREEN, Color.ORANGE, Color.WHITE, Color.YELLOW, Color.PINK};
    Color background_color[] =  {Color.white, Color.blue, Color. red, Color.green, Color.orange, Color.black, Color.yellow, Color.pink};
    Object background = PanelCombo.getSelectedItem();
}

This is the code that I have. Most of it is generated by the IDE and I cannot edit such as everything in private void initComponents.
The last lines are where I have initialized the items for the Combo Box. I don't really understand how they can be used in the program if they are at the end, but it works. The Color paint[] is what I will use for the foreground color later on.

The reason it works even though its at the end, you see that last '}' that means they are all still declared within the class which is where global variables are declared, and why Object background? i told you getSelectedItem() returns a String

OK, thanks. So any idea what I do from here?

OK, thanks. So any idea what I do from here?

Look at my edited post. then you would compare the selected Item to the different colours and set the one thats most appropriate/matches...please take a look at the link it shows you more then i could ever explain

Well actually, even in the link that you gave( I had already looked through at link before you even recommended it) the returned value from getSelectedItem is type casted into a String. It also says it when I tried changing it to a String.
Thanks though.

OK, thanks. So any idea what I do from here?

well from what i see from your code first step would be putting this:Object background = PanelCombo.getSelectedItem(); into your ComboBoxChange method, as you only want to get the selected item when the cobobox changes. next use something like this is in the comboboxchange method:

Object background = PanelCombo.getSelectedItem();

if(background.equals("White") {
//set color to white
}else if(...) {
}

i see also you have: PanelComboActionPerformed() ? if these two methods do the same thing you dont need both, only the one thats best suited

Thanks. Using the if statements is what I was running from in the first place. I see several sites using other ways.
Like this:

String c;
Color color;  

c = (String)PanelCombo.getSelectedItem();	
color = (Color)Color.getColor(c);
		
Area.setBackground(color);

But this doesn't work, so I guess it's if statements for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.