java GridBagLayout锚点

前端之家收集整理的这篇文章主要介绍了java GridBagLayout锚点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
学习GridBagLayout,这里的问题是,名称标签和com@R_301_460@没有显示在面板的顶部,但我已将其锚点设置为NORTH.为什么?
  1. import java.awt.GridBagConstraints;
  2. import java.awt.GridBagLayout;
  3. import java.awt.GridLayout;
  4.  
  5. import javax.swing.JCombo@R_301_460@;
  6. import javax.swing.JFrame;
  7. import javax.swing.JLabel;
  8. import javax.swing.JPanel;
  9. import javax.swing.WindowConstants;
  10.  
  11. public class Test2 {
  12. public Test2() {
  13. JFrame frame = new JFrame();
  14. frame.setTitle("test");
  15. frame.getContentPane().setLayout(new GridLayout(1,2));
  16. frame.setSize(800,600);
  17.  
  18. JPanel panel1 = new JPanel();
  19. panel1.setLayout(new GridBagLayout());
  20.  
  21. JLabel label = new JLabel("name");
  22. GridBagConstraints gridBagConstraints = new GridBagConstraints();
  23. gridBagConstraints.anchor = GridBagConstraints.NORTH;
  24. gridBagConstraints.weightx = 0.0;
  25. gridBagConstraints.weighty = 0.0;
  26. gridBagConstraints.gridx = 0;
  27. gridBagConstraints.gridy = 0;
  28. panel1.add(label,gridBagConstraints);
  29.  
  30. String[] petStrings = { "Bird","Cat","Dog","Rabbit","Pig" };
  31. JCombo@R_301_460@ petList = new JCombo@R_301_460@(petStrings);
  32. gridBagConstraints = new GridBagConstraints();
  33. gridBagConstraints.anchor = GridBagConstraints.NORTH;
  34. gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
  35. gridBagConstraints.weightx = 1.0;
  36. gridBagConstraints.weighty = 0.0;
  37. gridBagConstraints.gridx = 1;
  38. gridBagConstraints.gridy = 0;
  39. panel1.add(petList,gridBagConstraints);
  40.  
  41. frame.getContentPane().add(panel1);
  42. frame.getContentPane().add(new JPanel());
  43.  
  44. frame.setVisible(true);
  45. frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
  46. }
  47.  
  48. public static void main(String[] args) {
  49. new Test2();
  50. }
  51. }

解决方法

你必须改变
  1. gridBagConstraints.weighty = 0.0;

  1. gridBagConstraints.weighty = 1.0;

否则为组件保留的区域会缩小到组件的大小,并且无论您在哪个方向“锚定”组件.

改变重量后的结果如下:

猜你在找的Java相关文章