如何在GridLayout中调整JComponents的大小? [英] How do I resize JComponents in GridLayout?

查看:48
本文介绍了如何在GridLayout中调整JComponents的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java编程的新手.您能为我的第一个应用程序(一个简单的计算器)的布局提供帮助吗?这是我写的代码:

  import javax.swing.*;导入java.awt.*;导入java.awt.event.*;InputPad类扩展JFrame {私人JLabel statusLabel;私有JTextArea expTextArea;InputPad(){prepareGUI();}私人无效prepareGUI(){JFrame mainFrame = new JFrame("My Calculator");mainFrame.setSize(450,450);mainFrame.setLayout(new GridLayout(3,2));mainFrame.addWindowListener(new WindowAdapter(){公共无效windowClosing(WindowEvent windowEvent){System.exit(0);}});JLabel headerLabel = new JLabel(在此处放置表达式:",JLabel.CENTER);statusLabel =新的JLabel(",JLabel.CENTER);expTextArea =新的JTextArea("1+(2 ^ 3 * 4)");//数字面板JPanel digitPanel =新的JPanel();GroupLayout layoutDigits = new GroupLayout(digitPanel);digitPanel.setLayout(layoutDigits);layoutDigits.setAutoCreateGaps(true);layoutDigits.setAutoCreateContainerGaps(true);//操作员面板JPanel operatorPanel =新的JPanel();GroupLayout layoutOperators = new GroupLayout(operatorPanel);operatorPanel.setLayout(layoutOperators);layoutOperators.setAutoCreateGaps(true);layoutOperators.setAutoCreateContainerGaps(true);JButton [] numButtons =新的JButton [10];我对于(i = 0; i< 10; i ++){numButtons [i] =新的JButton(Integer.toString(i));numButtons [i] .addActionListener(e-> {//           去做});}JButton bEquals =新的JButton("=");bEquals.addActionListener(e-> {//           去做});JButton bPlus =新的JButton("+");bPlus.addActionListener(e-> {//           去做});JButton bMinus =新的JButton(-");bMinus.addActionListener(e-> {//           去做});JButton bMultiply =新的JButton("*");bMultiply.addActionListener(e-> {//           去做});JButton bDivide =新的JButton("/");bDivide.addActionListener(e-> {//           去做});JButton bLeftParenthesis =新的JButton((");bLeftParenthesis.addActionListener(e-> {//           去做});JButton bRightParenthesis = new JButton()");bRightParenthesis.addActionListener(e-> {//           去做});JButton bPower =新的JButton("^");bPower.addActionListener(e-> {//           去做});JButton bDel =新的JButton(←");bDel.addActionListener(e-> {//           去做});layoutDigits.setHorizo​​ntalGroup(layoutDigits.createSequentialGroup().addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(numButtons [7]).addComponent(numButtons [4]).addComponent(numButtons [1]).addComponent(numButtons [0])).addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(numButtons [8]).addComponent(numButtons [5]).addComponent(numButtons [2]).addComponent(bEquals)).addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(numButtons [9]).addComponent(numButtons [6]).addComponent(numButtons [3])));layoutDigits.setVerticalGroup(layoutDigits.createSequentialGroup().addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(numButtons [7]).addComponent(numButtons [8]).addComponent(numButtons [9])).addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(numButtons [4]).addComponent(numButtons [5]).addComponent(numButtons [6])).addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(numButtons [1]).addComponent(numButtons [2]).addComponent(numButtons [3])).addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(numButtons [0]).addComponent(bEquals)));layoutOperators.setHorizo​​ntalGroup(layoutOperators.createSequentialGroup().addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(bPlus).addComponent(bMinus).addComponent(bLeftParenthesis).addComponent(bPower)).addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(bMultiply).addComponent(bDivide).addComponent(bRightParenthesis).addComponent(bDel)));layoutOperators.setVerticalGroup(layoutOperators.createSequentialGroup().addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(bPlus).addComponent(bMultiply)).addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(bMinus).addComponent(bDivide)).addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(bLeftParenthesis).addComponent(bRightParenthesis)).addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(bPower).addComponent(bDel)));mainFrame.add(headerLabel);mainFrame.add(expTextArea);mainFrame.add(digitPanel);mainFrame.add(operatorPanel);mainFrame.add(statusLabel);mainFrame.setVisible(true);}} 

我为我的JFrame尝试了GridLayout,但是除了主JFrame外,我无法调整JComponent的大小.甚至我不能在GridLayout的一个单元中并排放置两个JPanel,也不能将JLabel扩展到GridLayout的两个单元.

这就是我得到的:

这就是我想要的:

解决方案

让我们从使用


请注意:

在发布代码之前,请注意以下提示:

  1. 您要扩展 JFrame ,同时创建一个 JFrame 对象,因此不建议这样做,请删除其中一个对象,在这种情况下在使用对象时,这是建议做的事情,只需从类中删除 extends JFrame .如果您确实需要扩展某些内容,请不要扩展 JFrame ,而要扩展 JPanel .

  2. 像在 main()方法中所做的一样,将您的程序放入EDT中

  3. 不要使用 System.exit(0); ,而是调用 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE),如上面的代码


现在是代码

  import java.awt.BorderLayout;导入java.awt.GridBagConstraints;导入java.awt.GridBagLayout;导入java.awt.GridLayout;导入java.awt.Insets;导入javax.swing.BoxLayout;导入javax.swing.JButton;导入javax.swing.JFrame;导入javax.swing.JLabel;导入javax.swing.JPanel;导入javax.swing.JTextArea;导入javax.swing.SwingUtilities;公共类CalculatorExample {私有JFrame框架;私有JTextArea区域;私有JButton [] [] digitsButtons,symbolsButtons;私有String [] [] digitsText = {{"7","8","9"},{"4","5","6"},{"1","; 2","3"},{"0","="}}};//看起来很奇怪,但这会使按钮的添加更加容易private String [] [] symbolText = {{"+","*"},{-","/"},{(",)"},{"^",←"}};私人JPanel buttonPane,areaAndResultsPane,digitsPane,symbolsPane;私人JLabel标签;公共静态void main(String [] args){SwingUtilities.invokeLater(new Runnable(){@Override公共无效run(){新的CalculatorExample().createAndShowGui();}});}公共无效createAndShowGui(){frame = new JFrame("Calculator Example");区域=新的JTextArea();area.setRows(5);area.setColumns(20);label = new JLabel("Results go here");digitsButtons =新的JButton [4] [3];symbolButtons =新的JButton [4] [2];areaAndResultsPane =新的JPanel();areaAndResultsPane.setLayout(new BoxLayout(areaAndResultsPane,BoxLayout.PAGE_AXIS));buttonPane =新的JPanel();buttonPane.setLayout(new GridLayout(1、2、10、10));digitsPane =新的JPanel();digitsPane.setLayout(new GridBagLayout());symbolPane =新的JPanel();symbolPane.setLayout(new GridLayout(4,2));GridBagConstraints c =新的GridBagConstraints();for(int i = 0; i< digitsText.length; i ++){for(int j = 0; j< digitsText [i] .length; j ++){digitsButtons [i] [j] =新的JButton(digitsText [i] [j]);}}for(int i = 0; i< SymbolsText.length; i ++){for(int j = 0; j< symbolsText [i] .length; j ++){symbolButtons [i] [j] =新的JButton(symbolsText [i] [j]);}}areaAndResultsPane.add(area);areaAndResultsPane.add(label);boolean shouldBreak = false;for(int i = 0; i< digitsButtons.length; i ++){for(int j = 0; j< digitsButtons [i] .length; j ++){c.gridx = j;c.gridy = i;c.fill = GridBagConstraints.HORIZONTAL;c.weightx = 0.5;如果(i == 3){如果(j == 1){c.gridwidth = 2;//这使得"="按钮更大shouldBreak = true;}}digitsPane.add(digitsButtons [i] [j],c);如果(应该打破){休息;}}}for(int i = 0; i< SymbolsButtons.length; i ++){for(int j = 0; j< symbolsButtons [i] .length; j ++){symbolPane.add(symbolsButtons [i] [j]);}}frame.add(areaAndResultsPane,BorderLayout.NORTH);buttonPane.add(digitsPane);buttonPane.add(symbolsPane);frame.add(buttonsPane,BorderLayout.CENTER);frame.pack();frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}} 

这是嵌套 JPanels 的工作,每个布局都有不同的布局,希望它可以帮助您从此处继续.

I'm new to Java programming. Can you help me with the layout of my first application (which is a simple calculator) please? Here's the code I wrote:

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

class InputPad extends JFrame {

    private JLabel statusLabel;
    private JTextArea expTextArea;

    InputPad() {
        prepareGUI();
    }

    private void prepareGUI(){
        JFrame mainFrame = new JFrame("My Calculator");
        mainFrame.setSize(450,450);
        mainFrame.setLayout(new GridLayout(3,2));
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
            }
        });

        JLabel headerLabel = new JLabel("Put your expression here:", JLabel.CENTER);
        statusLabel = new JLabel("",JLabel.CENTER);
        expTextArea = new JTextArea("1+(2^3*4)");

        //Digits Panel
        JPanel digitPanel = new JPanel();
        GroupLayout layoutDigits = new GroupLayout(digitPanel);
        digitPanel.setLayout(layoutDigits);
        layoutDigits.setAutoCreateGaps(true);
        layoutDigits.setAutoCreateContainerGaps(true);

        //Operators Panel
        JPanel operatorPanel = new JPanel();
        GroupLayout layoutOperators = new GroupLayout(operatorPanel);
        operatorPanel.setLayout(layoutOperators);
        layoutOperators.setAutoCreateGaps(true);
        layoutOperators.setAutoCreateContainerGaps(true);


        JButton[] numButtons= new JButton[10];

        int i;
        for (i=0;i<10;i++){
            numButtons[i] = new JButton(Integer.toString(i));
            numButtons[i].addActionListener(e -> {
//            TODO
            });
        }

        JButton bEquals = new JButton("=");
        bEquals.addActionListener(e -> {
//            TODO
        });

        JButton bPlus = new JButton("+");
        bPlus.addActionListener(e -> {
//            TODO
        });
        JButton bMinus = new JButton("-");
        bMinus.addActionListener(e -> {
//            TODO
        });
        JButton bMultiply = new JButton("*");
        bMultiply.addActionListener(e -> {
//            TODO
        });
        JButton bDivide = new JButton("/");
        bDivide.addActionListener(e -> {
//            TODO
        });
        JButton bLeftParenthesis = new JButton("(");
        bLeftParenthesis.addActionListener(e -> {
//            TODO
        });
        JButton bRightParenthesis = new JButton(")");
        bRightParenthesis.addActionListener(e -> {
//            TODO
        });
        JButton bPower = new JButton("^");
        bPower.addActionListener(e -> {
//            TODO
        });
        JButton bDel = new JButton("←");
        bDel.addActionListener(e -> {
//            TODO
        });


        layoutDigits.setHorizontalGroup(
                layoutDigits.createSequentialGroup()
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(numButtons[7])
                                .addComponent(numButtons[4])
                                .addComponent(numButtons[1])
                                .addComponent(numButtons[0]))
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(numButtons[8])
                                .addComponent(numButtons[5])
                                .addComponent(numButtons[2])
                                .addComponent(bEquals))
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(numButtons[9])
                                .addComponent(numButtons[6])
                                .addComponent(numButtons[3]))
        );
        layoutDigits.setVerticalGroup(
                layoutDigits.createSequentialGroup()
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(numButtons[7])
                                .addComponent(numButtons[8])
                                .addComponent(numButtons[9]))
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(numButtons[4])
                                .addComponent(numButtons[5])
                                .addComponent(numButtons[6]))
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(numButtons[1])
                                .addComponent(numButtons[2])
                                .addComponent(numButtons[3]))
                        .addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(numButtons[0])
                                .addComponent(bEquals))
        );

        layoutOperators.setHorizontalGroup(
                layoutOperators.createSequentialGroup()
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(bPlus)
                                .addComponent(bMinus)
                                .addComponent(bLeftParenthesis)
                                .addComponent(bPower))
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(bMultiply)
                                .addComponent(bDivide)
                                .addComponent(bRightParenthesis)
                                .addComponent(bDel))
        );
        layoutOperators.setVerticalGroup(
                layoutOperators.createSequentialGroup()
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(bPlus)
                                .addComponent(bMultiply))
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(bMinus)
                                .addComponent(bDivide))
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(bLeftParenthesis)
                                .addComponent(bRightParenthesis))
                        .addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(bPower)
                                .addComponent(bDel))
        );


        mainFrame.add(headerLabel);
        mainFrame.add(expTextArea);
        mainFrame.add(digitPanel);
        mainFrame.add(operatorPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

}

I tried the GridLayout for my JFrame, but I couldn't resize and of my JComponent except the main JFrame. Even I can't place two JPanels (side by side) in one cell of the GridLayout or expand a JLabel to two cells of the GridLayout.

This is what I got:

And here's what I want:

解决方案

Let's start from the use of Layout Managers, from the link on the part of GridLayout

GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns

So, this isn't what you want, but if you read the GridBagLayout part it says:

GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.

We can combine both of them, along with a BoxLayout and you will get a similar output to what you're trying to achieve:


PLEASE NOTE:

Before posting the code, take note of the following tips:

  1. You're extending JFrame and at the same time you're creating a JFrame object, this is discouraged, remove one of them, in this case as you're using the object and this is the recommended thing to do, simply remove the extends JFrame from your class. If you really need to extend something, don't extend JFrame but a JPanel instead.

  2. Place your program inside the EDT, as I did in the main() method

  3. Don't use System.exit(0); instead call setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) as shown in the above code


And now the code

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class CalculatorExample {
    private JFrame frame;
    private JTextArea area;
    private JButton[][] digitsButtons, symbolsButtons;
    private String[][] digitsText = {{"7", "8", "9"}, {"4", "5", "6"}, {"1", "2", "3"}, {"0", "="}}; //Looks strange but this will make the button adding easier
    private String[][] symbolsText = {{"+", "*"}, {"-", "/"}, {"(", ")"}, {"^", "←"}};
    private JPanel buttonsPane, areaAndResultsPane, digitsPane, symbolsPane;
    private JLabel label;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CalculatorExample().createAndShowGui();
            }
        });
    }
    
    public void createAndShowGui() {
        frame = new JFrame("Calculator Example");
        area = new JTextArea();
        area.setRows(5);
        area.setColumns(20);
        label = new JLabel("Results go here");
        digitsButtons = new JButton [4][3];
        symbolsButtons= new JButton [4][2];
        areaAndResultsPane = new JPanel();
        areaAndResultsPane.setLayout(new BoxLayout(areaAndResultsPane, BoxLayout.PAGE_AXIS));
        
        buttonsPane = new JPanel();
        buttonsPane.setLayout(new GridLayout(1, 2, 10, 10));
        
        digitsPane = new JPanel();
        digitsPane.setLayout(new GridBagLayout());
        
        symbolsPane = new JPanel();
        symbolsPane.setLayout(new GridLayout(4, 2));
        
        GridBagConstraints c = new GridBagConstraints();
        
        for (int i = 0; i < digitsText.length; i++) {
            for (int j = 0; j < digitsText[i].length; j++) {
                digitsButtons[i][j] = new JButton(digitsText[i][j]);
            }
        }
        
        for (int i = 0; i < symbolsText.length; i++) {
            for (int j = 0; j < symbolsText[i].length; j++) {
                symbolsButtons[i][j] = new JButton(symbolsText[i][j]);
            }
        }
        
        areaAndResultsPane.add(area);
        areaAndResultsPane.add(label);
        
        boolean shouldBreak = false;
        for (int i = 0; i < digitsButtons.length; i++) {
            for (int j = 0; j < digitsButtons[i].length; j++) {
                c.gridx = j;
                c.gridy = i;
                c.fill = GridBagConstraints.HORIZONTAL;
                c.weightx = 0.5;
                if (i == 3) {
                    if (j == 1) {
                        c.gridwidth = 2; //This makes the "=" button larger
                        shouldBreak = true;
                    }
                }
                digitsPane.add(digitsButtons[i][j], c);
                if (shouldBreak) {
                    break;
                }
            }
        }
        
        for (int i = 0; i < symbolsButtons.length; i++) {
            for (int j = 0; j < symbolsButtons[i].length; j++) {
                symbolsPane.add(symbolsButtons[i][j]);
            }
        }
        
        frame.add(areaAndResultsPane, BorderLayout.NORTH);
        buttonsPane.add(digitsPane);
        buttonsPane.add(symbolsPane);
        
        frame.add(buttonsPane, BorderLayout.CENTER);
        
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

This was done nesting JPanels, each with a different layout, I hope it helps you to continue from here.

这篇关于如何在GridLayout中调整JComponents的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆