在Java中是否有JPanel限制?
在下面的代码中,当一个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]
# 1 楼答案
您的程序在第二段代码中没有按预期工作,因为您正在使用
JPanel panel = new JPanel();
默认情况下,通过这一行,您可以从JPanel API中看到,您正在创建一个布局为
FlowLayout
的JPanel。JPanel API报告,关于空承包商:一般来说,对于JPanel来说,流布局是最简单的布局,不可能以易懂且简单的方式加载Swing内容。您正在使用的GridLayout提供了在网格中加载组件的能力,这有助于显示Java应用程序的GUI
现在,你知道了,因为这个程序有一个基本的FlowLayout,当你使用GridLayout时,它并没有像预期的那样显示所有swing组件。 如果要创建带有GridLayout的JPanel,只需键入:
在this页面和here中有一些关于JPanel和布局的教程
# 2 楼答案
有两个重要的事实需要知道。默认情况下,JFrame使用BorderLayout。默认情况下,JPanel使用Flowlayout。这就是为什么根据要将其他组件添加到的组件,您会看到不同的行为
FlowLayout几乎一文不值,所以当使用JPanel时,你几乎总是想更改它@马克·彼得斯向你展示了如何做到这一点。对于顶级容器来说,BorderLayout几乎总是完美的,我很少改变这一点。我倾向于将BoxLayout几乎完全用于嵌套的JPanel
# 3 楼答案
当您这样做时,您正在将JPanel添加到JFrame上,但是JFrame的布局没有改变,这意味着默认情况下它有BorderLayout。尝试将最后一行更改为:
add(panel, BorderLayout.CENTER);
你可以阅读更多关于JFramehere此外,JPanel的默认设置是FlowLayout,这意味着对象将被添加到“流动线”中。您应该在JPanel上设置布局,以获得所需的结果
# 4 楼答案
JPanel
本身不执行布局,它使用LayoutManager
。在您的例子中,您希望覆盖默认的FlowLayout
并使用GridLayout
(就像您对JFrame
所做的那样)。那就这么做吧