【问题标题】:Create 2 buttons on the same x axis in jFrame在 jFrame 的同一个 x 轴上创建 2 个按钮
【发布时间】:2020-05-05 22:35:28
【问题描述】:

我下面的 java 代码具有一个图像和一个按钮,我只想添加另一个按钮,该按钮与当前按钮所在的 x 轴位于同一 x 轴上。我不知道该怎么做。我以为我试图操纵 abc.weightx 并对其进行更改,但没有任何效果。我在下面附上了一张我正在尝试做的事情的图片。

    import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
    import java.io.IOException;
    import java.net.URL;
   import javax.swing.ImageIcon;
    import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JLabel;

    class Main extends JFrame {

public static void main(String[] args0) {

    try {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

        frame.getContentPane().setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 0.5;
        gbc.weighty = 0.4;
        gbc.fill = GridBagConstraints.BOTH;

        URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
        ImageIcon image = new ImageIcon(url);
        JLabel imageLabel = new JLabel(image);
        frame.add(imageLabel, gbc);

        gbc.weightx = 0.9;
        gbc.weighty = 0.1;
        gbc.fill = GridBagConstraints.NONE;







        JButton b = new JButton("Click Here");
        frame.add(b, gbc);

        frame.pack();
        frame.setVisible(true);

    } catch (IOException e) {
        e.printStackTrace();
    }
}}

【问题讨论】:

    标签: java swing layout layout-manager


    【解决方案1】:

    将按钮放在居中的流布局中。将流式布局放在边框布局的页面末尾。

    【讨论】:

    • 我是 java 新手,不知道该怎么做?你能用代码给我看看吗?非常感谢你的帮助。
    • “你能用代码给我看看吗” SO不是代码生成服务。如果您尝试实施建议并失败,请edit 发布minimal reproducible example,我会进一步查看。
    【解决方案2】:

    您没有从GridBagConstraint 设置gridxgridy,因此它们可能不会出现在您希望它们出现的位置。

    我建议关注@AndrewThompson's advice 并选择BorderLayout,您的主面板位于BorderLayout.CENTER 位置,您的按钮位于单独的JPanel,默认为FlowLayout,您会放在BorderLayout.SOUTH的位置。

    如果你想坚持GridBagLayout

    • 主面板:gridx=0gridy=0gridwidth=2weightx=1weighty=1
    • 左键:gridx=0gridy=1
    • 右键:gridx=1gridy=1

    我不会发布代码,因为如果你自己尝试一下,你会学到更多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2018-11-29
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多