2017-05-31 5 views
0

ボタンをクリックすると、エラーが表示されます。これはどのように可能ですか? ボタンをクリックすると、 "text1"というラベルがComboBoxのテキストを取得する必要があります。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"); 
関連する問題