I am trying to make a GUI in Java, using something along these lines:
public class GUIApp
{
DrawingPanel dp;
buttonPanel bp;
ova = Oval;
public GUIApp()
{
JFrame win = new JFrame("Drawing App");
dp = new DrawingPanel();
bp = new buttonPanel(this);
//Settings for panels and frame
ova = new Oval(100,100,100,100);
}
public void setOval(int c){
//Change color of oval
}
}
Then in my buttonPanel class I have this:
public class ButtonPanel extends JPanel
{
private JButton btnRed, btnGreen, btnBlue;
public ButtonPanel(GUIApp d)
{
ButtonListener listener = new ButtonListener();
btnRed = new JButton("Red");
btnGreen = new JButton("Green");
btnBlue = new JButton("Blue");
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
setBackground(Color.lightGray);
GridLayout grid = new GridLayout(3,1);
add(btnRed,grid);
add(btnGreen,grid);
add(btnBlue,grid);
}
private class ButtonListener implements ActionListener{
public void clickButton(ActionEvent event) {
Object location = event.getSource();
if (location == btnRed){
d.setOval(1);
}
else if(location == btnGreen){
d.setOval(2);
}
else if(location == btnBlue){
d.setOval(3);
}
}
}
}
But netbeans gives an error for the inner ButtonListener class, and I don’t know why. I also don’t know how to correctly call the setOval from within that class to the GUIApp class. What am I doing wrong?
The problem is that when you implement
ActionListeneryou must define the methodactionPerformed(ActionEvent e); you haven’t done that in yourButtonListenerclass. You can’t name the method anything that you want (as you’ve done withclickButton), so you should just rename yourclickButtonmethod toactionPerformed(and go ahead and add an@Overrideannotation too).Now in order to call
d.setOvalfrom within your inner class,dmust be in scope when theactionPerformedmethod is called. There are a couple ways to achieve this: you could makeda member variable of your class, or you could define yourButtonListeneras an anonymous class.For example, if you saved
das a member variable then your code would look like this:Or, you could use an anonymous class like this:
Note: Notice how I also changed the use of
==toequals()for object equality.