为什么 JButton 没有占据整个屏幕?

问题描述 投票:0回答:1

我刚刚开始使用 Java Swing 和 GridBagLayout,我不知道如何让按钮占据我试图给它的所有空间(在本例中是整个窗口)。如果我的代码看起来很糟糕,我深表歉意,我只是将 Java 作为一种爱好,并且没有接受过正式的培训。

这是 Main.java 中的代码:

gui = new Gui();
gui.textButton("Hello World!", 1.0, 1.0, 0, 0, 1, 1);

这是来自 Gui.java 的代码:

public class Gui extends JFrame {


    private static GridBagLayout gbl = new GridBagLayout();
    public JPanel panel = new JPanel();


    public Gui() {


        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        this.setTitle("Conlang Translator");
        this.setIconImage(new ImageIcon("images\\icon.png").getImage());

        
        this.setLayout(gbl);
        this.add(panel);
        this.setVisible(true);
    }


    public JButton textButton(String text, double weightx, double weighty, int gridx, int gridy, int gridwidth, int gridheight) {

    
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.gridheight = gridheight;
        gbc.fill = GridBagConstraints.BOTH;


        JButton button = new JButton(text);
        panel.add(button, gbc);
        panel.revalidate();
        panel.repaint();
        return button;
    }
}
java swing jbutton gridbaglayout
1个回答
0
投票

您正在 JFrame 上设置布局管理器,但您正在将按钮添加到 JPanel 中。不需要 JPanel 介入。

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

public class Gui extends JFrame {

    public static void main(String[] args){
        Gui gui = new Gui("Hello World");
        gui.setVisible(true);
    }

    public Gui( String buttonText ) {
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Conlang Translator");

        this.setLayout(new BorderLayout());
        this.add(new JButton(buttonText), BorderLayout.CENTER);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.