swing – GridBagLayout多个按钮边框
发布时间:2020-12-15 02:27:21 所属栏目:Java 来源:网络整理
导读:我正在尝试使用BoxLayout在JPanel中使用GridBagLayout 10(3×3 1)JButton. 但是我使用胶合盒或类似的GridBagLayout JPanel会占用BoxLayout中的所有额外空间.我可能遗漏了一些东西,或者这是不可能做到的? 我使用的一个解决方案是使用gridbaglayout内的扩展元
我正在尝试使用BoxLayout在JPanel中使用GridBagLayout 10(3×3 1)JButton.
但是我使用胶合盒或类似的GridBagLayout JPanel会占用BoxLayout中的所有额外空间.我可能遗漏了一些东西,或者这是不可能做到的? 我使用的一个解决方案是使用gridbaglayout内的扩展元素向上推按钮.这会将按钮放在正确的位置,但边框似乎很大. 以下是我的示例代码: import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class GridBagLayoutTest extends JFrame { public GridBagLayoutTest(){ super(); this.setTitle("JVectorView"); this.setSize(300,300); this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); Container content = this.getContentPane(); content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS)); content.add(new JLabel("Hello!")); content.add(new Controls()); content.add(Box.createGlue()); this.setVisible(true); } private class Controls extends JPanel{ private static final int WIDTH = 3,HEIGHT = 3; public Controls(){ GridBagConstraints constraints = new GridBagConstraints(); //this.setBorder(BorderFactory.createLineBorder(Color.red)); this.setBorder(BorderFactory.createTitledBorder("Some stuff")); constraints.fill = GridBagConstraints.NONE; this.setLayout(new GridBagLayout()); for(int row = 0; row < HEIGHT; row++){ for(int col = 0; col < WIDTH; col++){ constraints.gridx = col; constraints.gridy = row; this.add(new JButton("B"+(col+row*WIDTH)),constraints); } } constraints.gridx = 1; constraints.gridy = 3; this.add(new JButton("B"+(10)),constraints); } } public static void main(String[] args) { new GridBagLayoutTest(); } } 我希望边框紧贴按钮.是否可以让gridbaglayout在其内容上崩溃,还是总是强制填充面板? 解决方法JPanel p=new JPanel(new FlowLayout()); p.add(new Controls()); content.add(p); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |