问题
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