Reputation: 63
I've researched the ways to change the size of a jbutton to be displayed on a JFrame.
I am trying both the button.setSize(200,200) and button.setPreferredSize(new Dimension(200,200)), but it does not change. Here's the code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Index extends JFrame{
private String title = "This is the motherfucking title";
Dimension dim = new Dimension(500,500);
public Index(){
this.setResizable(false);
this.setTitle(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(dim);
this.getContentPane().setBackground(Color.BLACK);
JButton button = new JButton("Button");
button.setSize(200,200);
this.add(button);
}
public static void main(String args[]){
Index ih = new Index();
ih.setVisible(true);
}
}
Here's the result: https://i.sstatic.net/gbsF8.png
What am I doing wrong?
Upvotes: 2
Views: 7430
Reputation: 1638
try this:
JButton button = new JButton("Button");
button.setSize(200,200);
getContentPane().setLayout(null);
getContentPane().add(button);
setVisible(true);
inside your constructor.
Upvotes: 1
Reputation: 324137
this.add(button);
You are adding the button to the content pane of the frame. By default the content uses a BorderLayout
and the component is added to the CENTER
. Any component added to the CENTER
will automatically get the extra space available in the frame. Since you set the size of the frame to (500, 500) there is lots of space available.
As a general rule you should NOT attempt to set the preferred size
of a component, since only the component know how big it should be in order to paint itself properly. So your basic code should be:
JButton button = new JButton("...");
frame.add(button);
frame.pack();
frame.setVisible(true);
Now the button will be at its preferred size. However, the button will change size if you resize the frame. If you don't want this behaviour, then you need to use a different Layout Manager.
Upvotes: 1
Reputation: 18068
Use SwingUtilities.invokeLater();
create your Index()
inside it, then call setVisible(true);
at the end of constructor. At the same time remeber that by default JFrame
uses BorderLayout
.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Index();
}
});
Upvotes: 0