我尝试将组件放置在面板中,如下所示:

但在我的代码中,它看起来是这样的:

我在没有FlowLayout的情况下尝试过,但问题是一样的。当我将窗口大小设为最大值时,它会在一行中显示,但当我尝试调整窗口大小时,组件会从边框中移出。
你能帮我解决这个问题吗?下面是我的代码:
CNameLabel=new JLabel("Customer Name");
CNameTextField = new JTextField (20); // create the Customer Name text field
CNameTextField.setEditable(true); // set editable text box
CIDLabel=new JLabel("Customer ID");
C_IDTextField = new JTextField (10);
C_IDTextField.setEditable(true); // set editable text box
// Creating and populating the Top Panel下面的代码用于创建面板,设置面板的边框,以及设置组件的流布局:
topPanel=new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.setBorder(new TitledBorder(new EtchedBorder(), "Customer Data"));
topPanel.add(CNameLabel); topPanel.add(CNameTextField); topPanel.add(CIDLabel);
topPanel.add(C_IDTextField);
roomTypeLabel=new JLabel ("Room Type ");
//Create and populate Room type combo box
roomTypeCombo = new JComboBox();
roomTypeCombo.addItem( "Budget($50)" );
roomTypeCombo.addItem( "Standard($75)" );
roomTypeCombo.addItem( "Executive($200)" );
roomTypeCombo.addItem( "Luxury($400)" );
mealLabel=new JLabel ("Meal ");
//Create and populate Meal type combo box
mealCombo = new JComboBox();
mealCombo.addItem( "None" );
mealCombo.addItem( "Breakfast Only($10)" );
mealCombo.addItem( "Any Two($30)" );
mealCombo.addItem( "All Three($50)" );
daysLabel=new JLabel ("Days");
//Create and populate Days combo box
daysCombo = new JComboBox();
for(int i=0;i<31 ; i++)
{
daysCombo.addItem(i); // populate combobox with days
}
//Adding components to top panel
topPanel.add(roomTypeLabel);
topPanel.add(roomTypeCombo);
topPanel.add(mealLabel);
topPanel.add(mealCombo);
topPanel.add(daysLabel);
topPanel.add(daysCombo);我刚刚跳过了组件的包和声明。程序运行状况良好。
提前谢谢。
发布于 2012-04-10 11:46:00
最后,您可能需要调用pack()。我猜如果你想在newline中输入房间类型,那么你需要使用gridlayout,但不要忘记最后调用pack()。
https://stackoverflow.com/questions/10082601
复制相似问题