我目前正在开发一个计算器,它应该执行加法、减法、乘法和除法等基本计算。为了实现最终结果,我必须遵循计算器的特定设计。本题提供了计算器的设计。我已经尽力了解如何匹配计算器的官方设计,但它不匹配。
这是计算器的官方设计。它应该是这样的。
这就是我运行代码时得到的结果。
代码:
package patel.Jainam;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CalculatorFrame extends JFrame {
/**
* All the buttons that will be used in the calculator have been initialized
*/
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
private JButton button0;
private JButton buttonEqual;
private JButton buttonDot;
private JButton buttonClearLast;
private JButton buttonClearAll;
private JButton buttonAdd;
private JButton buttonSub;
private JButton buttonMul;
private JButton buttonDiv;
private JTextArea textArea;
public CalculatorFrame(){
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,1));
panel2.add(buttonClearLast = new JButton ("Clear Last"));
panel2.add(buttonClearAll = new JButton ("Clear All"));
add(panel2, BorderLayout.PAGE_START);
JPanel panel3 = new JPanel();
textArea = new JTextArea(2,10);
// textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel3.add(scrollPane);
add(panel3, BorderLayout.LINE_START);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4,4));
panel1.add(button7 = new JButton ("7"));
panel1.add(button8 = new JButton ("8"));
panel1.add(button9 = new JButton ("9"));
panel1.add(buttonAdd = new JButton ("+"));
panel1.add(button4 = new JButton ("4"));
panel1.add(button5 = new JButton ("5"));
panel1.add(button6 = new JButton ("6"));
panel1.add(buttonSub = new JButton ("-"));
panel1.add(button1 = new JButton ("1"));
panel1.add(button2 = new JButton ("2"));
panel1.add(button3 = new JButton ("3"));
panel1.add(buttonMul = new JButton ("*"));
panel1.add(button0 = new JButton ("0"));
panel1.add(buttonDot = new JButton ("."));
panel1.add(buttonEqual = new JButton ("="));
panel1.add(buttonDiv = new JButton ("/"));
add(panel1, BorderLayout.PAGE_END);
}
}
谢谢。
最佳答案
问题是您已经过度使用 GridLayout。
我建议您继续使用框架的默认布局管理器,即 BorderLayout
。
然后您将执行以下操作:
使用
GridLayout
为两个按钮创建一个面板。将此面板添加到框架的BorderLayout.PAGE_START
中。将包含文本区域的滚动 Pane 添加到框架的
BorderLayout.CENTER
中。使用
GridLayout
创建一个面板作为底部的按钮。将此面板添加到框架的BorderLayout.PAGE_END
中。
阅读 Swing 教程中关于 Using Layout Managers 的部分了解 Borderlayout
和 GridLayout
的更多信息和工作示例。
关于java - 使用 JFrame 和布局的 GUI 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242564/