日期:2014-05-20  浏览次数:21215 次

Swing的布局问题
以下代码定义一个窗口后在Panel中添加按钮、菜单、文本框,但是运行的效果是没有显示单行文本框TextField,其他的都正常,不知是哪里出错问题,请各位指点。谢谢

package SwingComponent;
import java.awt.BorderLayout;

import javax.swing.*;
import javax.swing.event.*;

public class SwingComponent01 
{
JFrame frame = new JFrame("测试");

JButton ok = new JButton("确定");
JButton cancel = new JButton("取消");

JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("文件");
JMenu edit = new JMenu("编辑");
JMenu tool = new JMenu("工具");
JMenu windows = new JMenu("窗口");
JMenu help = new JMenu("帮助");

JMenuItem create = new JMenuItem("新建");
JMenuItem open = new JMenuItem("打开");
JMenuItem save = new JMenuItem("保存");
JMenuItem exit = new JMenuItem("退出");

JRadioButton male = new JRadioButton("男", true);
JRadioButton female = new JRadioButton("女", false);
ButtonGroup bg = new ButtonGroup();

JCheckBox marry = new JCheckBox("已婚", false);
JCheckBox notMarry = new JCheckBox("未婚", false);
ButtonGroup bg2 = new ButtonGroup();

JTextField textField = new JTextField(40);
JTextArea textArea = new JTextArea(8,40);

//界面初始化方法init()
public void init()
{
JPanel button = new JPanel();

button.add(textField); //为何在JPanel中没有显示"textField"呢?
button.add(ok);
button.add(cancel);
frame.add(button,BorderLayout.SOUTH);

JPanel checkPanel = new JPanel();
bg.add(male);
bg.add(female);
checkPanel.add(male);
checkPanel.add(female);
checkPanel.add(marry);
checkPanel.add(notMarry);
bg2.add(marry);
bg2.add(notMarry);

file.add(create);
file.add(open);
file.add(save);
file.add(exit);

menubar.add(file);
menubar.add(edit);
menubar.add(tool);
menubar.add(windows);
menubar.add(help);

frame.add(textField);
frame.add(checkPanel);

Box topLeft = Box.createVerticalBox();
JScrollPane taJsp = new JScrollPane(textArea);
topLeft.add(taJsp);
topLeft.add(checkPanel);

Box top = Box.createHorizontalBox();
top.add(topLeft);

frame.add(top);
frame.add(menubar,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}



/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
new SwingComponent01().init();

}

}

------解决方案--------------------
frame.add(textField);

这句话去掉,坑爹啊~~