【发布时间】:2017-02-10 12:52:07
【问题描述】:
我正在尝试在java 中创建一个calculator。我是Layout Managers 的新手。我用GridBagLayout 创建了一个JFrame 对象。我创建了 2 个JPanel,一个用于数字,另一个用于操作。 JPanel 都使用 GridLayout。
这就是它们在JFrame中的排列方式。
window=new JFrame("Calculator");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridBagLayout());
//Creating window
GridBagConstraints gbc=new GridBagConstraints();
btns=new JPanel(); //JPanel for numbers
operations=new JPanel(); //JPanel for operations
numdisp=new JTextField(15); //JTextFIeld which displays the number
gbc.gridx=1;
gbc.gridy=1;
window.add(numdisp,gbc);
addbtn(); //method which defines all the variables
gbc.gridx=1;
gbc.gridy=2;
window.add(btns,gbc);
gbc.gridx=2;
gbc.gridy=2;
window.add(operations,gbc);
btns.setLayout(new GridLayout(4,3,0,0)); //Layout for both JPanel's
operations.setLayout(new GridLayout(7,1,1,1));
window.pack();
window.setVisible(true);
但这就是结果的样子……
我不明白为什么我的number 面板和number display 之间的差距很大。为什么会出现问题?怎么解决?
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2)另见calculator example。它使用
ScriptEngine来评估文本字段中的表达式。 3)另见GridBagConstraints.fill。
标签: java swing layout-manager gridbaglayout gridlayoutmanager