JPanel和JButton,无法说明如何布局2个简单按钮 [英] JPanel and JButton, cannot figure how to layout 2 simple buttons
本文介绍了JPanel和JButton,无法说明如何布局2个简单按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从JPanel开始,我试图将2个简单的按钮放在框架上,我能够放置按钮,但不能将它们定位,这是我的代码:
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);
这是我想要的草图:
推荐答案
查找布局填充和边框以解决此问题.
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);
}
}
这篇关于JPanel和JButton,无法说明如何布局2个简单按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文