JPanel and JButton, cannot figure how to layout 2 simple buttons

和自甴很熟 提交于 2020-01-04 05:26:35

问题


i am starting with JPanel and i am trying to put 2 simple buttons on a frame, i was able to put the buttons but not position them, here is my code:

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

and here is a sketch of what i want:


回答1:


Look to layout padding and borders to solve this.

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


来源:https://stackoverflow.com/questions/19211153/jpanel-and-jbutton-cannot-figure-how-to-layout-2-simple-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!