What I am trying to do is italicise the text inside a JButton, but it throws a Null Pointer Exception.
This only happens when I click the JButton.
I have 3 classes, Frame.java, Action.java and Button.java .
The Null Pointer Exception is thrown in Action.java at the line
callTo.setFont(newFont);, on line 27.I use JDK11 in Visual Studios Code
Frame.java:
import java.awt.*;
import java.util.HashMap;
import javax.swing.*;
public class Frame {
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
static HashMap<String, JButton> buttons = new HashMap<String, JButton>();
static HashMap<JButton, JLabel> italiciseButtons = new HashMap<JButton, JLabel>();
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(1600, 1000));
ImageIcon icon = new ImageIcon("C:\\Users\\Patrick\\Downloads\\DragonworldIslandsLogo.png");
frame.setIconImage(icon.getImage());
JButton yeet = Button.makeButton("yeet", "Yeet!", Color.GREEN);
yeet.addActionListener(new Action("italicise", yeet));
panel.add(yeet);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Action.java:
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import javax.swing.*;
public class Action implements ActionListener {
HashMap<JButton, String> buttonCalls = new HashMap<JButton, String>();
JLabel callTo;
public Action(String call, JButton callWith) {
if (call.equals("italicise")) {
callTo = Frame.italiciseButtons.get(callWith);
buttonCalls.put(callWith, call);
}
}
@Override
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
String called = buttonCalls.get(source);
if (called.equals("italicise")) {
Font font = source.getFont();
Font newFont = font.deriveFont(Font.ITALIC);
// THE LINE BELOW HAS THE PROBLEM!
callTo.setFont(newFont);
callTo.repaint();
}
}
}
Button.java:
import java.awt.*;
import javax.swing.*;
public class Button {
public static JButton makeButton(String buttonName, String buttonText, Color buttonColour) {
JButton button = new JButton(buttonText);
Frame.buttons.put(buttonName, button);
button.setFont(new Font("Roboto Mono", Font.PLAIN, 18));
if (buttonColour == Color.BLACK) {
button.setForeground(Color.WHITE);
}
button.setBackground(buttonColour);
button.setFocusPainted(false);
return button;
}
}
Thank you ahead of time!