The button takes up the whole screen, and I try using setSize()
but that doesn't appear to be doing anything. Here's my code so far:
JButton start = new JButton("PLAY");
start.setSize(new Dimension(100, 100));
myFrame.add(start);
The button takes up the whole screen, and I try using setSize()
but that doesn't appear to be doing anything. 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. Thats why single component will takes full screen. So add a suitable Layout Manager to JFrame
.
For details, go through, How to Use Various Layout Managers.
you can try using GridBagLayout
to set it's size within a Container
.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import 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);
}
}