我正在为计算器制作一个简单的布局,实际上我是java的新手,并且学习了基础知识。我的问题是,当我运行此代码时,只打开一个JFrame,并且不显示其按钮的其他面板。 PLz帮助,我的错误。
import java.awt.*;
import javax.swing.*;
public class Layouts extends JFrame{
public Layouts(){
super("Calculator");
setLookAndFeel();
setSize(350,350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border = new BorderLayout();
setLayout(border);
GridLayout numbers = new GridLayout(2,2);
row2.setLayout(numbers);
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
GridLayout operators = new GridLayout(2,2);
row3.setLayout(operators);
row3.add(plus);
row3.add(subtract);
row3.add(multiply);
row3.add(equals);
setVisible(true);
}
private void setLookAndFeel()
{
try
{
IManager.setLookAndFeel("com.sun.java.lang.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc)
{
}
}
//row 1
JPanel row1 = new JPanel();
JTextField text = new JTextField(20);
//row 2
JPanel row2 = new JPanel();
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
//row3
JPanel row3 = new JPanel();
JButton plus = new JButton("+");
JButton subtract = new JButton("-");
JButton multiply = new JButton("*");
JButton equals = new JButton("=");
public static void main(String[] args)
{
Layouts l1 = new Layouts();
}
}
答案 0 :(得分:0)
BorderLayout border = new BorderLayout();
setLayout(border);
但是你没有向border
添加任何东西!添加numbers
和operators
。
答案 1 :(得分:0)
请记住添加所有组件(即row2,row3等)。
示例:
add(row2,BorderLayout.CENTER)
add(row3,BorderLayout.SOUTH)
答案 2 :(得分:0)
您需要将JPanel
和JButton
添加到JFrame
。在这种情况下,JFrame
是您的Layouts
类。所以做一些像:
row1.add(text);
this.add(row1);
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
this.add(row2);
...
检查本教程是非常有用的JButton, JPanel & JFrame examples