0

If I click on the button, an error appears. How is this possible? My result has to be that if I click on the button, the label "text1" should get the text of the 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);
        }
    }
}
Soccerlife
  • 671
  • 3
  • 9
  • 20
  • 2
    Telling us what error appears would be useful. – E.D. May 31 '17 at 22:09
  • Look up "variable shadowing" as you're shadowing the text1 variable by **re-declaring** it in the constructor. Don't do this. And yes, in the future, please ask a more complete question, one with the error message and an indication of which line throws it. – Hovercraft Full Of Eels May 31 '17 at 22:10
  • For example, change `JLabel text1 = new JLabel("Result");` to `text1 = new JLabel("Result");` so you're not re-declaring the variable and making the constructor's text1 a local variable. – Hovercraft Full Of Eels May 31 '17 at 22:11

1 Answers1

0

You are not properly assigning abc and text1. Change the code like this:

        String[] items = {"Item1", "Item2", "Item3"};
        abc = new JComboBox(items);
        JButton button1 = new JButton("Click");
        button1.addActionListener(new knopHandler());
        text1 = new JLabel("Result");
tsolakp
  • 5,858
  • 1
  • 22
  • 28