使用ActionListener更改字体大小

时间:2016-11-28 01:13:48

标签: java fonts 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大字体它只适用于现在的价值而不是简单的兴趣。

1 个答案:

答案 0 :(得分:0)

你没有告诉我们你问题中最重要的部分 - 你得到的是NullPointerException。同样,这是关键信息,这是了解错误和解决问题的关键,不应该被排除在当前或未来的问题之外。

解决NPE的关键是找到抛出它的行,然后仔细检查它是否为null。然后回顾一下你的代码,找出原因并予以纠正。你的NPE被扔到这里:

if(presentValuePanel.isEnabled() && actionCommand.equals("Large font")){

并且是由于presentValuePanel变量为null(因为当选择简单兴趣时,创建simpleInterestPanel但不创建presentValuePanel)然后尝试从此null变量调用方法 - 不允许。

解决方案是不允许这种情况发生,不允许在空变量上调用方法。一个选项是在程序初始化时创建所有JPanels,如果您的程序连接到能够更改为不同的公式,这将是一个有效的选项,我认为未来的程序将会这样做。所以这没关系。否则,另一个选项是在调用代码之前检查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?

相关问题