2

我从 JPanel 开始,我试图在一个框架上放置 2 个简单的按钮,我能够放置按钮但不能定位它们,这是我的代码:

JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

JButton but = new JButton("text");
JButton but2 = new JButton("list");

JPanel panel= new JPanel(new GridLayout(1, 2));
panel.setSize(100, 100);
panel.add(but);
panel.add(but2);    

frame.add(panel);
frame.setVisible(true);

这是我想要的草图:

我想要的是

4

1 回答 1

4

寻找布局填充和边框来解决这个问题。

在此处输入图像描述

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

class TwoButtonLayout {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                // adjust numbers to need..
                JPanel panel = new JPanel(new GridLayout(1, 2, 40, 40));
                // adjust numbers to need..
                panel.setBorder(new EmptyBorder(20,30,20,30));
                panel.setBackground(Color.WHITE);

                JButton but = new JButton("text");
                JButton but2 = new JButton("list");

                panel.add(but);
                panel.add(but2);

                JOptionPane.showMessageDialog(null, panel);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}
于 2013-10-06T16:56:30.247 回答