Java – the best layout / nested layout for this structure

I'm new to swing. I'm trying to create an interface, such as:

——————————The text text of the information text 124124 124 124 124 124 124 124 124 124 124 124 124 124 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| button | button | button | 2 | 5 | 6 | 4 | button —–

Our idea is that all buttons are expanded in their "cells", so I have read the nested GridLayout, but I have a problem thinking about how to implement it Any suggestions on how to nest layouts or better methods?

Solution

Gridbaglayout will be the best solution for the complexity of code readability Since this result is best suited for gridbaglayout, just know how to solve the same constraint: -)

import java.awt.*;
import javax.swing.*;

public class GridBagLayoutExample {

    private GridBagConstraints gbc;
    private JButton[] buttons;

    public GridBagLayoutExample() {
        buttons = new JButton[7];
        gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
    }

    private void displayGUI() {
        JFrame frame = new JFrame("GridBagLayout Example");
        frame.setDefaultCloSEOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel(new GridBagLayout());
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(Integer.toString(i + 1));          
        }
        JLabel informationLabel = new JLabel("Information Text",JLabel.CENTER);
        addComp(contentPane,informationLabel,1.0,0.20,4,1);
        addComp(contentPane,buttons[0],1,0.25,0.60,3);
        JPasswordField passwordField = new JPasswordField(10);
        addComp(contentPane,passwordField,0.50,2,buttons[6],1);
        JTextField tField = new JTextField(10);
        addComp(contentPane,tField,3,buttons[2],3);
        addComp(contentPane,buttons[1],buttons[4],buttons[5],buttons[3],1);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void addComp(JPanel panel,JComponent comp,int x,int y,double wx,double wy,int gw,int gh) {
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = wx;
        gbc.weighty = wy;
        gbc.gridwidth = gw;
        gbc.gridheight = gh;

        panel.add(comp,gbc);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new GridBagLayoutExample().displayGUI();
            }
        };
        EventQueue.invokelater(runnable);
    }
}

OUTPUT:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>