一些背景:我正在制作一个程序,它使用一个充满各种类型节点的JTree。 TreeSelectionListener确定它是什么类型的节点,清除组件的内部JPanel,然后将相应的JPanel添加到它刚刚清除的JPanel,以编辑特定于该类型节点的属性。 JPanel使用GridBagLayout,但文本字段没有正确显示(注意:标题是JTextField,描述是JTextArea:
JPanel的代码如下:
class nodePanel extends JPanel{
public nodePanel(DefaultMutableTreeNode info){
super(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets=new Insets(10,10,10,10);
c.gridx=0;
c.gridy=0;
c.gridheight=1;
c.gridwidth=1;
c.weightx=0;
c.weighty=0;
c.fill=GridBagConstraints.NONE;
c.anchor=GridBagConstraints.EAST;
this.add(new JLabel("Title: "),c);
c.gridy=1;
c.weighty=2;
c.gridheight=2;
this.add(new JLabel("Description: "),c);
c.gridx=1;
c.gridy=0;
c.gridheight=1;
c.gridwidth=2;
c.weightx=100;
c.weighty=0;
c.anchor=GridBagConstraints.WEST;
c.fill=GridBagConstraints.HORIZONTAL;
JTextField title = new JTextField();
title.setMinimumSize(new Dimension(300,25));
this.add(title,c);
c.gridy=1;
c.gridheight=2;
c.weighty=200;
JTextArea description = new JTextArea();
JScrollPane descriptionScroll= new JScrollPane(description);
descriptionScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
descriptionScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
this.add(descriptionScroll, c);
}
}
谢谢
答案 0 :(得分:3)
// ..
JTextField title = new JTextField(20); // suggest a size in columns!
//title.setMinimumSize(new Dimension(300,25)); // don't call these methods! (1)
this.add(title,c);
c.gridy=1;
c.gridheight=2;
c.weighty=200;
JTextArea description = new JTextArea(3, 15); // suggest a size in rows/cols!
// ..
答案 1 :(得分:0)
好吧,问题不在于JPanel本身 - 封闭的JPanel有Gridbag,但没有设置重量或任何尺寸。猜猜它表明问题是你最不期望的地方。
答案 2 :(得分:0)
它,是因为你没有给它长度。如果你在其中添加长度它将工作正常。用这个代替你的代码
JTextField title = new JTextField(10);
JTextArea description = new JTextArea(2,10);
答案 3 :(得分:0)
class nodePanel extends JPanel{
public nodePanel(DefaultMutableTreeNode info){
super(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets=new Insets(10,10,10,10);
c.gridx=0;
c.gridy=0;
c.gridheight=1;
c.gridwidth=1;
c.weightx=0;
c.weighty=0;
c.fill=GridBagConstraints.NONE;
c.anchor=GridBagConstraints.EAST;
this.add(new JLabel("Title: "),c);
c.gridy=1;
c.weighty=2;
c.gridheight=2;
this.add(new JLabel("Description: "),c);
c.gridx=1;
c.gridy=0;
c.ipadx=20;
c.gridheight=1;
c.gridwidth=2;
c.weightx=100;
c.weighty=0;
c.anchor=GridBagConstraints.WEST;
c.fill=GridBagConstraints.HORIZONTAL;
JTextField title = new JTextField(10);
title.setMinimumSize(new Dimension(300,25));
this.add(title,c);
c.gridy=1;
c.gridheight=2;
c.ipadx=20;
c.ipady=5;
c.weighty=200;
JTextArea description = new JTextArea(5,2);
JScrollPane descriptionScroll= new JScrollPane(description);
descriptionScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
descriptionScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
this.add(descriptionScroll, c);
}
}
使用此代码
我改变了你的代码。你没有使用c.ipadx
我添加这个字段,它应该可以工作。