2017-09-09 3 views
0

간단한 팁 계산기 프로그램을 만들려고 노력 중입니다. 그러나 일반적으로 액션 리스너에 익숙하지 않아서 잘못된 생각을하고 있습니다. 단추가 num 값을 업데이트하고 문자열로 서식을 지정한 다음 레이블 텍스트 (사용자가 입력 한 금액 (청구 금액) 표시)를 변경합니다. 여기 JButton에 두 개의 액션을 추가하는 방법은 무엇입니까? 팁 계산기 프로그램

내 코드입니다 :

package calculatorCW; 

import java.awt.Color; 
import java.awt.event.*; 
import java.text.DecimalFormat; 
import java.text.ParseException; 
import javax.swing.*; 

public class calGui { 
    double tip = 0; 
    String num = "000.00", output1 = "00.00", output2 = "00.00"; 
    JFrame frame = new JFrame(); 
    JPanel myPanel = new JPanel(); 
    JLabel label1, label2, label3, label4; 
    JTextField myText1, myText2; 
    JButton buttons, tBtn1, tBtn2, tBtn3, calc, btn0; 
    DecimalFormat formatter = new DecimalFormat(); 
    private int i = 1; 

    public calGui() { 
     initializeLabels(); 
     initializeTextFields(); 
     initializeButtons(); 
     setPanels(); 
     setBounds(); 
     guiExtras(); 
     setActionListeners(); 
    } 

    public static void main(String[] args) { 
     new calGui(); 
    } 

    public void initializeLabels() { 

     label1 = new JLabel("<html> <p style='font-size: 15px; color: red;'> TIP CALCULATOR </p></html>"); 
     label2 = new JLabel("<html> <p style='color: white;'> Bill Amount:</p></html> "); 
     label3 = new JLabel("<html> <p style='color: white;'>Tip Percentage: </p></html>"); 
     label4 = new JLabel("<html> <p style='color: white;'>Total Cost: </p></html>"); 
    } 

    public void initializeTextFields() { 
     myText1 = new JTextField(output1); 
     myText2 = new JTextField(output2); 
    } 

    public void initializeButtons() { 
     tBtn1 = new JButton("<html> <p style='color: blue;'>15 %</p></html>"); 
     tBtn2 = new JButton("<html> <p style='color: blue;'>18 %</p></html>"); 
     tBtn3 = new JButton("<html> <p style='color: blue;'>20 %</p></html>"); 
     calc = new JButton("<html> <p style='color: black;'>CALC</p></html>"); 
     btn0 = new JButton("0"); 
     //Buttons Loop 
     for (int col = 50; col <= 190; col = col + 70) { 
      for (int row = 253; row <= 393; row = row + 70) { 
       buttons = new JButton("" + i); 
       myPanel.add(buttons); 
       buttons.setBounds(row, col, 60, 50); 
       buttons.setActionCommand(String.valueOf(i)); 
       i++; 
      } 
     } 
    } 

    public void setPanels() { 
     myPanel.add(tBtn1); 
     myPanel.add(tBtn2); 
     myPanel.add(tBtn3); 
     myPanel.add(calc); 
     myPanel.add(btn0); 
     myPanel.add(label1); 
     myPanel.add(label2); 
     myPanel.add(label3); 
     myPanel.add(label4); 
     myPanel.add(myText1); 
     myPanel.add(myText2); 
    } 

    public void setBounds() { 
     tBtn1.setBounds(23, 90, 60, 50); 
     tBtn2.setBounds(93, 90, 60, 50); 
     tBtn3.setBounds(163, 90, 60, 50); 
     calc.setBounds(13, 190, 100, 50); 
     btn0.setBounds(323, 260, 60, 50); 
     label1.setBounds(155, -5, 200, 50); 
     label2.setBounds(13, 50, 100, 20); 
     label3.setBounds(13, 70, 200, 20); 
     label4.setBounds(13, 160, 100, 20); 
     myText1.setBounds(96, 50, 100, 20); 
     myText2.setBounds(96, 160, 100, 20); 
    } 

    public void guiExtras() { 
     myPanel.setLayout(null); 
     myPanel.setSize(500, 400); 
     frame.add(myPanel); 
     frame.setBounds(600, 50, 500, 400); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     myText1.setEditable(false); 
     myText2.setEditable(false); 
     //myPanel.setOpaque(true); 
     myPanel.setBackground(Color.black); 
    } 

    public void setActionListeners() { 
     //bill amounts 
     buttons.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       num = num + (e.getActionCommand()); 
      } 
     }); 

     buttons.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       try { 
        output1 = formatter.format(formatter.parse(num)); 
        myText1.setText(output1); 
       } catch (ParseException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
      } 
     }); 

     //tips 
     tBtn1.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       tip = .15; 
      } 
     }); 
     tBtn2.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       tip = .18; 
      } 
     }); 
     tBtn3.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       tip = .20; 
      } 
     }); 
    } 
} 
+1

적어도 게시 한 코드의 문제점을 말하고 많은 요구 사항보다는 훨씬 구체적인 질문을하십시오. –

+1

스택 오버플로에 오신 것을 환영합니다! 귀하는 귀하의 질문에 많은 코드 작성 방법을 게시 했으므로 문제가있는 곳에서 우리 (그리고 미래의 독자들에게)가 명확하지 않습니다. 문제 코드를 10 줄 이하로 줄이십시오. 참조 : [최소, 완전하고 검증 가능한 예제를 만드는 방법] (http://stackoverflow.com/help/mcve) 및 [소규모 프로그램을 디버깅하는 방법] (https://ericlippert.com/2014/03/05)/how-to-debug-small-programs /). –

+0

gui에서 번호를 클릭 할 때 빌 금액 Jlabel을 "00.00"에서 사용자 번호 –

답변

1

이 같은 리스너에 둘 다 할 수

button.addActionListener(new Actionlistener{ 
public void actionPerformed(ActionEvent ae){ 
//add code to update value of num 
//change text of Jlabel 
} 
}); 
3

현재 생성 된 버튼 단지 temporare 참조입니다 '버튼'에 ActionListener를 추가 'initializeButtons()'에 있습니다. 나중에 'setActionListeners'를 호출하면 버튼을 초기화하는 동안 생성 된 마지막 버튼에 ActionListener가 추가됩니다.

단추에 클래스 변수를 사용하지 않는 것이 좋습니다. 대신 로컬 변수 단추를 사용하십시오.

당신은 버튼을 초기화하는 동안 ActionListener를 추가하여이 문제를 해결할 수 있습니다

public void initializeButtons() { 
    ... 
    //Buttons Loop 
    for (int col = 50; col <= 190; col = col + 70) { 
     for (int row = 253; row <= 393; row = row + 70) { 
      JButton button = new JButton("" + i); 
      // bill amounts 
      button.addActionListener(new ActionListener() { 

       public void actionPerformed(ActionEvent e) { 
        num = num + (e.getActionCommand()); 
        try { 
         output1 = formatter.format(formatter.parse(num)); 
         myText1.setText(output1); 
        } catch (ParseException e1) { 
         e1.printStackTrace(); 
        } 
       } 
      }); 
      ... 
     } 
    } 
} 
+0

고마워 - 바로 버튼 액션 리스너를 모든 버튼에 지정하지 않았다는 것을 알지 못했다. –

+0

2 개의 새로운 질문이 있습니다. 입력을 할 수 있습니다. 나는 코멘트 아래에 그것을 게시했다. –

0

나의 새로운 질문은 이것이다 : 내 코드와 함께 이제 두 가지 문제가 있습니다. 첫 번째 문제는 청구서 금액을 추가하기 위해 숫자 버튼 중 하나를 누르면 해당 금액이 청구서 금액에 표시되지 않습니다. 사용자가 9를 입력하면 "000.09"를 표시합니다. 이제 사용자가 5를 입력하면 청구 금액에 "000.95"가 표시되기를 원합니다. Button Action Listener에서 설정 한 방식이 잘못 되었다면 수학을 이해합니다. 두 번째 문제는 내가 리셋 버튼을 추가하고 textFields의 값을 원본으로 다시 설정하기를 원한다는 것입니다. setResetListener() 메서드에서 리셋 버튼에 액션 리스너를 생성하여 double 값을 원래 값으로 다시 변환합니다. 그런 다음 textField에 다시 표시하고 싶습니다. 그러나, 그렇게하지 않습니다. 또한 myPanel의 배경을 검은 색으로 원래대로 다시 칠하기를 원합니다. 이것은 스레드에 대한 것 때문이라고 생각하십니까? 지금까지 가지고있는 코드는 다음과 같습니다.

package calculatorCW; 
import java.awt.Color; 
import java.awt.event.*; 
import java.text.DecimalFormat; 
import java.text.ParseException; 
import javax.swing.*; 
public class calGui 
{ 
    private int i=1; 
    double tip=0,finalAmount=0,amountTaxed=0; 
    String num="000.00",output1="000.00",output2="000.00"; 
    JFrame frame = new JFrame(); 
    JPanel myPanel = new JPanel(); 
    JLabel label1, label2, label3, label4; 
    JTextField myText1, myText2; 
    JButton buttons,tBtn1,tBtn2, tBtn3,calc,btn0,reset; 
    DecimalFormat formatter = new DecimalFormat(); 

    public calGui() 
    { 
     initializeLabels(); 
     initializeTextFields(); 
     initializeButtons(); 
     setPanels(); 
     setBounds(); 
     guiExtras(); 
     setTipListeners(); 
     setCalcListener(); 
    } 
    public void initializeLabels() 
    { 

     label1 = new JLabel("<html> <p style='font-size: 15px; color: red;'> TIP CALCULATOR </p></html>"); 
     label2 = new JLabel("<html> <p style='color: white;'> Bill Amount:</p></html> "); 
     label3 = new JLabel("<html> <p style='color: white;'>Tip Percentage: </p></html>"); 
     label4 = new JLabel("<html> <p style='color: white;'>Total Cost: </p></html>"); 
    } 
    public void initializeTextFields() 
    { 
     myText1 = new JTextField(output1); 
     myText2 = new JTextField(output2); 
    } 
    public void initializeButtons() 
    { 
     tBtn1 = new JButton("<html> <p style='color: blue;'>15 %</p></html>"); 
     tBtn2 = new JButton("<html> <p style='color: blue;'>18 %</p></html>"); 
     tBtn3 = new JButton("<html> <p style='color: blue;'>20 %</p></html>"); 
     calc = new JButton("<html> <p style='color: black;'>CALC</p></html>"); 
     reset = new JButton("<html> <p style='color: black;'>Reset</p></html>"); 
     btn0 = new JButton("0"); 
     //Buttons Loop 
       for (int col = 50; col<=190; col=col+70) 
        { 
         for(int row =253; row<=393; row=row+70) 
         { 
          buttons = new JButton(""+i); 
          myPanel.add(buttons); 
          buttons.setBounds(row, col, 60, 50); 
          buttons.setActionCommand(String.valueOf(i)); 
          setButtonsListeners(); 
          i++; 
         } 
        } 

    } 

    public void setPanels() 
    { 
     myPanel.add(tBtn1); 
     myPanel.add(tBtn2); 
     myPanel.add(tBtn3); 
     myPanel.add(calc); 
     myPanel.add(reset); 
     myPanel.add(btn0); 
     myPanel.add(label1); 
     myPanel.add(label2); 
     myPanel.add(label3); 
     myPanel.add(label4); 
     myPanel.add(myText1); 
     myPanel.add(myText2); 
    } 
    public void setBounds() 
    { 
     tBtn1.setBounds(23, 90, 60, 50); 
     tBtn2.setBounds(93, 90, 60, 50); 
     tBtn3.setBounds(163, 90, 60, 50); 
     calc.setBounds(13, 190, 100, 50); 
     reset.setBounds(13, 260, 100, 50); 
     btn0.setBounds(323, 260, 60, 50); 
     label1.setBounds(155,-5,200, 50); 
     label2.setBounds(13, 50, 100, 20); 
     label3.setBounds(13, 70, 200, 20); 
     label4.setBounds(13, 160, 100, 20); 
     myText1.setBounds(96, 50, 100, 20); 
     myText2.setBounds(96, 160, 100, 20); 
    } 
    public void guiExtras() 
    { 
     myPanel.setLayout(null); 
     myPanel.setSize(500,400); 
     frame.add(myPanel); 
     frame.setBounds(600,50,500,400); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     myText1.setEditable(false); 
     myText2.setEditable(false); 
     //myPanel.setOpaque(true); 
     myPanel.setBackground(Color.black); 
    } 

    public void setButtonsListeners() 
    { 
     //bill amounts 
     buttons.addActionListener(new ActionListener() 
     {@Override public void actionPerformed(ActionEvent e) 
     { 
      num=num+(e.getActionCommand()); 
      //buttons.setEnabled(true); 
      try { 
       output1=formatter.format(formatter.parse(num)); 
      } catch (ParseException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      myText1.setText(output1); 
     }}); 
    } 

    public void setTipListeners() 
    { 
     //tips 
     tBtn1.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.15;}}); 
     tBtn2.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.18;}}); 
     tBtn3.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) {tip=.20;}}); 
    } 

    public void setCalcListener() 
    { 
     calc.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) 
     { 
      amountTaxed=(Double.parseDouble(output1)*tip)+Double.parseDouble(output1); 
      finalAmount=(amountTaxed*8.25)+amountTaxed; 
      try { 
       output2=formatter.format(formatter.parse(Double.toString(finalAmount))); 
      } catch (ParseException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      myText2.setText(output2); 
      myPanel.setBackground(Color.gray); 
      label1.setText(("<html> <p style='font-size: 15px; color: white;'> TIP CALCULATOR </p></html>")); 
     }}); 
    } 
    public void setResetListerner() 
    { 
     reset.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) 
     { 
      tip=0; 
      finalAmount=0; 
      amountTaxed=0; 
      num="000.00"; 
      output1="000.00"; 
      output2="000.00"; 
      myText2.setText(output2); 
      myText1.setText(output1); 
      myPanel.setBackground(Color.BLACK); 
      //myPanel.repaint(); 

     }}); 
    } 

    public static void main(String[] args) 
    { 
     new calGui(); 
    } 
} 
관련 문제