【问题标题】:Placing buttons in a specified location using swing in java使用java中的swing将按钮放置在指定位置
【发布时间】:2012-12-01 18:58:31
【问题描述】:

我正在尝试学习如何制作 JAVA 程序并且我正在使用 Swing。我正在尝试在窗口的左上角放置一个按钮,并且它一直在顶部中心。

public void createGUI(){
    JFrame frame = new JFrame("My Project");
    frame.setDefaultCloseOperation(3);
    frame.setSize(400, 350);
    frame.setVisible(true);

    JPanel panel = new JPanel();

    frame.add(panel);

    addButtonGUI(panel, new JButton(), "test", 1, 1);
}

public void addButtonGUI(JPanel panel, JButton button, String text, int x, int y){
    GridBagConstraints gbc = new GridBagConstraints();
    button.setText(text);
    button.setEnabled(true);
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = 2;
    gbc.weightx = 1.0D;
    gbc.fill = 2;
    panel.add(button, gbc);
}

我做错了什么还是有更好的方法来做到这一点? 请帮忙

【问题讨论】:

  • frame.setDefaultCloseOperation(3); 不要使用幻数。 J2SE 为这些值提供了描述性命名的常量。

标签: java swing jpanel layout-manager gridbaglayout


【解决方案1】:

您需要将JPanel的布局设置为GridBagLayout才能使用GridBagConstraints

JPanel panel = new JPanel(new GridBagLayout());

此外,由于您只有一个有效的“单元格”,您需要使用锚点并将 weighty 设置为 JButton 以允许在 Y 轴上移动。

gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1.0;

我还将fill 设置为NONE

gbc.fill = GridBagConstraints.NONE;

这样按钮就不会占据面板的整个宽度。 (2 = 水平填充)。

【讨论】:

    【解决方案2】:

    而不是

    addButtonGUI(panel, new JButton(), "test", 1, 1);
    }
    

    如果你使用会发生什么

    addButtonGUI(panel, new JButton(), "test", 0, 0);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2023-04-06
      • 2015-08-18
      • 2015-06-16
      • 2012-08-19
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多