0

如何更改下面的代码,改变框架大小后,框架上其他对象的大小也以相同的比例变化?

package application;

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

public class Program extends JFrame {

    private GroupLayout layout;
    private GroupLayout.Group groupX;
    private GroupLayout.Group groupY;

    public Program() {
        initialize();
    }

    private void initialize() {
        this.layout = new GroupLayout(this.getContentPane());
        this.groupX = this.layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        this.groupY = this.layout.createParallelGroup(GroupLayout.Alignment.LEADING);
    }

    public void addComponent(Component component, int x, int y) {

        getContentPane().setLayout(layout);

        groupX.addGroup(layout.createSequentialGroup()
                .addGap(x, x, x)
                .addComponent(component, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE));

        groupY.addGroup(layout.createSequentialGroup()
                .addGap(y, y, y)
                .addComponent(component, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE));    
        layout.setHorizontalGroup(groupX);
        layout.setVerticalGroup(groupY);
    }


    public static void main(String[] args) {
        Program jf = new Program();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setBounds(new Rectangle(0, 0, 250, 100));
        JButton p = new JButton("Click!!");
        jf.addComponent(p, 86, 20);
        jf.setVisible(true);
    }
}

如何更改下面的代码,改变框架大小后,框架上其他对象的大小也以相同的比例变化?

在此处输入图像描述

4

2 回答 2

1

我只想说,我不喜欢GroupLayout,但这就是我:D

在此处输入图像描述在此处输入图像描述

jButton1 = new javax.swing.JButton();

jButton1.setText("jButton1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGroup(layout.createSequentialGroup()
    .addGap(152, 152, 152)
    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
    .addGap(175, 175, 175))
);
layout.setVerticalGroup(
  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGroup(layout.createSequentialGroup()
    .addGap(137, 137, 137)
    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(94, 94, 94))
);
于 2013-04-04T07:05:41.317 回答
-1
Try using GridBagLayout which is easier.

private void initialize() {
    getContentPane().setLayout(new GridBagLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(new Rectangle(0, 0, 250, 100));
    JButton p = new JButton("Click!!");
    add(p, new GridBagConstraints(0, 0, 1, 1, 0.5, 0.5,
            GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
            new Insets(5, 5, 5, 5), 0, 0));
    setVisible(true);
}
于 2013-04-04T07:20:27.023 回答