Java Swing GridBagLayout – 添加没有空格的按钮
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java Swing GridBagLayout – 添加没有空格的按钮,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2671字,纯文字阅读大概需要4分钟。
内容图文
如何删除gridBagLayout引起的间距并使它们粘在一起?
这是我的代码只需添加3个按钮.
我读了这个问题,但没有完整的解决方案How to fix gap in GridBagLayout;
我只想将所有按钮放在JFrame的顶部.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyProblem {
private JFrame frame = new JFrame();
public static void main(String[] args) {
new MyProblem();
}
public MyProblem() {
frame.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1;
gc.weighty = 1;
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.NORTH;
for (int i = 0; i < 3; i++) {
JPanel jPanel = new JPanel(new BorderLayout());
jPanel.setSize(80, 80);
jPanel.add(new JButton("Button " + i),BorderLayout.PAGE_START);
frame.add(jPanel, gc);
gc.gridy++;
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
我的按钮如何:
我希望我的按钮看起来像:
解决方法:
布局会产生一列按钮,所以..
更改:
gc.fill = GridBagConstraints.HORIZONTAL;
至:
gc.fill = GridBagConstraints.BOTH;
编辑1
I want to keep buttons to the same height as described in picture and just putting them at the top.
使用组合布局将它们限制在顶部相当容易.在这种情况下,我们可能会将带有按钮的面板添加到带有BorderLayout的面板的PAGE_START中.边框布局的那一部分将拉伸子组件的宽度(我们的面板与GridLayout)来填充可用空间,但它将尊重其中任何内容的高度 – 为组件提供所需的垂直空间.
编辑2
这是一个实现上述想法的MCVE.外面板(带有青色边框)用于约束按钮面板的高度(带橙色边框).有关其工作原理的更多详细信息,请参阅源代码中的注释.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class MyProblem {
private JFrame frame = new JFrame();
public static void main(String[] args) {
new MyProblem();
}
public MyProblem() {
frame.setLayout(new BorderLayout()); // actually the default
// we will use this panel to constrain the panel with buttons
JPanel ui = new JPanel(new BorderLayout());
frame.add(ui);
ui.setBorder(new LineBorder(Color.CYAN, 3));
// the panel (with GridLayout) for the buttons
JPanel toolPanel = new JPanel(new GridLayout(0,1,0,4)); // added some gap
toolPanel.setBorder(new LineBorder(Color.ORANGE, 3));
// toolPanel will appear at the top of the ui panel
ui.add(toolPanel, BorderLayout.PAGE_START);
for (int i = 0; i < 3; i++) {
toolPanel.add(new JButton("Button " + i));
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setSize(500, 500); // instead..
frame.pack(); // pack will make it as small as it can be.
frame.setMinimumSize(frame.getSize()); // nice tweak..
frame.setVisible(true);
}
}
内容总结
以上是互联网集市为您收集整理的Java Swing GridBagLayout – 添加没有空格的按钮全部内容,希望文章能够帮你解决Java Swing GridBagLayout – 添加没有空格的按钮所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。