Im reading Core Java (Cay Horstmann) V I
And I came across this program.........
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MyFrame extends JFrame
{
private ButtonPanel buttonPanel;
public MyFrame()
{
setSize(300,200);
setLocation(570,350);
setTitle("Button Test");
buttonPanel=new ButtonPanel();
add(buttonPanel);
}
private class ButtonPanel extends JPanel
{
public void paintComponent(Graphics g)
{
JButton redButton=new JButton("Red");
JButton yellowButton=new JButton("Yellow");
JButton greenButton=new JButton("Green");
add(redButton);
add(yellowButton);
add(greenButton);
ColorAction setRed=new ColorAction(Color.RED);
ColorAction setYellow=new ColorAction(Color.YELLOW);
ColorAction setGreen=new ColorAction(Color.GREEN);
redButton.addActionListener(setRed);
yellowButton.addActionListener(setYellow);
greenButton.addActionListener(setGreen);
}
}
private class ColorAction implements ActionListener
{
private Color bgColor;
public ColorAction(Color c)
{
bgColor=c;
}
public void actionPerformed(ActionEvent e)
{
buttonPanel.setBackground(bgColor);
}
}
}
class JButtonTest
{
public static void main (String arg[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MyFrame buttonFrame=new MyFrame();
buttonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonFrame.setVisible(true);
}
} );
}
}
But I modified it. I created a new InnerClass for the button panel and drew the buttons using the paintComponent method. But in that book, they directly created an instance for JPanel in the Frame class itself and added buttons directly from constructor of the Frame class.
When I executed my code, I got three buttons and when I clicked a button, the BG color didnt change and instead the image of the button was drawn in the top left corner.
So where am I going wrong?