java - 使用 JFrame 和布局的 GUI 计算器
问题描述
我目前正在开发一个计算器,它应该执行基本计算,例如加法、减法、乘法和除法。为了达到最终结果,我必须遵循计算器的特定设计。这个问题提供了计算器的设计。我已经尽我最大的努力来匹配计算器的官方设计,但它不匹配它。
这是计算器的官方设计。这就是它应该的样子。
这就是我运行代码时得到的。
编码:
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
使用 a为两个按钮创建一个面板。将此面板添加到BorderLayout.PAGE_START
框架中。将包含文本区域的滚动窗格添加到
BorderLayout.CENTER
框架中。GridLayout
使用底部的按钮创建一个面板。将此面板添加到BorderLayout.PAGE_END
框架中。
阅读 Swing 教程中有关使用布局管理器的部分,以获取更多信息Borderlayout
和GridLayout
.
推荐阅读
- c# - 为什么单元测试仍然没有像调试它移动到数据访问层时那样被嘲笑
- dart - 为颤振更新 dart sdk
- gcc - 在 clang 或 gcc 中使用线程清理器时是否需要使用 -fopenmp
- amazon-web-services - 如何过滤NULL?
- javascript - 如何获取输入字段的值并将其存储在数组中
- javascript - 打开网站的多个选项卡后,IIS Webserver 冻结
- nodemcu - NodeMCU - 在 ESP32 上启用 UART1/2
- mysql - MySQL:A列和B列的累积总和到B列
- makefile - 使变量不评估
- python - 来自编号列表的用户输入并返回列表