Java:如何向框架添加按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20601505/
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 03:02:57  来源:igfitidea点击:

Java: How to add a button to a frame?

javabluej

提问by user3105629

I try to just use a add.method to add a button to a frame. But only the frame pops up. I don't see any buttons.

我尝试仅使用 add.method 将按钮添加到框架中。但只有框架弹出。我没有看到任何按钮。

import javax.swing.*;
public class okd {
    public static void main() {
        JFrame frame = new JFrame();
        JButton b1 = new JButton();
        frame.setSize(500,500);
        frame.add(b1);
        b1.setSize(400,400);
        b1.setVisible(true);
        frame.setVisible(true);
    }
}

采纳答案by PakkuDon

Your button has been added to the frame. You'll notice a difference if you remove your frame.add()line. The 'problem' lies with the following.

您的按钮已添加到框架中。如果您删除frame.add()线路,您会发现有所不同。“问题”在于以下几点。

  • You haven't specified a layout resulting in your frame using the default BorderLayout manager.
  • You haven't specified a constraint in frame.add(). Because of this the component has been added to whatever the default position is for the layout which is BorderLayout.CENTER. Components added to the center take up the much space as possible hence why your button is filling the entire frame.
  • 您尚未使用默认的 BorderLayout 管理器指定导致您的框架的布局。
  • 您尚未在frame.add(). 因此,该组件已添加到布局的任何默认位置,即BorderLayout.CENTER. 添加到中心的组件会尽可能多地占用空间,因此您的按钮会填充整个框架。

Here's some tutorials on layout managers.You might want to have a read through these at some point.

这里有一些关于布局管理器的教程您可能希望在某个时候通读这些内容。

回答by ChiefTwoPencils

There is a button there. Add some text to it and it will magically appear.

那里有一个按钮。添加一些文字,它会神奇地出现。

public static void main(String[] args){
    JFrame frame = new JFrame();
    JButton b1 = new JButton();
    frame.setSize(500,500);     
    b1.setSize(400,400);
    b1.setVisible(true);
    b1.setText("HelloWorld");
    frame.add(b1);
    frame.setVisible(true);
}//SSCCE1

回答by Joel eldo

To remove the Large appearance of the button, You need to add a layout Manager to the Code Like this:

要删除按钮的大外观,您需要在代码中添加一个布局管理器,如下所示:

import javax.swing.*;
import java.awt.*;
public static void main(String[] args)
{
    JFrame frame = new JFrame();
    JButton b1 = new JButton();
    frame.setSize(500,500); 
    b1.setVisible(true);
    b1.setText("HelloWorld");
    frame.setLayout(new FlowLayout());
    frame.add(b1);
    frame.setVisible(true);
}