2017-05-31 84 views
0

如果单击按钮,则会显示错误。这怎么可能? 我的结果是,如果我点击按钮,标签“text1”应该获得组合框的文本。列表中的选定项目在JAVA中不起作用

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); 
     } 
    } 
} 
+2

告诉我们什么错误显示将是有益的。 –

+0

通过**在构造函数中重新声明**来查找“变量阴影”,因为您正在隐藏text1变量。不要这样做。是的,未来,请提出一个更完整的问题,其中一个提供错误消息,并指出哪一行将其引发。 –

+0

例如,将'JLabel text1 = new JLabel(“Result”);'更改为'text1 = new JLabel(“Result”);'这样你就不会重新声明变量并使构造函数的text1成为局部变量。 –

回答

0

你没有正确分配ABC文本1。改变这样的代码:

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