[英]How do I set the size of a JButton?
The button takes up the whole screen, and I try using setSize()
but that doesn't appear to be doing anything. 该按钮占据了整个屏幕,我尝试使用
setSize()
但这似乎没有任何作用。 Here's my code so far: 到目前为止,这是我的代码:
JButton start = new JButton("PLAY");
start.setSize(new Dimension(100, 100));
myFrame.add(start);
By default, JFrame
has BorderLayout
with CENTER
alignment. 默认情况下,
JFrame
具有BorderLayout
和CENTER
对齐。 Thats why single component will takes full screen. 这就是为什么单个组件需要全屏显示的原因。 So add a suitable Layout Manager to
JFrame
. 因此,向
JFrame
添加合适的布局管理器。
For details, go through, How to Use Various Layout Managers . 有关详细信息,请阅读如何使用各种布局管理器 。
you can try using GridBagLayout
to set it's size within a Container
. 您可以尝试使用
GridBagLayout
在Container
设置其大小。
import java.awt.GridBagConstraints;
导入java.awt.GridBagConstraints; import java.awt.GridBagLayout;
导入java.awt.GridBagLayout; import java.awt.Insets;
导入java.awt.Insets; import javax.swing.JButton;
导入javax.swing.JButton; import javax.swing.JFrame;
导入javax.swing.JFrame; import javax.swing.JPanel;
导入javax.swing.JPanel;
public class test extends JPanel{
private static final long serialVersionUID = 1L;
JButton b1, b2, b3, b4, b5;
GridBagConstraints g = new GridBagConstraints();
public test() {
setLayout(new GridBagLayout());
g.insets = new Insets(1, 1, 1, 1);
b1 = new JButton("Button 1");
g.gridx = 0;
g.gridy = 6;
g.gridwidth = 2;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b1, g);
b2 = new JButton("Button 2");
g.gridx = 0;
g.gridy = 0;
g.gridwidth = 3;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b2, g);
b3 = new JButton("Button 3");
g.gridx = 2;
g.gridy = 2;
g.gridwidth = 1;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b3, g);
b4 = new JButton("Button 4");
g.gridx = 6;
g.gridy = 0;
g.gridheight = 3;
g.gridwidth = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b4, g);
b5 = new JButton("Button 5");
g.gridx = 1;
g.gridy = 3;
g.gridheight = 1;
g.gridwidth = 2;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b5, g);
}
public static void main(String[] args) {
test t = new test();
JFrame frame = new JFrame("test");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(t);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.