如何向 JFrame 添加多个按钮?

How do I add multiple buttons to JFrame?

我需要一些非常基本的东西。 我试过这个:

import java.*;
import javax.swing.*;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class thisthing
{
    public static void main(String[]args)
    {
        boolean done = false;
        while (!done)
        {
            JFrame frame = new JFrame();

            JButton button= new JButton("Add Interest");
            frame.add(button);
            JButton button1 = new JButton("Other Button");
            frame.add(button1);

            class AddInterestListener implements ActionListener
            {
                public void actionPerformed(ActionEvent event)
                {
                    System.out.println("hello, I was pressed");
                }
            }
            class OtherButtonListener implements ActionListener
            {
                public void actionPerformed(ActionEvent event)
                {
                    System.out.println("The Other button was pressed");
                }
            }

            ActionListener listener = new AddInterestListener();
            button.addActionListener(listener);
            ActionListener listener1 = new OtherButtonListener();
            button1.addActionListener(listener1);

            frame.setSize(100, 100);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
}

但是当我 运行 我的电脑在一个 window 上制作两个按钮时遇到问题,所以它试图制作两个 windows。我真的不知道怎么形容,只能说是一团糟,我做错了什么。 最后我需要添加 15 个三角形按钮(著名的 AP peg 游戏项目)..那么有什么方法可以重新定位按钮并弄乱它们的大小吗?

您可以(推荐)使用另一个布局管理器(或自己定义一个)。或者(真的不推荐和极其丑陋的解决方案,但它有效):

frame.setLayout(null);

JButton button = new JButton("Hello world");
button.setBounds(20 , 20 , 100 , 30);
frame.add(button);

这会将按钮定位在给定位置并具有给定大小。或者你可以使用 button.setSize(100 , 30); button.setLocation(20 , 20);

注意:没有布局管理器,您可以自由定位您的组件,但默认情况下它们将具有边界(0、0、0、0),因此您始终必须设置位置和大小才能获得任何东西可见的。我只提供这个解决方案,因为你要求它,但你不应该使用它。