ActionListener

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import java.awt.*;

import javax.swing.*;

publicclass ChangeColorViewer

{

publicstaticvoid main(String[] arg)

{

//Creates the frame

JFrame frame =new JFrame();

finalint FRAME_WIDTH = 400;

finalint FRAME_HEIGHT = 400;

JButton button =new JButton("Red");

JButton button2 =new JButton("Yellow");

JButton button3 =new JButton("Green");

JPanel panel =new JPanel();

panel.add(button);

panel.add(button2);

panel.add(button3);

frame.add(panel);

class RedButtonListenerimplements ActionListener

{

publicvoid actionPerformed(ActionEvent event)

{

panel.setBackground(Color.RED);

}

}

frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

frame.setTitle("The Changing Color Game");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

I am trying to write a program that will change the background color of the panel when you click on 1 of 3 buttons. I get this error messaage when I compile my source code that I have so far..

C:\Documents and Settings\Drew\My Documents\NDSU 1st semester\Computer Science\lab 12\ChangeColorViewer.java:42: local variable panel is accessed from within inner class; needs to be declared final

panel.setBackground(Color.RED);

^

1 error

Tool completed with exit code 1

I was wondering how I might set "panel" to private so that I can use it in my Listeners......

thanks

[3012 byte] By [sourcer3a] at [2007-10-2 6:24:40]
# 1

> >

> class RedButtonListener implements ActionListener

> {

> public void actionPerformed(ActionEvent event)

> {

> panel.setBackground(Color.RED);

> }

> }

>

> C:\Documents and Settings\Drew\My Documents\NDSU 1st

> semester\Computer Science\lab

> 12\ChangeColorViewer.java:42: local variable panel is

> accessed from within inner class; needs to be

> declared final

> panel.setBackground(Color.RED);

> ^

The way you're cramming everything into main like that you're going to get those problems..........

but as a simple hack just do this:

final JPanel xPanel = panel;

//.....................................................................

class RedButtonListener implements ActionListener

{

public void actionPerformed(ActionEvent event)

{

xPanel.setBackground(Color.RED);

}

}

> I was wondering how I might set "panel" to private so

> that I can use it in my Listeners......

Like any othe thing, declare it private, but this ain't going to help the rest of your code much.

WIlfred_Deatha at 2007-7-16 13:26:32 > top of Java-index,Java Essentials,New To Java...
# 2
Another problem, where are you adding the ActionListener to the buttons?
floundera at 2007-7-16 13:26:32 > top of Java-index,Java Essentials,New To Java...