在下面的代码中,当 JPanel 没有添加到 JFrame 扩展中时,程序可以正常工作,但是,我注释掉了 JPanel 并使用了 GridLayout,一切都正确且很好地放置在 JFrame 上。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]