java的swing中如何在gridbaglayout下把三列组件紧密联在一起
这是我目前的样式图我想让选择和提交两个按钮以及左侧的文本框连在一起三者之间不能有空隙这是我的代码add(fileLocation,newConstraints(1,1,1...
这是我目前的样式图 我想让选择和提交两个按钮以及左侧的文本框连在一起 三者之间不能有空隙这是我的代码add(fileLocation,new Constraints(1,1,1,1,100,100).setAnchor(Constraints.EAST).setFill(Constraints.HORIZONTAL)); add(fileOperation,new Constraints(2,1,1,1,100,100).setAnchor(Constraints.EAST)); add(fileUpload,new Constraints(3,1,1,1,100,100).setAnchor(Constraints.WEST)); 其中Constraints类继承了GridBagConstraints类 构造方法的四个参数分别是gridx gridy gridwidth gridheight weightx weighty这是构造方法的代码public Constraints(int gridx,int gridy,int gridwidth,int gridheight,int weightx,int weighty){ this.gridx=gridx; this.gridy=gridy; this.gridwidth=gridwidth; this.gridheight=gridheight; this.weightx=weightx; this.weighty=weighty; } 怎么弄 谢谢
展开
1个回答
展开全部
估计是两个按钮的weightx weighty 的范围弄错了,我尝试了下你的代码,如下
public class TestFrame {
public TestFrame() {
JFrame f = new JFrame();
JPanel p = new JPanel(new GridBagLayout());
JTextField fileLocation = new JTextField(20);
JButton fileOperation = new JButton("OK");
JButton fileUpload = new JButton("Cancel");
p.add(fileLocation, new Constraints(0, 0, 1, 1, 1, 1).setFill(GridBagConstraints.HORIZONTAL));
p.add(fileOperation,new Constraints(1, 0, 1, 1, 0, 0));
p.add(fileUpload,new Constraints(2, 0, 1, 1, 0, 0));
f.add(p);
f.pack();
f.setDefaultCloseOperation(3);
f.setVisible(true);
}
public static void main(String[] args) {
new TestFrame();
}
}
class Constraints extends GridBagConstraints {
public Constraints(int gridx, int gridy, int gridwidth, int gridheight,
int weightx, int weighty) {
this.gridx = gridx;
this.gridy = gridy;
this.gridwidth = gridwidth;
this.gridheight = gridheight;
this.weightx = weightx;
this.weighty = weighty;
}
public Constraints setAnchor(int i){
this.anchor = i;
return this;
}
public Constraints setFill(int i){
this.fill = i;
return this;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询