列表的选定项目在JAVA中不起作用

时间:2017-05-31 22:06:19

标签: java

如果单击该按钮,则会出现错误。这怎么可能? 我的结果必须是,如果我点击按钮,标签" text1"应该得到ComboBox的文本。

import javax.swing.*;
import java.awt.*;

public class Naveed extends JFrame {

    public static void main(String[] args) {
        JFrame frame = new Naveed();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setTitle("Rechthoek");
        Paneel paneel = new Paneel();
        frame.setContentPane(paneel);
        frame.setVisible(true);
    }
}

//

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Paneel extends JPanel {
    private JComboBox abc;
    private JLabel text1;

    public Paneel() {
        String[] items = {"Item1", "Item2", "Item3"};
        JComboBox abc = new JComboBox(items);
        JButton button1 = new JButton("Click");
        button1.addActionListener(new knopHandler());
        JLabel text1 = new JLabel("Result");

        add(abc);
        add(button1);
        add(text1);
    }

    class knopHandler implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            String s = abc.getSelectedItem().toString();
            text1.setText(s);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有正确分配 abc text1 。像这样更改代码:

Any