PDA

View Full Version : Java Swing Interface Quirk



Yeldarb
January 5th, 2007, 12:23 AM
Ok, so I'm writing a program with a GUI for the first time.. but I'm kind of a perfectionist so this is bugging me:


Frame root = new JFrame();

JPanel input_screen;
JPanel wait_screen;
JPanel result_screen;

JTextArea input;
JTextArea solution_box;
JScrollPane scroll;

...

input_screen = new JPanel();

// Create the screen where they enter the puzzle
Box box = Box.createVerticalBox();

JLabel puzzleText = new JLabel("Puzzle:");
box.add(puzzleText);

input = new JTextArea(5, 5);
box.add(input);

JButton solve = new JButton("Solve");
solve.setActionCommand("submit");
box.add(solve);

solve.addActionListener(this);

input_screen.add(box);


The problem is that when I type in the JTextArea, the JLabel and JButton above and below it move with the text. How can I set them to be in fixed positions? I tried containing the JTextArea in its own JPanel.. but it didn't fix it.

kirupa
January 5th, 2007, 02:21 AM
You need to use a layout manager to handle positioning of all of your controls. My favorite is GridLayout, and you can find out more about it here: http://java.sun.com/docs/books/tutorial/uiswing/layout/grid.html (this link also contains info on other layout managers on the left nav)

:)

Yeldarb
January 5th, 2007, 02:53 AM
Thanks Kirupa, just what I was looking for :)

BorderLayout ended up working best in this instance :D

Tchuki
January 9th, 2007, 09:17 PM
You can also specifiy exact positioning just incase you or anyone else is interested.



setLayout(null);

objectName.setBounds(left, top, width, height);

The layout managers are more ideal, but for small GUI applets I sometimes use exact positioning.