[newbie] NullPointerException when accessing ActionEvent handler
Code:
ColorAction.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
public class ColorAction implements ActionListener {
public ColorAction (Color c)
{
backgroundColor = c;
}
public void actionPerformed(ActionEvent event) {
[B]buttonPanel.setBackground(backgroundColor);[/B]
//breaks here
}
private Color backgroundColor;
private JPanel buttonPanel;
}
ButtonFrame.java
import java.awt.Color;
import javax.swing.*;
public class ButtonFrame extends JFrame {
public ButtonFrame() {
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//create buttons
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
JPanel buttonPanel = new JPanel();
//add buttons to panel
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
//add panel to frame
add(buttonPanel);
//create button Actions
ColorAction yellowAction = new ColorAction(Color.yellow);
ColorAction blueAction = new ColorAction(Color.blue);
ColorAction redAction = new ColorAction(Color.red);
//associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
private static final int DEFAULT_WIDTH=300;
private static final int DEFAULT_HEIGHT=200;
}
Test.java
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{ //FIX Does not work!!
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
);
}
}
:confused:
I tried creating a similar interface in NetBeans so that I can try to compare side-by-side, however, somehow the UI elements don't show up when running Java Projects. I noted that the code breaks at this point though:
Code:
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
backgroundPanel.setBackground(Color.yellow);
//cannot be references from a static context.
}
I think NetBeans has a different style of connecting events.
...