Zmiana textu labela po kliknięciu przycisku.

0

Witam,

Jako totalnie początkujący postanowiłem przerzucić się z Delphi w Javę, jako że najprościej się nauczyć tworząc proste przykłady postanowiłem napisać program który po naciśnięciu button zmienia text labela. Niestety przy tym kodzie wywala błedem:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import java.awt.Label;


public class wwiinn {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					wwiinn window = new wwiinn();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public wwiinn() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 524, 353);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		Label label1 = new Label("New label");
		label1.setBounds(267, 145, 68, 21);
		frame.getContentPane().add(label1);
		
		JButton button1 = new JButton("przycisk");
		button1.addActionListener(new Conditionaliter() {
			public void actionPerformed(ActionEvent arg0) {
				label1.setText("yyyyyy");
			}
		});
		button1.setBounds(49, 141, 117, 25);
		frame.getContentPane().add(button1);
		
	}
}

Błąd:

 Description	Resource	Path	Location	Type
Cannot refer to a non-final variable label1 inside an inner class defined in a different method	wwiinn.java	/aaa/src	line 54	Java Problem

Czy może mi to ktoś wytłumaczyć czemu wyrzuca błąd, chodzi dokładnie o ten fragment:

 		JButton button1 = new JButton("przycisk");
		button1.addActionListener(new Conditionaliter() {
			public void actionPerformed(ActionEvent arg0) {
				label1.setText("yyyyyy");

... przecież wcześniej jest zadeklarowany label1...

0

zmień

button1.addActionListener(new Conditionaliter() {

na

button1.addActionListener(new ActionListener() {

swoją drogą skąd wziąłeś new Conditionaliter()??

0

Po tej zmianie ten sam błąd:

		Label label1 = new Label("New label");
		label1.setBounds(267, 145, 68, 21);
		frame.getContentPane().add(label1);
		
		JButton button1 = new JButton("przycisk");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				**label1.setText("yyyyyy");**
			}	
 Description	Resource	Path	Location	Type
Cannot refer to a non-final variable label1 inside an inner class defined in a different method	wwiinn.java	/aaa/src	line 54	Java Problem
0

Ty piszesz lodówką ten kod? Każde normalne IDE podpowie ci od razu jako quick fix zeby zrobić final Label label1 = new Label("New label");

1 użytkowników online, w tym zalogowanych: 0, gości: 1