Java 如何设置按钮的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2536873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:02:20  来源:igfitidea点击:

How can I set size of a button?

javauser-interfaceswingbuttonsize

提问by Roman

I put my buttons in a JPane with GridLayout. Then I put JPanel into another JPanel with BoxLayout.Y_AXIS. I want buttons in the GridLayout to be square. I use tmp.setSize(30,30) and it does not work. I also try to use new GridLayout(X, Y, 4, 4)but I cannot figure out what X and Y are. So, what is the correct way to do this stuff?

我将按钮放在带有 GridLayout 的 JPane 中。然后我将 JPanel 放入另一个带有 BoxLayout.Y_AXIS 的 JPanel。我希望 GridLayout 中的按钮是方形的。我使用 tmp.setSize(30,30) 但它不起作用。我也尝试使用,new GridLayout(X, Y, 4, 4)但我无法弄清楚 X 和 Y 是什么。那么,做这些事情的正确方法是什么?

ADDED:

添加:

I still cannot solve the problem. Here is the code of what I am trying to do:

我仍然无法解决问题。这是我正在尝试做的代码:

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

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel();
        firstPanel.setLayout(new GridLayout(4, 4));
        JButton btn;
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                btn = new JButton();
                btn.setPreferredSize(new Dimension(100, 100));
                firstPanel.add(btn);
            }
        }

        JPanel secondPanel = new JPanel();
        secondPanel.setLayout(new GridLayout(5, 13));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                btn = new JButton();
                btn.setPreferredSize(new Dimension(40, 40));
                secondPanel.add(btn);
            }
        }

        mainPanel.add(firstPanel);
        mainPanel.add(secondPanel);
        frame.add(mainPanel);

        frame.setSize(400,600);
        frame.setVisible(true);
    }
}

The problem is that Java tries to make width of the firstPaneland secondPanelequal! Moreover, Java tries to to fill all height of the window. How can I remove this behavior?

问题是Java试图使宽度firstPanelsecondPanel平等!此外,Java 尝试填充窗口的所有高度。我怎样才能消除这种行为?

采纳答案by Kris

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

以下代码可以满足您的要求。只需确保分配足够的空间,以便按钮上的文本可见

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

X 和 Y(GridLayout 构造函数的两个第一个参数)分别指定网格中的行数和列数。如果您希望该值不受限制,您可以将其中之一保留为 0。

Edit

编辑

I've modified the provided code and I believe it now conforms to what is desired:

我已经修改了提供的代码,我相信它现在符合所需的内容:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

基本上我现在设置面板的首选尺寸和框架的最小尺寸。

回答by Jonas

Try with setPreferredSizeinstead of setSize.

尝试使用setPreferredSize而不是setSize.

UPDATE:GridLayouttake up all space in its container, and BoxLayoutseams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.

更新:GridLayout占用其容器中的所有空间,并BoxLayout接缝以占用其容器中的所有宽度,所以我添加了一些不可见的胶水面板,当用户拉伸窗口时只占用空间。我只是水平地而不是垂直地完成了这个,但是如果你愿意,你可以用同样的方式实现它。

Since GridLayoutmake all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.

由于GridLayout使所有单元格的大小相同,因此它们是否具有指定的大小并不重要。你必须为它的容器指定一个大小,就像我所做的那样。

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

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel(new GridLayout(4, 4));
        firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                firstPanel.add(new JButton());
            }
        }

        JPanel firstGluePanel = new JPanel(new BorderLayout());
        firstGluePanel.add(firstPanel, BorderLayout.WEST);
        firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        JPanel secondPanel = new JPanel(new GridLayout(13, 5));
        secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                secondPanel.add(new JButton());
            }
        }

        JPanel secondGluePanel = new JPanel(new BorderLayout());
        secondGluePanel.add(secondPanel, BorderLayout.WEST);
        secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        mainPanel.add(firstGluePanel);
        mainPanel.add(secondGluePanel);
        frame.getContentPane().add(mainPanel);

        //frame.setSize(400,600);
        frame.pack();
        frame.setVisible(true);
    }
}

回答by John

GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.

GridLayout 通常不是按钮的最佳选择,尽管它可能适用于您的应用程序。一个很好的参考是关于使用布局管理器的教程。如果您查看 GridLayout 示例,您会发现按钮看起来有点傻——太大了。

A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommendthat GroupLayout or GridBag layout are better than GridLayout when hand-coding.)

更好的主意可能是为您的按钮使用 FlowLayout,或者如果您确切地知道自己想要什么,也许是 GroupLayout。(Sun/Oracle建议手动编码时 GroupLayout 或 GridBag 布局比 GridLayout 更好。)

回答by Tanvir Rahman

This is how I did it.

我就是这样做的。

            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("SAP Multiple Entries");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(10,10,10,10));
            frame.setLayout(new FlowLayout());
            frame.setSize(512, 512);
            JButton button = new JButton("Select File");
            button.setPreferredSize(new Dimension(256, 256));
            panel.add(button);

            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();

                        keep = selectedFile.getAbsolutePath();


                       // System.out.println(keep);
                        //out.println(file.flag); 
                       if(file.flag==true) {
                           JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
                       }
                       else{
                           JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
                       }
                    }
                }
            });
            frame.add(button);
            frame.pack();
            frame.setVisible(true);