• Post Reply Bookmark Topic Watch Topic
  • New Topic

change background color of panel  RSS feed

 
burle sharma
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Program is not working. I want to use buttonPanel object in ColorAction class and the process is unknown to me . Please help.
package button;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonFrame extends JFrame
{
public JPanel buttonPanel;
private static final int DEFAULT_WIDTH=300;
private static final int DEFAULT_HEIGHT=200;

public ButtonFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");

buttonPanel = new JPanel();

buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);


add(buttonPanel);

ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}



}

class ColorAction implements ActionListener
{
private Color backgroundColor;
public ColorAction(Color c)
{
backgroundColor=c;
}

public void actionPerformed(ActionEvent e)
{
buttonPanel.setBackground(backgroundColor);
}
}
 
Piet Souris
Rancher
Posts: 1943
66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Burle,

you're close, but some things need to be done.

First of all, create a 'public static void main(String[] args)' method in your
ButtonFrame class. All that needs to be done in this main() is to create an
instance of your ButtonFrame, with 'new ButtonFrame();'

In your constructor, do the usual things at the end:


Finally, in your actionPerformed() method at the end, you issue
buttonPanel.setBackground(..);

This will only work if class ColorAction has knowledge of this buttonPanel,
which is not the case here. Easiest way to solve this is to make the class
ColorAction an innerclass of ButtonFrame.

But to make all this easy, watch the indentation of your code. It is now
quite hard to see where a method or class ends. Next time when showing
code on this forum, use the code tags.

Greetz,
Piet
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!