2016-11-28 1 views
2

JMenuItem을 클릭하면 글꼴 크기가 변경되는 Listener를 만들어야합니다. 그러나 다른 부분에 다른 레이블이 있으므로 글꼴 크기를 변경하면 프로그램의 다른 부분에 대한 레이블이 호출되었지만 활성 상태가 아닐 때 오류가 발생합니다. 기본적으로 모든 글꼴을 한 번에 변경할 수는 없습니다.ActionListener로 글꼴 크기 변경

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(); 

    } 

} 

참고 : 버튼 글꼴을 확대 몇 가지 이유를 들어 나는 내가 다른 수식을 변경할 때 요구하고 요구하고 있지 무엇 showing..That 여전히 현재의 가치와 단순한이자가 아닌 JMenuItem Large 폰트를 클릭하십시오 ..

+1

귀하의 질문은 오류를 일으키는 코드의 상호 관련성, 심지어 NPE 문제를 포함한다. 귀하의 설명과 작은 코드 스 니펫을 기반으로 프로그램 구조에 무엇이 잘못 될 수 있는지 추측 할 수있는 방법을 모릅니다. 즉, 더 많은 코드를 게시하고 더 많이 알려주려고합니다. . 아니요, 전체 프로그램을보고 싶지는 않지만 ** 작고 ** (링크가 아닌 질문에 대한 편집으로 게시 할 수있을만큼 작음) compiilable and runnable 프로그램을 작성하면 도움이됩니다. 우리에게 직접 당신의 실수, [mcve]. –

+0

좋아, 내가 묻는대로 작은 프로그램을 만들었다 ... 현재 값을 클릭하고 JMenuItem으로 글꼴을 변경하면 작동하지만 간단한 관심과 함께 할 때 ... JButton을 무시한다. "글꼴 확대"Idk 왜 여전히 나타나는가. –

+0

principalMessage 변수에 둘 이상의 JLabel 객체가 포함되어 있으며 JVM에서 중요한 것은 변수가 아니라 사용중인 객체입니다. 따라서 ActionListener는 참조를 보유하고있는 객체의 Font 만 변경합니다. 프로그램을보다 단순하게 만들고 둘 이상의 객체에 대해 동일한 변수를 사용하지 않아야합니다. –

답변

0

당신은 우리에게 문제의 가장 중요한 부분을 말하지 않고 있습니다. 당신은 NullPointerException을 얻고 있습니다. 다시 이것은 무엇이 잘못되었는지를 파악하고 해결하는 데 중요하며 현재 또는 미래의 질문에서 빠져 나가지 않아야하는 중요한 정보입니다.

NPE를 해결하는 핵심은 던지는 줄을 찾은 다음 null 인 변수를주의 깊게 확인하는 것입니다. 그런 다음 코드를 다시보고 이유를 찾아서 수정하십시오.

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

과 presentValuePanel중인 변수에 null로 인한 (단순이자는 simpleInterestPanel이 생성을 선택하면 이후하지만 presentValuePanel는 아니다) 다음은 떨어져 메소드를 호출하려고 : 귀하의 NPE는 여기에서 발생되는 이 null 변수의 - 허용되지 않습니다.

해결 방법은 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?