使用 ActionListener 更改字体大小
Change font size with ActionListener
我需要创建一个侦听器,当我单击 JMenuItem
时它会更改字体大小。但是,我对不同的部分有不同的标签,所以当我更改字体大小时,当程序其他部分的标签被调用但未激活时,它会向我抛出一个错误。基本上我不能一次更改所有字体。
我试过使用 if 语句,但出于某种原因,似乎只有第一个有效!别人给我一个nullPointerException
.
到目前为止,这是我的侦听器代码..
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class financeFormula extends JFrame {
private JMenu fileMenu;
private JMenu textMenu;
private JMenuItem exitItem;
private JMenuItem fontSize;
private JMenuItem help;
private JPanel presentValuePanel;
private JPanel financeFinderPanel;// A panel container
private JLabel principalMessage;
private JLabel yearlyRateMessage;
private JLabel termYearMessage;
private JPanel simpleInterestPanel;
private JPanel doublingTimePanel;
private JPanel compoundInterestPanel;
private JLabel NONEMessage;
private JLabel imageLabel;
private JLabel label;// A message to display
private JMenuBar menuBar;
private JTextField principalText; // To hold user input
private JButton calcButton; // Performs calculation
private final int WINDOW_WIDTH = 600; // Window width
private final int WINDOW_HEIGHT = 600; // Window height
private JTextField yearlyRateText;
private JTextField termYearText;
DecimalFormat dc =new DecimalFormat("####0.00"); //formater
private JComboBox financeBox;
double principal = 400.0;
double yearlyRate = .04;
double termYears = 4.0;
private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
"Doubling time", "Compound interest", "Decaf"};
//financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);
/**
* Constructor
*/
public financeFormula()
{
// Call the JFrame constructor.
super("Finance Class");
// Set the size of the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify what happens when the close
// button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame.
financeFinderPanel();
setLayout(new BorderLayout());
//buildPanel();
menuBar = new JMenuBar();
//buildFileMenu();
buildTextMenu();
//menuBar.add(fileMenu);
menuBar.add(textMenu);
setJMenuBar(menuBar);
// Add the panel to the frame's content pane.
add(financeFinderPanel);
//add(panel);
// Display the window.
setVisible(true);
}
private void financeFinderPanel()
{
// Create a panel to hold the combo box.
financeFinderPanel = new JPanel();
//create label
label = new JLabel("Pick your formula");
//ImageIcon funnyImage = new ImageIcon("funny.gif");
//imageLabel = new JLabel();
//imageLabel.setLocation(50, 55);
label.setForeground(Color.BLUE);
// Create the combo box
financeBox = new JComboBox(financeFormulas);
//imageLabel.setIcon(funnyImage);
// Register an action listener.
financeBox.addActionListener(new financeBoxListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
// Add the combo box to the panel.
financeFinderPanel.add(financeBox);
financeFinderPanel.add(label);
// financeFinderPanel.add(imageLabel);
}
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
//buildFileMenu();
buildTextMenu();
// Add the file and text menus to the menu bar.
//menuBar.add(fileMenu);
menuBar.add(textMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
public void buildTextMenu(){
fontSize = new JMenuItem("Large font");
fontSize.setMnemonic(KeyEvent.VK_2);
fontSize.addActionListener(new FontListener());
textMenu = new JMenu("Text");
textMenu.add(fontSize);
}
private void presentValuePanel()
{
// Create the label, text field, and button components.
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Present Value");
//fontButton = new JButton("Enlarge Font");
// Add an action listener to the button.
//calcButton.addActionListener(new CalcButtonListener());
//calcButton.addActionListener(new financeFormListener());
//fontButton.addActionListener(new FontListener());
// Create a panel to hold the components.
presentValuePanel = new JPanel();
// Add the label, text field, and button to the panel.
presentValuePanel.add(principalMessage);
presentValuePanel.add(principalText);
presentValuePanel.add(yearlyRateMessage);
presentValuePanel.add(yearlyRateText);
presentValuePanel.add(termYearMessage);
presentValuePanel.add(termYearText);
presentValuePanel.add(calcButton);
//presentValuePanel.add(fontButton);
}
private void simpleInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Simple Interest");
simpleInterestPanel = new JPanel();
// calcButton.addActionListener(new financeFormListener());
simpleInterestPanel.add(principalMessage);
simpleInterestPanel.add(principalText);
simpleInterestPanel.add(yearlyRateMessage);
simpleInterestPanel.add(yearlyRateText);
simpleInterestPanel.add(termYearMessage);
simpleInterestPanel.add(termYearText);
simpleInterestPanel.add(calcButton);
}
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
pack();
}
}
}
private class FontListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String actionCommand = e.getActionCommand();
if(presentValuePanel.isEnabled() && actionCommand.equals("Large font")){
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
else if(simpleInterestPanel.isEnabled() && actionCommand.equals("Large font")){
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
}
}
static void main(String[] args) {
// TODO Auto-generated method stub
new financeFormula();
}
}
注意:出于某种原因,按钮放大字体仍在显示。这不是我要的,我要问的是当我更改不同的公式并单击 JMenuItem 大字体时,它仅适用于当前值而不是简单的兴趣..
您没有告诉我们问题中最重要的部分——您收到了 NullPointerException。同样,这是了解问题所在并解决问题的关键信息,不应将其排除在您当前或未来的问题之外。
解决 NPE 的关键是找到抛出它的行,然后仔细检查它是否有空变量。然后回头查看您的代码,找出原因并进行更正。您的 NPE 被扔在这里:
if(presentValuePanel.isEnabled() && actionCommand.equals("Large font")){
,并且是由于presentValuePanel变量为null(因为选择了简单的兴趣,因此创建了简单的Interestpanel,但不是PresentValuePanel),然后您尝试从此null变量中调用方法,不允许使用该方法。
解决方案是不允许这种情况发生,不允许对空变量调用方法。一种选择是在程序初始化时创建所有 JPanel,如果您的程序能够更改为不同的公式,这将是一个有效的选项,我认为未来的程序将会这样做。所以这没关系。否则,另一种选择是在调用代码之前检查是否为 null。例如,查看程序的更改:
public class financeFormula extends JFrame {
public static final String LARGE_FONT = "Large Font"; // !! constant
// ....
public void buildTextMenu() {
fontSize = new JMenuItem(LARGE_FONT); // !! Use constant
fontSize.setMnemonic(KeyEvent.VK_2);
fontSize.addActionListener(new FontListener());
textMenu = new JMenu("Text");
textMenu.add(fontSize);
}
// ....
private class FontListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// !! block change
String actionCommand = e.getActionCommand();
if (actionCommand.equals(LARGE_FONT)) { // !! check for Large Font, and if pressed set the Fonts
if (presentValuePanel != null && presentValuePanel.isEnabled()) { // Check for null!
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
} else if (simpleInterestPanel != null && simpleInterestPanel.isEnabled()) { // Check for null!
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
}
// !! block change
}
}
请注意,在使用字符串进行相等性检查时,请始终使用字符串常量以避免琐碎但难以调试的拼写或大写错误。
有关 NullPointerExceptions 的更多信息,请阅读:What is a NullPointerException, and how do I fix it?
我需要创建一个侦听器,当我单击 JMenuItem
时它会更改字体大小。但是,我对不同的部分有不同的标签,所以当我更改字体大小时,当程序其他部分的标签被调用但未激活时,它会向我抛出一个错误。基本上我不能一次更改所有字体。
我试过使用 if 语句,但出于某种原因,似乎只有第一个有效!别人给我一个nullPointerException
.
到目前为止,这是我的侦听器代码..
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class financeFormula extends JFrame {
private JMenu fileMenu;
private JMenu textMenu;
private JMenuItem exitItem;
private JMenuItem fontSize;
private JMenuItem help;
private JPanel presentValuePanel;
private JPanel financeFinderPanel;// A panel container
private JLabel principalMessage;
private JLabel yearlyRateMessage;
private JLabel termYearMessage;
private JPanel simpleInterestPanel;
private JPanel doublingTimePanel;
private JPanel compoundInterestPanel;
private JLabel NONEMessage;
private JLabel imageLabel;
private JLabel label;// A message to display
private JMenuBar menuBar;
private JTextField principalText; // To hold user input
private JButton calcButton; // Performs calculation
private final int WINDOW_WIDTH = 600; // Window width
private final int WINDOW_HEIGHT = 600; // Window height
private JTextField yearlyRateText;
private JTextField termYearText;
DecimalFormat dc =new DecimalFormat("####0.00"); //formater
private JComboBox financeBox;
double principal = 400.0;
double yearlyRate = .04;
double termYears = 4.0;
private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
"Doubling time", "Compound interest", "Decaf"};
//financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);
/**
* Constructor
*/
public financeFormula()
{
// Call the JFrame constructor.
super("Finance Class");
// Set the size of the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify what happens when the close
// button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame.
financeFinderPanel();
setLayout(new BorderLayout());
//buildPanel();
menuBar = new JMenuBar();
//buildFileMenu();
buildTextMenu();
//menuBar.add(fileMenu);
menuBar.add(textMenu);
setJMenuBar(menuBar);
// Add the panel to the frame's content pane.
add(financeFinderPanel);
//add(panel);
// Display the window.
setVisible(true);
}
private void financeFinderPanel()
{
// Create a panel to hold the combo box.
financeFinderPanel = new JPanel();
//create label
label = new JLabel("Pick your formula");
//ImageIcon funnyImage = new ImageIcon("funny.gif");
//imageLabel = new JLabel();
//imageLabel.setLocation(50, 55);
label.setForeground(Color.BLUE);
// Create the combo box
financeBox = new JComboBox(financeFormulas);
//imageLabel.setIcon(funnyImage);
// Register an action listener.
financeBox.addActionListener(new financeBoxListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
// Add the combo box to the panel.
financeFinderPanel.add(financeBox);
financeFinderPanel.add(label);
// financeFinderPanel.add(imageLabel);
}
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
//buildFileMenu();
buildTextMenu();
// Add the file and text menus to the menu bar.
//menuBar.add(fileMenu);
menuBar.add(textMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
public void buildTextMenu(){
fontSize = new JMenuItem("Large font");
fontSize.setMnemonic(KeyEvent.VK_2);
fontSize.addActionListener(new FontListener());
textMenu = new JMenu("Text");
textMenu.add(fontSize);
}
private void presentValuePanel()
{
// Create the label, text field, and button components.
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Present Value");
//fontButton = new JButton("Enlarge Font");
// Add an action listener to the button.
//calcButton.addActionListener(new CalcButtonListener());
//calcButton.addActionListener(new financeFormListener());
//fontButton.addActionListener(new FontListener());
// Create a panel to hold the components.
presentValuePanel = new JPanel();
// Add the label, text field, and button to the panel.
presentValuePanel.add(principalMessage);
presentValuePanel.add(principalText);
presentValuePanel.add(yearlyRateMessage);
presentValuePanel.add(yearlyRateText);
presentValuePanel.add(termYearMessage);
presentValuePanel.add(termYearText);
presentValuePanel.add(calcButton);
//presentValuePanel.add(fontButton);
}
private void simpleInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Simple Interest");
simpleInterestPanel = new JPanel();
// calcButton.addActionListener(new financeFormListener());
simpleInterestPanel.add(principalMessage);
simpleInterestPanel.add(principalText);
simpleInterestPanel.add(yearlyRateMessage);
simpleInterestPanel.add(yearlyRateText);
simpleInterestPanel.add(termYearMessage);
simpleInterestPanel.add(termYearText);
simpleInterestPanel.add(calcButton);
}
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
pack();
}
}
}
private class FontListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String actionCommand = e.getActionCommand();
if(presentValuePanel.isEnabled() && actionCommand.equals("Large font")){
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
else if(simpleInterestPanel.isEnabled() && actionCommand.equals("Large font")){
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
}
}
static void main(String[] args) {
// TODO Auto-generated method stub
new financeFormula();
}
}
注意:出于某种原因,按钮放大字体仍在显示。这不是我要的,我要问的是当我更改不同的公式并单击 JMenuItem 大字体时,它仅适用于当前值而不是简单的兴趣..
您没有告诉我们问题中最重要的部分——您收到了 NullPointerException。同样,这是了解问题所在并解决问题的关键信息,不应将其排除在您当前或未来的问题之外。
解决 NPE 的关键是找到抛出它的行,然后仔细检查它是否有空变量。然后回头查看您的代码,找出原因并进行更正。您的 NPE 被扔在这里:
if(presentValuePanel.isEnabled() && actionCommand.equals("Large font")){
,并且是由于presentValuePanel变量为null(因为选择了简单的兴趣,因此创建了简单的Interestpanel,但不是PresentValuePanel),然后您尝试从此null变量中调用方法,不允许使用该方法。
解决方案是不允许这种情况发生,不允许对空变量调用方法。一种选择是在程序初始化时创建所有 JPanel,如果您的程序能够更改为不同的公式,这将是一个有效的选项,我认为未来的程序将会这样做。所以这没关系。否则,另一种选择是在调用代码之前检查是否为 null。例如,查看程序的更改:
public class financeFormula extends JFrame {
public static final String LARGE_FONT = "Large Font"; // !! constant
// ....
public void buildTextMenu() {
fontSize = new JMenuItem(LARGE_FONT); // !! Use constant
fontSize.setMnemonic(KeyEvent.VK_2);
fontSize.addActionListener(new FontListener());
textMenu = new JMenu("Text");
textMenu.add(fontSize);
}
// ....
private class FontListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// !! block change
String actionCommand = e.getActionCommand();
if (actionCommand.equals(LARGE_FONT)) { // !! check for Large Font, and if pressed set the Fonts
if (presentValuePanel != null && presentValuePanel.isEnabled()) { // Check for null!
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
} else if (simpleInterestPanel != null && simpleInterestPanel.isEnabled()) { // Check for null!
principalMessage.setFont(new Font("sans-serif", Font.PLAIN, 22));
}
}
// !! block change
}
}
请注意,在使用字符串进行相等性检查时,请始终使用字符串常量以避免琐碎但难以调试的拼写或大写错误。
有关 NullPointerExceptions 的更多信息,请阅读:What is a NullPointerException, and how do I fix it?