Skip to main content
GameDev.net gamedev.net
🔒 Locked

[Java] Getting buttons working.

Started by monp Sep 20, 2010 at 8:02 PM 4 replies 800+ views
Original Post
monp
monp
Currently my button shows up, but it fills my whole program. How can I fix this?
[source="java"]import javax.swing.*;public class Hello{	public static void main(String[] args)	{		JFrame frame = new JFrame("Hello, Java");		JLabel label = new JLabel("Hello. Java", JLabel.CENTER);		JButton button = new JButton("Ok");		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		frame.add(label);		frame.add(button);		frame.setSize(300,200);		frame.setVisible(true);	}}
dmatter
dmatter
It's all down to the layout manager you use. By default the content pane of the JFrame uses the BorderLayout and you specify which area of the border layout you want to add to, if you don't specify (and you're not) then it'll default to adding to the center. The center will always expand to fill all leftover space which, in this case, is all of it and explains why your button is so big.

You could change to, say, a FlowLayout and in fact JPanels use these by default so, what you could do, is add a JPanel to the JFrame and add your button to the JPanel. Or just give the JFrame a FlowLayout to use.

The decision as to which layout manager to use where entirely depends on how you want your GUI to look and behave.
monp
monp
What is Flowlayout?
monp
monp
I have changed my code to include the JPanel and it shows the button at the top but not the label centered anymore, and if I reverse the label and panel order it shows the label but no button.
[source="java"]import javax.swing.*;public class Hello{	public static void main(String[] args)	{		JFrame frame = new JFrame("Hello, Java");		JLabel label = new JLabel("Hello. Java", JLabel.CENTER);		JPanel panel = new JPanel();		panel.add(new JButton("OK"));		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		frame.add(label);		frame.add(panel);		frame.setSize(300,200);		frame.setVisible(true);	}}

Yeah my mind went blank for a moment then I googled it already.
monp
monp
Never mind I got it working it was much simpler than I was making it out to be.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.