2017-05-31 67 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"); 
相關問題