简体   繁体   中英

How to make compact grid with resizable JButtons?

I am trying to reuse Swing SpringLayout compact grid functionality to make a compact grid of resizable JButtons using: http://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html

It works fine but SpringLayout can not resise JButtons so it is useless for me. Is there some other way to create a compact grid with resizable Jbuttons on it?

A: Use GridLayout, use GridBagLayout, write your own LayoutManager.
Q: How can I write my own LayoutManager?

please no, for Swing Guru like as @StanislavL isn't somehow complicated to wrote own LayoutManager , for rest of us is better to use MigLayout or GridBagLayout ,

You can use GridBagLayout for this. Here is a sample that shows two buttons - one maintains its width and the other one changes its width when the frame is resized.

Note the GridBagConstraints that tell the component how it should behave in the layout. The weight controls the resize behaviour. Further information can be found in the Java Tutorials .

package test;

import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;

public class LayoutResizeButtonTest extends JFrame {

    public static void main(String[] args) {

        LayoutResizeButtonTest app = new LayoutResizeButtonTest();

        app.setDefaultCloseOperation(EXIT_ON_CLOSE);
        app.setVisible(true);

    }

    LayoutResizeButtonTest() {

        this.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;

        this.add(new Button("Resizable"), c);

        c = new GridBagConstraints();
        c.weightx = 0.0;

        this.add(new Button("Not Resizable"));

        this.pack();

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM