Here is the code snippet:
public class Test {
Test(){
JFrame f=new JFrame();
JPanel panel=new JPanel();
GridBagLayout gb=new GridBagLayout();
panel.setLayout(gb);
GridBagConstraints gc= new GridBagConstraints();
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=1;
gc.gridy=0;
String label="hello";
JLabel l1=new JLabel(label);
panel.add(l1,gc);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=0;
gc.gridy=0;
JCheckBox check=new JCheckBox();
check.getAccessibleContext().setAccessibleDescription(label);
panel.add(check,gc);
f.add(panel);
f.setSize(200, 300);
f.setVisible(true);
}
public static void main(String[] args) {
Test t=new Test();
}
}
checkbox and label are coming fine from left to right but the problem which I am facing is label is coming little bit above from the checkbox what should I do to make them come in same line ?
As I have tested your code it was because of the gc.anchor=GridBagConstraints.NORTHWEST;
the text is not aligning in the center of the checkbox. I don't get it why you needed that anchor but if you want to align the text and the checkbox to the left you can use setHorizontalTextPosition(SwingConstants.LEFT)
as suggested by @a_horse_with_no_name. Try running this code below you'll see that it's perfectly aligned.
public class Testcheckbox {
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
public Testcheckbox(){
JFrame f=new JFrame();
JPanel content = new JPanel();
content.setLayout(new FlowLayout(SwingConstants.NORTH_WEST));
JPanel panel=new JPanel();
panel.setLayout(gb);
String label="hello";
JLabel l1=new JLabel(label);
l1.setHorizontalTextPosition(SwingConstants.LEFT);
// gc.anchor=GridBagConstraints.NORTHWEST;
gc.weightx = 0;
gc.weighty = 0;
gc.gridx = 1;
gc.gridy = 0;
panel.add(l1,gc);
JCheckBox check=new JCheckBox();
check.getAccessibleContext().setAccessibleDescription(label);
check.setHorizontalTextPosition(SwingConstants.LEFT);
// gc.anchor=GridBagConstraints.NORTH;
gc.weightx = 0;
gc.weighty = 0;
gc.gridx = 0;
gc.gridy = 0;
panel.add(check,gc);
f.add(content);
content.add(panel);
f.setSize(200, 300);
f.setVisible(true);
}
public static void main(String[] args) {
Testcheckbox t = new Testcheckbox();
}
}
EDIT
Check my code above again and I have updated it. I have added another panel
so that the layout of the gridbag
is not affected by where you want to put the content of the panel
in the JPanel
. Did I get that right?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.