【发布时间】:2021-02-19 14:56:38
【问题描述】:
我正在尝试从头开始构建自己的计算器。
当我像现在这样运行我的程序时,一些按钮不会出现,直到我将光标悬停在它们上方,我的界限都被搞砸了。但是,当我将 window.setVisible(true); 移动到构造函数的开头时,所有对象的每个边界都已正确放置,但 all 我的对象仅在鼠标悬停时显示。
package guitest;
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import static javax.swing.JFrame.*;
public class Frame implements ActionListener{
public static int Calculator(int n1, int n2){
return n1 + n2;
}
JTextField num1,num2,ans;
JButton calculate, add, sub, pro, div;
JPanel textFields, actions;
Frame(){
//Window is being created.
JFrame window = new JFrame("Calculator");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setSize(400, 400);
//Creating panel
textFields = new JPanel();
actions = new JPanel();
//Adjusting JPanel
textFields.setBounds(0, 0, 240, 400);
actions.setBounds(240, 0, 160, 400);
//Creating textfields.
num1 = new JTextField("Number 1");
num2 = new JTextField("Number 2");
ans = new JTextField("Answer");
ans.setEditable(false);
//Creating calculate button.
calculate = new JButton("Calclulate");
add = new JButton("+");
sub = new JButton("-");
pro = new JButton("*");
div = new JButton("/");
//adjusting TextFields to my window
num1.setBounds(30, 20, 200, 20);
num2.setBounds(30, 60, 200, 20);
ans.setBounds(30,100,200,20);
//adjusting Buttons to my window
calculate.setBounds(30, 140, 90, 30);
add.setBounds(20, 20, 50, 50);
sub.setBounds(75, 20, 50, 50);
pro.setBounds(20, 75, 50, 50);
div.setBounds(75, 75, 50, 50);
calculate.addActionListener(this);
//adding to my window
textFields.add(num1);textFields.add(num2);textFields.add(ans);textFields.add(calculate);
actions.add(add);actions.add(sub);actions.add(pro);actions.add(div);
window.add(textFields);window.add(actions);
window.setVisible(true);
//Setting everything visible
//textFields.setVisible(true);actions.setVisible(true);
//num1.setVisible(true);num2.setVisible(true);ans.setVisible(true);
//calculate.setVisible(true);add.setVisible(true);sub.setVisible(true);pro.setVisible(true);div.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String n1 = num1.getText();
String n2 = num2.getText();
int a = Integer.parseInt(n1);
int b = Integer.parseInt(n2);
int c;
c = Calculator(a,b);
String result = String.valueOf(c);
ans.setText(result);
}
public static void main(String[] args) {
new Frame();
}
}
when window.setVisible(true); is in the bottom.
when window.setVisible(true); is at the top.
How it is supposed to look.(我手动将鼠标悬停在所有对象上。)
【问题讨论】:
-
停止
.setBounds(...)。 Swing 不打算以这种方式使用,并且这样做,您正在与库和布局管理器作斗争。作弊解决方案是将布局管理器设置为null,但这只会延续坏习惯并允许创建仅在一个系统上工作的GUI。真正的解决方案是学习和使用布局管理器。
标签: java swing jframe jpanel jbutton