Hi, I'm trying to build a two classes:
1) One to add the panels
2) The panel class
The code compiles fine, but when i run it, i get a null pointer exception on line 52 of TestFrame (the class)
import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; /** This frame contains a text field and a control panel to change the font of the text. */ public class TestFrame extends JFrame { /** Constructs the frame. */ public TestFrame() { // Construct text sample sampleField = new JLabel("Big Java"); add(sampleField, BorderLayout.CENTER); // This listener is shared among all components class ChoiceListener implements ActionListener { public void actionPerformed(ActionEvent event) { setSampleFont(); } } listener = new ChoiceListener(); createControlPanel(); setSampleFont(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } /** Creates the control panel to change the font. */ public void createControlPanel() { JPanel facenamePanel = comboBox.createComboBox(); // Line up component panels JPanel controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(3, 1)); controlPanel.add(facenamePanel); // Add panels to content pane add(controlPanel, BorderLayout.SOUTH); } /** Gets user choice for font name, style, and size and sets the font of the text sample. */ public void setSampleFont() { // Get font name String facename = (String) facenameCombo.getSelectedItem(); // Set font of text field sampleField.setFont(new Font(facename,Font.BOLD,32)); sampleField.repaint(); } private JLabel sampleField; private JComboBox facenameCombo; private ActionListener listener; private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 400; private ComboBox comboBox; }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JPanel; /** This frame contains a text field and a control panel to change the font of the text. */ public class ComboBox extends JPanel { /** Creates the combo box with the font style choices. @return the panel containing the combo box */ public JPanel createComboBox() { facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); facenameCombo.addItem("Monospaced"); facenameCombo.setEditable(true); facenameCombo.addActionListener(listener); JPanel panel = new JPanel(); panel.add(facenameCombo); return panel; } private JComboBox facenameCombo; private ActionListener listener; }