2015-02-12 1 views
0

Я пытаюсь создать программу, которая будет действовать как калькулятор, который Windows предоставляет в ОС, но я изо всех сил пытаюсь понять, как я должен добавить второй прослушиватель действий, который узнайте второй клик. Кроме того, как бы я установил его только для первой нажатой кнопки.Как создать второй «ActionListener»

import javax.swing.*; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
public class Calculator extends JFrame implements ActionListener { 
JButton b0 = new JButton("0"); 
JButton b1 = new JButton("1"); 
JButton b2 = new JButton("2"); 
JButton b3 = new JButton("3"); 
JButton b4 = new JButton("4"); 
JButton b5 = new JButton("5"); 
JButton b6 = new JButton("6"); 
JButton b7 = new JButton("7"); 
JButton b8 = new JButton("8"); 
JButton b9 = new JButton("9"); 
int a; 
public Calculator(){ 
    JFrame f = new JFrame("Calculator"); 
    f.setVisible(true); 
    f.setSize(500,300); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JPanel p = new JPanel(); 
    p.setLayout(new FlowLayout()); 
    f.add(p); 
    p.add(b0); 
    p.add(b1); 
    p.add(b2); 
    p.add(b3); 
    p.add(b4); 
    p.add(b5); 
    p.add(b6); 
    p.add(b7); 
    p.add(b8); 
    p.add(b9); 
    b0.addActionListener(this); 
    b1.addActionListener(this); 
    b2.addActionListener(this); 
    b3.addActionListener(this); 
    b4.addActionListener(this); 
    b5.addActionListener(this); 
    b6.addActionListener(this); 
    b7.addActionListener(this); 
    b8.addActionListener(this); 
    b9.addActionListener(this); 
    ActionListener d = new ActionListener(); 
    b0.addActionListener(d); 
} 
public static void main(String[] args){ 
    new Calculator(); 
} 
public void actionPerformed(ActionEvent e){ 
    if (e.getSource() == b0){ 
     a = 0; 
     System.out.println(a); 
    } 
    if (e.getSource() == b1){ 
     a=1; 
     System.out.println(a); 

    } 
    if (e.getSource() == b2){ 
     a = 2; 
     System.out.println(a); 
    } 
    if (e.getSource() == b3){ 
     a = 3; 
     System.out.println(a); 
    } 
    if (e.getSource() == b4){ 
     a = 4; 
     System.out.println(a); 
    } 
    if (e.getSource() == b5){ 
     a = 5; 
     System.out.println(a); 
    } 
    if (e.getSource() == b6){ 
     a = 6; 
     System.out.println(a); 
    } 
    if (e.getSource() == b7){ 
     a = 7; 
     System.out.println(a); 
    } 
    if (e.getSource() == b8){ 
     a = 8; 
     System.out.println(a); 

    } 
    if (e.getSource() == b9){ 
     a = 9; 
     System.out.println(a); 
    } 
} 
} 
+4

Для ваших цифровых кнопок, вам не нужно второй ActionListener. Вам нужно использовать массивы здесь, а вместо использования второго слушателя сделать текущий умнее. –

+0

Некоторые примечания: 1) Рамка должна быть видимой * после *, вы добавляете к ней все свои компоненты. 2) Вместо того, чтобы устанавливать фиксированный размер кадра, вы должны вызвать метод 'pack()' непосредственно перед вызовом 'setVisible (true)' 3). Поскольку он должен быть калькулятором, вы можете попробовать «GridLayout» 'FolwLayout', чтобы сделать сетку кнопок. – dic19

+0

В вашем случае вам не нужен второй прослушиватель действий. Для тех, кто это делает, вы создаете отдельные классы, которые реализуют ActionListener. Не пытайтесь делать все в одном классе. –

ответ

1

Если вы хотите, чтобы ответ на нажатие кнопки будет отличаться в зависимости от того, если нажата кнопка первой или второй, ключ, чтобы не дать ему два ActionListeners, а дать ему один смарт ActionListener , Например, если вы дадите ActionListener логическую переменную firstPress, вы можете установить ее и проверить ее внутри ActionListener и изменить поведение слушателя в зависимости от состояния этой переменной. Например, если вы хотите, чтобы приемник две кнопки с цифрами, а затем добавить их, вы могли бы сделать что-то вроде:

private class ButtonListener implements ActionListener { 
    private int firstNumber; 
    private boolean firstClick = true; 

    public void actionPerformed(ActionEvent e) { 
    // here actionCommand is the button's text 
    String actionCommand = e.getActionCommand(); 
    int number = Integer.parseInt(actionCommand); 

    if (firstClick) { 
     firstNumber = number; // set the firstNumber 
     System.out.println("First Number is: " + firstNumber); 
    } else { 
     int secondNumber = number; //set secondNumber 
     int sum = firstNumber + secondNumber; // add them 
     System.out.println("Second Number is: " + secondNumber); 
     System.out.println("Sum is: " + sum); 
    } 

    firstClick = !firstClick; // toggle firstClick 
    }; 
} 

Например,

import java.awt.event.*; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class Calc2 extends JPanel { 

    private static final int MAX = 10; 

    public Calc2() { 
     ButtonListener buttonListener = new ButtonListener(); 
     for (int i = 0; i < MAX; i++) { 
     String text = String.valueOf(i); 
     JButton button = new JButton(text); 
     button.addActionListener(buttonListener); 
     add(button); 
     } 
    } 

    private class ButtonListener implements ActionListener { 
     private int firstNumber; 
     private boolean firstClick = true; 

     public void actionPerformed(ActionEvent e) { 
     // here actionCommand is the button's text 
     String actionCommand = e.getActionCommand(); 
     int number = Integer.parseInt(actionCommand); 

     if (firstClick) { 
      firstNumber = number; 
      System.out.println("First Number is: " + firstNumber); 
     } else { 
      int secondNumber = number; 
      int sum = firstNumber + secondNumber; 
      System.out.println("Second Number is: " + secondNumber); 
      System.out.println("Sum is: " + sum); 
     } 

     firstClick = !firstClick; // toggle firstClick 
     }; 
    } 

    private static void createAndShowGui() { 
     Calc2 mainPanel = new Calc2(); 

     JFrame frame = new JFrame("Calc2"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
Смежные вопросы