Java,GridBagLayout。如何将组件添加到其他组件

Java,GridBagLayout。如何将组件添加到其他组件,java,swing,layout-manager,gridbaglayout,Java,Swing,Layout Manager,Gridbaglayout,我正在学习JSwing,我发现了GridBagLayout 我正在尝试创建一个简单的计算器,我通过添加多个JPanel设置每个preferedSize来实现,但是当我调整窗口框架的大小时,面板也不会调整大小。 然后我发现了Gridbag的布局 但这是我得到的: import javax.swing.*; 导入java.awt.*; 公共类计算扩展JFrame{ 私有最终整数宽度=300; 私人最终内部高度=450; 公共计算(){ 设置尺寸(宽度、高度); JPanel mainPanel=新的

我正在学习JSwing,我发现了GridBagLayout

我正在尝试创建一个简单的计算器,我通过添加多个JPanel设置每个preferedSize来实现,但是当我调整窗口框架的大小时,面板也不会调整大小。 然后我发现了Gridbag的布局

但这是我得到的:

import javax.swing.*;
导入java.awt.*;
公共类计算扩展JFrame{
私有最终整数宽度=300;
私人最终内部高度=450;
公共计算(){
设置尺寸(宽度、高度);
JPanel mainPanel=新的JPanel();
setLayout(新的BorderLayout());
添加(createButtons(),BorderLayout.SOUTH);
添加(主面板);
}
私有JPanel createButtons(){
JPanel面板=新的JPanel();
GridBagLayout=新的GridBagLayout();
面板设置布局(布局);
GridBagConstraints g=新的GridBagConstraints();
g、 gridx=0;
g、 gridy=0;
对于(int i=0;i<9;i++){
面板.添加(新的按钮(“+i”),g);
g、 gridx++;
如果(g.gridx==3){
g、 gridx=0;
g、 gridy++;
}
}
返回面板;
}
公共静态void main(字符串…参数){
Calc Calc=新的Calc();
计算设置可见(真);
}
}

应该是这样的:

我试过:

  • 锚定。。。但它不起作用
  • 创建多个JPanel(一个带有GridLayout),但不起作用
如果你不想用勺子舀代码,没关系。。但是我应该从哪里开始呢

编辑: 我知道如何安排按钮。。。但我无法设置标题以填充所有x轴: 代码:

import javax.swing.*;
导入java.awt.*;
公共类ButtonPanel扩展了JPanel{
JPanel-top;
杰帕内尔左;
杰帕内尔权利;
私有类CButton扩展了JButton{
私人经营;
公共按钮(){
}
}
公共按钮面板(){
initComponent();
initLayout();
}
私有void initLayout(){
GridBagLayout=新的GridBagLayout();
这个.setLayout(布局);
layout.columnWeights=新的双[]{3,1};
layout.rowWeights=newdouble[]{1,1};
GridBagConstraints c=新的GridBagConstraints();
c、 gridx=0;
c、 gridy=0;
c、 fill=GridBagConstraints.BOTH;
c、 权重x=5;
添加(顶部,c);
c、 gridy++;
c、 权重=1;
添加(左,c);
c、 gridx++;
本条增补(右,c);
}
私有void initComponent(){
top=新的JPanel();
top.setLayout(新的GridLayout(1,3));
对于(int i=0;i<3;i++){
添加(新的JButton(“bbb”));
}
左=新JPanel();
左.setLayout(新的GridLayout(3,3));
对于(int i=0;i<9;i++){
添加(新的JButton(“+i”);
}
右=新JPanel();
右.setLayout(新的GridLayout(3,1));
对于(int i=0;i<3;i++){
JButton btn=新JButton(“aa”);
对。添加(btn);
}
}
公共静态void main(字符串[]args){
JFrame=新JFrame(“测试”);
frame.setLayout(新的BorderLayout());
frame.add(newbuttonpanel(),BorderLayout.SOUTH);
框架。设置尺寸(300450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


它应该是:

您可能可以在一个面板中完成所有操作,其中有些按钮跨越多个列

所以我给你一个不同的例子,用一个GridBagLayout来布局按钮,在这里你可以把你的按钮排列定义为一个值数组,检查它是否是你项目的一个很好的起点

package test;

import static test.Calculator.Buttons.*;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Calculator extends JPanel {
    //Here define all possible buttons with labels
    public enum Buttons {
        PERCENT("%"), CE("CE"), CLEAR("C"),
        ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), ZERO("0"),
        ADD("+"), SUB("-"), MULT("x"), DIV("/"), RESULT("="), DECPOINT(".");
        
        protected String text;
        
        Buttons(String txt) {
            this.text=txt;
        }
        
        public String getText() {
            return text;
        }
    };
    
    //This array contains your keypad layout, contiguous repeated elements will span across multiple columns (e.g. ZERO). 
    protected Buttons[][] keyPad = {
        {PERCENT, CE, CLEAR, DIV},
        {SEVEN, EIGHT, NINE, MULT},
        {FOUR, FIVE, SIX, ADD},
        {ONE, TWO, THREE, SUB},
        {ZERO, ZERO, DECPOINT, RESULT}
    };
    
    Map<JButton, Buttons> sourceMap=new HashMap<>();
    
    ActionListener padListener=new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            onKeyPadPressed(sourceMap.get(e.getSource()));
        }
    };
    
    public Calculator() {
        setLayout(new GridBagLayout());
        GridBagConstraints c=new GridBagConstraints();
        c.weightx=1.0;
        c.weighty=1.0;
        c.fill=GridBagConstraints.BOTH;
        
        for (int y=0;y<keyPad.length;y++) {
            for (int x=0;x<keyPad[y].length;) {
                Buttons b=keyPad[y][x];
                if (b==null) {
                    continue;
                }
                JButton btn=new JButton(b.getText());
                c.gridx=x;
                c.gridy=y;

                c.gridwidth=0;
                while(x<keyPad[y].length&&keyPad[y][x]==b) {
                    c.gridwidth++;
                    x++;
                }
                add(btn,c);
                
                sourceMap.put(btn,b);
                btn.addActionListener(padListener);
            }
        }
        
    }
    
    //Callback method, whenever a button is clicked you get the associated enum value here
    protected void onKeyPadPressed(Buttons b) {
        System.out.println("Pressed "+b);
        switch (b) {
//          case ZERO:
//          .... here your logic
        }
    }
    
    public static void main(String[] args) {
        JFrame frame=new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Calculator());
        frame.pack();
        frame.setVisible(true);
    }
}
封装测试;
导入静态测试。计算器。按钮。*;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.HashMap;
导入java.util.Map;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
公共类计算器扩展JPanel{
//这里定义所有可能的带有标签的按钮
公共枚举按钮{
百分比(“%”,CE(“CE”)、净空(“C”),
一(1)、二(2)、三(3)、四(4)、五(5)、六(6)、七(7)、八(8)、九(9)、零(0),
添加(“+”)、子(“-”)、多(“x”)、DIV(“/”)、结果(“=”)和depoint(“.”);
受保护的字符串文本;
按钮(字符串txt){
this.text=txt;
}
公共字符串getText(){
返回文本;
}
};
//此阵列包含键盘布局,连续重复元素将跨越多个列(例如零)。
受保护的按钮[]键盘={
{百分比,CE,清除,DIV},
{7,8,9,MULT},
{四,五,六,加上},
{1,2,3,SUB},
{ZERO,ZERO,DECPOINT,RESULT}
};
Map sourceMap=newhashmap();
ActionListener padListener=新建ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
onkeypad按下(sourceMap.get(e.getSource());
}
};
公共计算器(){
setLayout(新的GridBagLayout());
GridBagConstraints c=新的GridBagConstraints();
c、 权重x=1.0;
c、 权重y=1.0;
c、 fill=GridBagConstraints.BOTH;

对于(int y=0;y,您可能可以在一个面板中执行所有操作,其中有些按钮跨越多个列

所以我给你一个不同的例子,用一个GridBagLayout来布局按钮,在这里你可以把你的按钮排列定义为一个值数组,检查它是否是你项目的一个很好的起点

package test;

import static test.Calculator.Buttons.*;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Calculator extends JPanel {
    //Here define all possible buttons with labels
    public enum Buttons {
        PERCENT("%"), CE("CE"), CLEAR("C"),
        ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), ZERO("0"),
        ADD("+"), SUB("-"), MULT("x"), DIV("/"), RESULT("="), DECPOINT(".");
        
        protected String text;
        
        Buttons(String txt) {
            this.text=txt;
        }
        
        public String getText() {
            return text;
        }
    };
    
    //This array contains your keypad layout, contiguous repeated elements will span across multiple columns (e.g. ZERO). 
    protected Buttons[][] keyPad = {
        {PERCENT, CE, CLEAR, DIV},
        {SEVEN, EIGHT, NINE, MULT},
        {FOUR, FIVE, SIX, ADD},
        {ONE, TWO, THREE, SUB},
        {ZERO, ZERO, DECPOINT, RESULT}
    };
    
    Map<JButton, Buttons> sourceMap=new HashMap<>();
    
    ActionListener padListener=new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            onKeyPadPressed(sourceMap.get(e.getSource()));
        }
    };
    
    public Calculator() {
        setLayout(new GridBagLayout());
        GridBagConstraints c=new GridBagConstraints();
        c.weightx=1.0;
        c.weighty=1.0;
        c.fill=GridBagConstraints.BOTH;
        
        for (int y=0;y<keyPad.length;y++) {
            for (int x=0;x<keyPad[y].length;) {
                Buttons b=keyPad[y][x];
                if (b==null) {
                    continue;
                }
                JButton btn=new JButton(b.getText());
                c.gridx=x;
                c.gridy=y;

                c.gridwidth=0;
                while(x<keyPad[y].length&&keyPad[y][x]==b) {
                    c.gridwidth++;
                    x++;
                }
                add(btn,c);
                
                sourceMap.put(btn,b);
                btn.addActionListener(padListener);
            }
        }
        
    }
    
    //Callback method, whenever a button is clicked you get the associated enum value here
    protected void onKeyPadPressed(Buttons b) {
        System.out.println("Pressed "+b);
        switch (b) {
//          case ZERO:
//          .... here your logic
        }
    }
    
    public static void main(String[] args) {
        JFrame frame=new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Calculator());
        frame.pack();
        frame.setVisible(true);
    }
}
封装测试;
导入静态测试。计算器。按钮。*;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.HashMap;
导入java.util.Map;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
公共类计算器扩展JPanel{
package test;

import static test.Calculator.Buttons.*;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Calculator extends JPanel {
    //Here define all possible buttons with labels
    public enum Buttons {
        PERCENT("%"), CE("CE"), CLEAR("C"),
        ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), ZERO("0"),
        ADD("+"), SUB("-"), MULT("x"), DIV("/"), RESULT("="), DECPOINT(".");
        
        protected String text;
        
        Buttons(String txt) {
            this.text=txt;
        }
        
        public String getText() {
            return text;
        }
    };
    
    //This array contains your keypad layout, contiguous repeated elements will span across multiple columns (e.g. ZERO). 
    protected Buttons[][] keyPad = {
        {PERCENT, CE, CLEAR, DIV},
        {SEVEN, EIGHT, NINE, MULT},
        {FOUR, FIVE, SIX, ADD},
        {ONE, TWO, THREE, SUB},
        {ZERO, ZERO, DECPOINT, RESULT}
    };
    
    Map<JButton, Buttons> sourceMap=new HashMap<>();
    
    ActionListener padListener=new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            onKeyPadPressed(sourceMap.get(e.getSource()));
        }
    };
    
    public Calculator() {
        setLayout(new GridBagLayout());
        GridBagConstraints c=new GridBagConstraints();
        c.weightx=1.0;
        c.weighty=1.0;
        c.fill=GridBagConstraints.BOTH;
        
        for (int y=0;y<keyPad.length;y++) {
            for (int x=0;x<keyPad[y].length;) {
                Buttons b=keyPad[y][x];
                if (b==null) {
                    continue;
                }
                JButton btn=new JButton(b.getText());
                c.gridx=x;
                c.gridy=y;

                c.gridwidth=0;
                while(x<keyPad[y].length&&keyPad[y][x]==b) {
                    c.gridwidth++;
                    x++;
                }
                add(btn,c);
                
                sourceMap.put(btn,b);
                btn.addActionListener(padListener);
            }
        }
        
    }
    
    //Callback method, whenever a button is clicked you get the associated enum value here
    protected void onKeyPadPressed(Buttons b) {
        System.out.println("Pressed "+b);
        switch (b) {
//          case ZERO:
//          .... here your logic
        }
    }
    
    public static void main(String[] args) {
        JFrame frame=new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Calculator());
        frame.pack();
        frame.setVisible(true);
    }
}