将动作侦听器添加到JComboBox [英] adding an action listener to a JComboBox

查看:104
本文介绍了将动作侦听器添加到JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想将组合框中的选定选项打印到文本字段。请解释出什么问题了,因为我必须完成该操作&在课堂上解释它。任何帮助将不胜感激。

I just want to print the selected option in the combo box, to a textfield. Please explain what's wrong because i have to complete it & explain it in class. Any help would be greatly appreciated. Thanks in advance.


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

public class App3 extends JFrame implements ActionListener
{
    private JPanel boxPanel,textPanel;
    private JLabel selectName,selectedName;
    private JComboBox nameCombo;
    private JTextField valueOfSelectedName;
    private Container c;

    public App3()
    {
        super("Combo example");
        setup();
        setSize(200,200);
        setLocation(50,50);
        show();
    }

    public void setup()
    {
        c = getContentPane();

        boxPanel = new JPanel();
        c.add(boxPanel,BorderLayout.NORTH);

        selectName = new JLabel("Select Name : ");
        selectedName = new JLabel("The selected Name : ");

        String[] names = {"Ramila","Hashan","Shaad","Gus","Mahasen","Hasaru","Shabba"};
        nameCombo = new JComboBox(names);
        nameCombo.addActionListener(this);

        valueOfSelectedName = new JTextField(10);

        boxPanel.add(selectName);
        boxPanel.add(nameCombo);

        c.add(textPanel,BorderLayout.CENTER);

        textPanel.add(selectedName);
        textPanel.add(valueOfSelectedName);

    }

    public void actionPerformed(ActionEvent e) 
    {
        JComboBox nameCombo = (JComboBox)e.getSource();
        String newSelection = (String)nameCombo.getSelectedItem();
        valueOfSelectedName.setText(newSelection);
    }

    public static void main(String args[])
    {
        App3 a = new App3();
    }
}

我没有任何编译时错误,当我运行它时得到这些错误。

i don't get any compile time errors, i get these errors when i run it.


Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1041)
    at java.awt.Container.add(Container.java:927)
    at App3.setup(App3.java:42)
    at App3.(App3.java:16)
    at App3.main(App3.java:58)

Process completed.


推荐答案

private JPanel boxPanel,textPanel;
...
textPanel = new JPanel();

您尚未创建JPanel对象,因此textPanel指向null,这就是为什么正在生成Exception的原因抛出。创建对象,一切都会正常工作

You have not created the JPanel object hence, textPanel is pointing to null which is why the Exception is being thrown. Create the object and everything should work fine

这篇关于将动作侦听器添加到JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆