简体   繁体   中英

How do I declare a JComboBox?

I was creating a program to work with a drop-down list, but I got stuck at the line of declaration of JComboBox box, I get these error messages: Multiple markers at this line - The constructor JComboBox(String[]) is undefined - Line breakpoint:JComboBox [line: 25] - JComboBox() No matter how I try to define JComboBox, I get some sort of error. Please help me with it.

Here's the code of the public class:

    import javax.swing.*;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JRadioButton;
    import javax.swing.ButtonGroup;
    import java.awt.event.ItemListener;
    import java.awt.event.ItemEvent;

    public class JComboBox extends JFrame {

        private JComboBox box;
        private JLabel picture;

        private static String[] filename = { "p.png", "i.png" };
        private Icon pics[] = { new ImageIcon(getClass().getResource(filename[0])),
                new ImageIcon(getClass().getResource(filename[1])) };

        public JComboBox() {

            super("This is the title");
            setLayout(new FlowLayout());

            JComboBox box = new JComboBox(filename);

            box.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent event) {
                    if (event.getStateChange() == ItemEvent.SELECTED) {
                        picture.setIcon(pics[box.getSelectedIndex()]);
                    }
                }
            });

            add(box);
            picture = new JLabel(pics[0]);
            add(picture);

        }

    }

And here's the code of the main class:

    import javax.swing.*;

    public class JComboBox1 extends JFrame {

        public static void main(String[] args) {


            JComboBox Box = new JComboBox();
            Box.setVisible(true);
            Box.setSize(400,400);
            Box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }

    }

Thank you.

Your problem, as @Andy mentioned is that you have a collision in the name of your class and the swing component. If you absolutely must name your class JComboBox you'll have to reference the swing component by the fully-qualified name, as such

public class JComboBox extends JFrame {

    private javax.swing.JComboBox box;

If you hover over your private instance with an IDE you should see the fully-qualified name matching the package in which you've created your JComboBox class. Save yourself some pain and rename your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM