如何在固定位置获得一排按钮?

时间:2016-03-20 12:11:07

标签: java layout

我必须制作一个非常简单的计算器,并且按钮(加,减,除和乘)需要低于数字输入并产生固定位置。在picture显示我应该拥有的内容,另一方面显示我目前拥有的内容。

package calculator; 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;




public class Calculator extends JFrame {
private JTextField Number1TxtField; 
private JTextField Number2TxtField;  
private JTextField ResultTxtField; 
private JButton add; 
private JButton subtract; 
private JButton multiply; 
private JButton divide;



 public Calculator() { // class for the calculator 




        setLayout(new FlowLayout(FlowLayout.LEFT,8,10));
        add(new JLabel("Number 1"));
        Number1TxtField=new JTextField(8); add(Number1TxtField);
        add(new JLabel("Number 2"));
        Number2TxtField=new JTextField(8);
        Number2TxtField=new JTextField(8); add(Number2TxtField);
        add(new JLabel("Result"));
        ResultTxtField= new JTextField(8); add(ResultTxtField);
        ResultTxtField.setEditable(false); add(ResultTxtField);




        //new JPanel
        add = new JButton("Add"); add(add);

        subtract = new JButton ("Subtract"); add(subtract);

        multiply = new JButton ("Multiply"); add(multiply);

        divide = new JButton ("Divide"); add(divide);


        ButtonListener btnlistener = new ButtonListener ();

        add.addActionListener(btnlistener);

        subtract.addActionListener(btnlistener);

        multiply.addActionListener(btnlistener);

        divide.addActionListener(btnlistener);
    }

class ButtonListener implements ActionListener {

      @Override

      public void actionPerformed(ActionEvent e) {

String num1str = Number1TxtField.getText();

double num1 = Double.parseDouble(num1str );

String num2str = Number2TxtField.getText();

double num2 = Double.parseDouble(num2str );

double result;

      if (e.getSource() == add)
          result = num1+num2;

      else if (e.getSource() == subtract)
    result = num1-num2;

      else if (e.getSource() == multiply)
    result = num1*num2;

      else //DivideButton
    result = num1/num2;


ResultTxtField.setText(String.valueOf(result));

  }
    }



        public static void main(String[] args) { 



        Calculator frame = new Calculator(); 

        frame.setTitle("Calculator");  

        frame.setSize(600,120);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true); 
    }
}

1 个答案:

答案 0 :(得分:1)

创建两个面板:topPanelbuttonsPanel。将您的按钮添加到buttonsPanel,然后将此面板添加到CENTER的{​​{1}}位置。然后将文本字段添加到JFrame并将topPanel放到topPanel的NORTH位置。

JFrame