【问题标题】:I can´t get my -/+ button to work (calculator)我无法让我的 -/+ 按钮工作(计算器)
【发布时间】:2015-09-11 12:09:36
【问题描述】:

我正在学习 Java。我正在编写一个计算器进行练习,但我无法让 +/- 按钮工作。该按钮应该使数字为负/正。例如,如果您输入 5 + 3 并希望 3 成为 -3,它只会删除 5+ 并且只显示 -3

下面是代码:

计算器类:

package me.lommeregner.main;

public class Main {

  public static String tal = "";  //tal means number
  public static float first = 0;
  public static float second = 0;
  public static int operator;
  static float oper = 0;
  static JTextField jtf = new JTextField();
  public static boolean minplu = false;

  public static void main(String[] args) {

    jtf.setPreferredSize(new Dimension(250,40 ));
    Scanner test = new Scanner(System.in);

    final Button jbn0 = new Button("0", 0);
    final Button jbn1 = new Button("1", 1);
    final Button jbn2 = new Button("2", 2);
    final Button jbn3 = new Button("3", 3);
    final Button jbn4 = new Button("4", 4);
    final Button jbn5 = new Button("5", 5);
    final Button jbn6 = new Button("6", 6);
    final Button jbn7 = new Button("7", 7);
    final Button jbn8 = new Button("8", 8);
    final Button jbn9 = new Button("9", 9);


    final Button jbKomma = new Button(".");
    final Button jbnepo = new Button("+/-"); //the button i need help with



    final Button jbPlus = new Button(" + ");
    final Button jbMinus = new Button(" - ");
    final Button jbGange = new Button(" * ");
    final Button jbDivition = new Button(" / ");
    final Button jbClear = new Button("C");
    final Button jbClearEntity = new Button("CE");
    final Button jbErLigMed = new Button(" = ");



    //North
    JPanel panelNorth = new JPanel();
    panelNorth.add(jtf);

    //East
    JPanel panelEast = new JPanel();
    panelEast.setLayout(new GridLayout(4, 1));
    panelEast.add(jbPlus);
    panelEast.add(jbMinus);
    panelEast.add(jbGange);
    panelEast.add(jbDivition);
    panelEast.add(jbErLigMed);
    panelEast.add(jbClear);
    panelEast.add(jbClearEntity);


    //Center
    JPanel panelCenter = new JPanel();
    panelCenter.setLayout(new GridLayout(3,3));
    panelCenter.add(jbn0);
    panelCenter.add(jbn1);
    panelCenter.add(jbn2);
    panelCenter.add(jbn3);
    panelCenter.add(jbn4);
    panelCenter.add(jbn5);
    panelCenter.add(jbn6);
    panelCenter.add(jbn7);
    panelCenter.add(jbn8);
    panelCenter.add(jbn9);
    panelCenter.add(jbKomma);
    panelCenter.add(jbnepo);


    //Main Panel
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(panelNorth, BorderLayout.NORTH);
    panel.add(panelEast, BorderLayout.EAST);
    panel.add(panelCenter, BorderLayout.CENTER);


    //Frame
    GameWindow frame = new GameWindow("Lommeregner - "+randomMessage(), 315, 350);



    frame.setVisible(true);
    frame.add(panel);
    /*test.next();
    System.out.println(frame.size());*/




    //actionListeners

    //Numbers

    jbn0.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn0.value);
            tal = tal+jbn0.value;        //tal means number
        }});
    jbn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn1.value);
            tal = tal+jbn1.value;       //tal means number
        }});
    jbn2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn2.value);
            tal = tal+jbn2.value;
        }});
    jbn3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn3.value);
            tal = tal+jbn3.value;
        }});
    jbn4.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn4.value);
            tal = tal+jbn4.value;
        }});
    jbn5.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn5.value);
            tal = tal+jbn5.value;
        }});
    jbn6.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn6.value);
            tal = tal+jbn6.value;
        }});
    jbn7.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn7.value);
            tal = tal+jbn7.value;
        }});
    jbn8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn8.value);
            tal = tal+jbn8.value;
        }});
    jbn9.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbn9.value);
            tal = tal+jbn9.value;
        }});

    //operators

    jbKomma.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText(jtf.getText()+jbKomma.name);
            tal = tal+jbKomma.name;
        }});

    jbnepo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = jtf.getText();
            if(tal.length() !=0 && minplu !=true && second == 0){
                System.out.println(first);
            minplu = true;
            jtf.setText("-"+tal);
            tal = "-"+tal;
            text = "";
            }else if(tal.length() != 0 && minplu == true && second == 0){
                minplu = false;
                tal = tal.substring(1, tal.length());
                System.out.println(tal);
                jtf.setText(text.substring(1, text.length()));
                text = "";
            }else if(tal.length() != 0 && minplu == true && second != 0){
                minplu = false;
                tal = tal.substring(1, tal.length());
                System.out.println(tal);
                jtf.setText(tal+text.substring(tal.length() - text.length(), text.length()));
                text = "";
            }

        }});

    jbPlus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jtf.getText().length() !=0){
            jtf.setText(jtf.getText()+jbPlus.getText());
            first = Float.parseFloat(tal);
            tal = "";
            operator = 1;
        }}});
    jbMinus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jtf.getText().length() !=0){
            jtf.setText(jtf.getText()+jbMinus.getText());
            first = Float.parseFloat(tal);
            tal = "";
            operator = 2;
            }}});
    jbGange.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jtf.getText().length() !=0){
            jtf.setText(jtf.getText()+jbGange.getText());
            first = Float.parseFloat(tal);
            tal = "";
            operator = 3;   
        }}});
    jbDivition.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jtf.getText().length() !=0){
            jtf.setText(jtf.getText()+jbDivition.getText());
            first = Float.parseFloat(tal);
            tal = "";
            operator = 4;
            }}});
    jbErLigMed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jtf.getText().length() !=0){
            second = Float.parseFloat(tal);
            if(operator == 1)oper = first + second;
            if(operator == 2)oper = first - second;
            if(operator == 3)oper = first * second;
            if(operator == 4)oper = first / second;
            jtf.setText(jtf.getText()+jbErLigMed.getText()+oper);
            tal ="";
        }}});
    jbClear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jtf.setText("");
            oper = 0;
            second = 0;
            first = 0;
            tal="";

        }});
    jbClearEntity.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = jtf.getText();
            if(tal.length() !=0)
            tal = tal.substring(0, tal.length() - 1);
            if(text.length() !=0)
            jtf.setText(text.substring(0, text.length() - 1));
            System.out.println(tal);
        }});        
  }


  // random message i made for fun
  public static String randomMessage(){

    Random r = new Random();

    String[] message = {"17 * 17 = "+17*17, "What is 10 * 10??", "This is a calculator", "Have u found the secret spot yet??", "QUICK PRESS alt-F4!!!!", "Welcome", ""};

    int ri =r.nextInt(message.length - 1);

    return message[ri];
  }
}

按钮类:

package me.lommeregner.main;

import javax.swing.JButton;

public class Button extends JButton{

  boolean operator;
  int value;
  String name;

  public Button(String name) {
    this.setText(name);
    this.name = name;
    operator = true;
  }

  public Button(String name, int value) {
    this.setText(name);
    this.value = value;
    operator = false;
  }

  public void setValue(int value) {
    this.value = value;
  }

  public void setOperator(boolean operator) {
    this.operator = operator;
  }

  public int getValue() {
    return value;
  }

  private boolean getOperator() {
    return operator;
  }
}

GameWindow 类:

package me.lommeregner.main;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow(String title, int width, int height) {
        setTitle(title);
        setSize(width, height);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(true);

    }
}

【问题讨论】:

  • 您的帖子甚至没有包含所有代码。 GameWindow 类是在哪里定义的?
  • +/- 是否假设将最后输入的数字与-1 相乘?
  • @DušanRychnovský 我现在添加了游戏窗口类。我之前没有添加它,因为我认为你不需要它。
  • @Ian2thedv +/- 应该使最后输入的数字变成负数/正数
  • 如果没有使所有按钮变量最终化,代码将无法编译。

标签: java swing calculator


【解决方案1】:

不会解决你的实际问题,但这里有一些建议可以更好地构建代码:

  1. 不要将您的类称为“按钮”。有一个同名的 AWT 类。让您的课程更具描述性。

  2. 不要使用最终变量。

  3. 不要在 main() 方法中创建计算器。 main() 方法应该用于创建您的计算器应用程序。例如,您可能有一个 JPanel 代表计算器。然后所有需要的变量/方法都将在该类中定义。

  4. 某些按钮(如 1、2、3、4...)提供通用功能,因此请提供通用 ActionListener,这样您就无需重复 10 次代码。

例如:

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

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
//              display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(30, 30) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

【讨论】:

  • 好的,谢谢,你能解释一下这是什么意思吗:EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } });
  • @Jonasm.,所有 Swing 组件都应该在 Event Dispatch Thread 上创建/更新。阅读 Concurrency 上的 Swing 教程部分了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2010-12-26
  • 2018-11-11
  • 2014-06-12
  • 1970-01-01
相关资源
最近更新 更多