首页 > 解决方案 > 在 jFrame 的同一个 x 轴上创建 2 个按钮

问题描述

我下面的 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();
    }
}}

标签: javaswinglayoutlayout-manager

解决方案


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

我建议您遵循@AndrewThompson 的建议,将BorderLayout您的主面板放在该BorderLayout.CENTER位置,并将您的按钮与您放在该位置JPanel的 default分开。FlowLayoutBorderLayout.SOUTH

如果你想坚持GridBagLayout

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

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


推荐阅读