How do you set the position of button in grid layout?
My code:
public class Form {
public static void main(String[] args) {
Form form = new Form();
form.go();
}
public void go() {
开发者_JAVA百科 JFrame form = new JFrame();
GridLayout layout = new GridLayout(2,7);
Label nameLabel = new Label("Name");
form.setLayout(layout);
JTextField nameBox = new JTextField();
form.getContentPane().add(nameLabel);
form.getContentPane().add(nameBox);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setSize(500,500);
form.setVisible(true);
}
}
Now, how can I set this position of the JTextField so its 2,7 and not 1,2?
Try adding empty components into the positions before 2,7 , something like:
form.add(nameLabel);
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(nameBox);
seems that you better use GridBag layout,and use gridx gridy constraints to position your components...Here is a tutorial from java: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html As far as I know you cannot directly put components wherever you want using grid layout( @Paŭlo Ebermann has mentioned the same thing)
A GridLayout will always sort the components of the container in the order they are in the container. You can't put a component at a specific place, other than by inserting dummy components for all the places before.
You might want to try other layout managers. GridBagLayout can do this, but is quite more complicated to use.
精彩评论