Java JCheckBox ItemListener使程序无法正常工作

时间:2013-09-11 21:04:29

标签: java swing actionlistener

我将程序最小化以仅包含问题,并且我尝试编码完全按照我从许多示例中理解的那样编写代码。当我使用ActionListener时,我解决了问题。但我想知道为什么使用ItemListener,复选框无法正常运行。 如果我在没有ItemListener的情况下运行我的程序,它可以正常工作。使用此ItemListener,checkBox不会更改状态。

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class omaJFrame extends JFrame{
    private JCheckBox checkBox1;

    public omaJFrame() {
        super("Window Title");

        TheHandler handler = new TheHandler();
        setLayout(new FlowLayout());

        checkBox1 = new JCheckBox("Checkbox 1");
        add(checkBox1);
        checkBox1.addItemListener(handler); 
    }

    private class TheHandler implements ItemListener {
        String output = "";

        public void itemStateChanged(ItemEvent event) {
            if (event.getItem()==checkBox1)
                output = String.format("%s", checkBox1.isSelected());
            JOptionPane.showMessageDialog(null, output); 
        }
    }
}

import javax.swing.JFrame;
public class EventHandlerMain {
    public static void main(String[] args) {
        omaJFrame window = new omaJFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(350,200);
        window.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:1)

适合我。另请注意,应在event dispatch thread上构建和操作Swing GUI对象

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class OmaJFrame extends JFrame {

    private JCheckBox checkBox1;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                OmaJFrame f = new OmaJFrame();
            }
        });
    }

    public OmaJFrame() {
        super("Window Title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        TheHandler handler = new TheHandler();
        setLayout(new FlowLayout());
        checkBox1 = new JCheckBox("Checkbox 1");
        add(checkBox1);
        checkBox1.addItemListener(handler);
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    }

    private class TheHandler implements ItemListener {

        String output = "";

        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getItem() == checkBox1) {
                output = String.format("%s", checkBox1.isSelected());
            }
            JOptionPane.showMessageDialog(null, output);
        }
    }
}