Java gridbaglayout anchor
•
Java
Learn gridbaglayout. The problem here is the name and label com@R_950_2419 @It does not appear at the top of the panel, but I have set its anchor to north Why?
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.JCombo@R_950_2419@; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; public class Test2 { public Test2() { JFrame frame = new JFrame(); frame.setTitle("test"); frame.getContentPane().setLayout(new GridLayout(1,2)); frame.setSize(800,600); JPanel panel1 = new JPanel(); panel1.setLayout(new GridBagLayout()); JLabel label = new JLabel("name"); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.anchor = GridBagConstraints.NORTH; gridBagConstraints.weightx = 0.0; gridBagConstraints.weighty = 0.0; gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panel1.add(label,gridBagConstraints); String[] petStrings = { "Bird","Cat","Dog","Rabbit","Pig" }; JCombo@R_950_2419@ petList = new JCombo@R_950_2419@(petStrings); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.anchor = GridBagConstraints.NORTH; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 0.0; gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; panel1.add(petList,gridBagConstraints); frame.getContentPane().add(panel1); frame.getContentPane().add(new JPanel()); frame.setVisible(true); frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new Test2(); } }
Solution
You have to change
gridBagConstraints.weighty = 0.0;
to
gridBagConstraints.weighty = 1.0;
Otherwise, the area reserved for the component will shrink to the size of the component and "anchor" the component in any direction
The results after changing the weight are as follows:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码