在下面的代碼,當一個JPanel沒有添加到JFrame extention,程序工作正常,但後來,我註釋掉JPanel並使用了網格佈局,一切都正確,並很好地放置在JFrame的。 JPanel如何顯示對象會受到一些限制嗎?在代碼中,我註釋掉下面的語句:Java中的任何JPanel限制?
this.setLayout(new GridLayout(3,2));
this.add(nameLabel);
this.add(name);
this.add(urlLabel);
this.add(url);
this.add(typeLabel);
this.add(type);
,並錯誤地顯示程序,但如果上面的語句去掉註釋和下面的一個評論說:
//add some panes..
JPanel panel = new JPanel();
panel.add(nameLabel);
panel.add(name);
panel.add(urlLabel);
panel.add(url);
panel.add(typeLabel);
panel.add(type);
this.add(panel);
,則程序工作正常以下是完整的代碼摘錄。
[CODE]
public class FeedInfo extends JFrame {
private JLabel nameLabel = new JLabel("Name:", SwingConstants.RIGHT);
private JTextField name;
private JLabel urlLabel = new JLabel("URL",SwingConstants.RIGHT);
private JTextField url;
private JLabel typeLabel = new JLabel("Type",SwingConstants.RIGHT);
private JTextField type;
public FeedInfo()
{
super("Feed Information");
this.setSize(400,105);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String response1 = JOptionPane.showInputDialog(null,"Enter the site name:");
name = new JTextField(response1,20);
String response2 = JOptionPane.showInputDialog(null,"Enter the site address:");
url = new JTextField(response2, 20);
String[] choices ={"Personal","Commercial","Unkown"};
int response3 = JOptionPane.showOptionDialog(null, "what type of site is it?",
"site Type",0, JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
type = new JTextField(choices[response3],20);
//add some panes..
JPanel panel = new JPanel();
panel.add(nameLabel);
panel.add(name);
panel.add(urlLabel);
panel.add(url);
panel.add(typeLabel);
panel.add(type);
this.add(panel);
/*this.setLayout(new GridLayout(3,2));
this.add(nameLabel);
this.add(name);
this.add(urlLabel);
this.add(url);
this.add(typeLabel);
this.add(type);
*/
this.setVisible(true);
}
[/CODE]
請注意,'GridLayout'不太適合顯示名稱/值對的行。一般而言,帶標籤的列應該比具有值的列要薄。在最近的時間裏,我會爲此尋找'GroupLayout',而在之前的JRE中,我可能使用了嵌套佈局。 – 2012-03-26 15:16:15