java - 如何对齐按钮

标签 java swing layout-manager

按钮一个接一个地水平放置。我需要知道如何使它们垂直出现在屏幕上。我尝试添加 SwingConstants.xxxx。然后 item.SwingConstants.xxx 出现水平对齐错误。任何帮助表示赞赏。 (想坚持这种风格的节目)

import java.awt. * ;
import java.awt.event. * ;
import javax.swing. * ;

@SuppressWarnings("serial")
public class Class_GUI_4 extends JFrame {
  private JTextField tf; // textfield
  private JCheckBox b1; // button 1
  private JCheckBox b2; // button2
  public Class_GUI_4() {
    super("TITLE");
    setLayout(new FlowLayout());

    tf = new JTextField("A testing Sentence", 20);
    tf.setFont(new Font("Serif", Font.PLAIN, 14));
    add(tf);

    b1 = new JCheckBox("Bold");
    b2 = new JCheckBox("Italic");
    add(b1);
    add(b2);

    thehandler handler = new thehandler();
    b1.addItemListener(handler);
    b2.addItemListener(handler);
  }

  private class thehandler implements ItemListener {
    @Override
    public void itemStateChanged(ItemEvent event) {
      Font font = null;
      if (b1.isSelected() && b2.isSelected()) font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
      else if (b1.isSelected()) font = new Font("Serif", Font.BOLD, 14);
      else if (b2.isSelected()) font = new Font("Serif", Font.ITALIC, 14);
      else font = new Font("Serif", Font.PLAIN, 14);
      tf.setFont(font);
    }
  }

  public static void main(String[] args) {
    Class_GUI_4 gui = new Class_GUI_4();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setSize(200, 350);
    gui.setVisible(true);
  }
}

最佳答案

how to make them come on screen vertically?

尝试使用 BoxLayout

setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

而不是 FlowLayout在本例中,它按定向流排列组件,就像段落中的文本行一样。

setLayout(new FlowLayout());

值得一读How to Use BoxLayout

enter image description here

<小时/>

不要在这种情况下使用 GridLayout 来添加相同大小的组件,如下所示:

enter image description here

<小时/>

您可以尝试使用 GridBagLayout 。了解更多关于 How to Use GridBagLayout

示例代码:(根据您的要求以百分比更改高度)

setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;

//Set the margin between components top, left, bottom, right
//gc.insets=new Insets(5, 5, 5, 5);

tf = new JTextField("A testing Sentence", 20);
tf.setFont(new Font("Serif", Font.PLAIN, 14));

gc.gridx = 0; // 1st row
gc.gridy = 0; // 1st column
gc.weighty = 0.9; // 90%
add(tf, gc);

b1 = new JCheckBox("Bold");
b2 = new JCheckBox("Italic");
gc.gridy = 1; // 2nd column
gc.weighty = 0.05;// 5%
add(b1, gc);

gc.gridy = 2; // 3rd column
gc.weighty = 0.05;// 5%
add(b2, gc);

enter image description here

关于java - 如何对齐按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096507/

相关文章:

java - 如何在heroku 上为Java 进程生成线程转储?

java - 从 Realm 数据库中的清除中排除列

java - 将java swing应用程序连接到共享服务器上的ms access db的最佳方法?

java - 如何不扩展 Swing 组件?

Java Swing 取消无限循环

java - 将响应编码为 Gzip 导致无法在浏览器中设置 Cookie

java - 如何使用构建类或 war 文件将我的 Spring MVC Web 应用程序部署到 Apache tomat 目录中?

java - MigLayout 列约束

java - 删除 GridBagLayout 中按钮周围的空间

java - 如何更改 JButton 的大小?