JPanel和JButton,无法想象如何布局2个简单的按钮

时间:2013-10-06 16:31:09

标签: java swing jpanel jbutton layout-manager

我从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);

这是我想要的草图:

what i want

1 个答案:

答案 0 :(得分:4)

查看布局填充和边框以解决此问题。

enter image description here

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);
    }
}