gpt4 book ai didi

java - Java 中有 JPanel 限制吗?

转载 作者:行者123 更新时间:2023-12-01 07:13:08 25 4
gpt4 key购买 nike

在下面的代码中,当 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]

最佳答案

JPanel 本身不执行布局,它使用 LayoutManager。在您的情况下,您想要覆盖默认的 FlowLayout 并使用 GridLayout (就像您对 JFrame 所做的那样)。所以就这样做吧!

JPanel panel = new JPanel(new GridLayout(3, 2));
...

关于java - Java 中有 JPanel 限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com