How do you set the position of button in grid layout?

拟墨画扇 提交于 2019-12-24 00:28:50

问题


My code:

public class Form {
    public static void main(String[] args) {
        Form form = new Form();
        form.go();
    }

    public void go() {
        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?


回答1:


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);



回答2:


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)




回答3:


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.



来源:https://stackoverflow.com/questions/6906331/how-do-you-set-the-position-of-button-in-grid-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!