我正在为计算器做一个简单的布局,实际上我是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();
}
}
最佳答案
请记住添加所有组件(即row2,row3等。)
例:
add(row2,BorderLayout.CENTER)
add(row3,BorderLayout.SOUTH)
关于java - Jframe中的JPanels未显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13730840/