Java 如何对齐JPanels/JFrames中的元素?

Java 如何对齐JPanels/JFrames中的元素?,java,swing,jframe,jpanel,layout-manager,Java,Swing,Jframe,Jpanel,Layout Manager,我对在java中使用GUI是完全陌生的,所以我在弄清楚如何对齐所有需要对齐的内容时遇到了一些困难。我必须在我的JFrame中对齐(一个向左,一个向右)的面板和其中一个面板中的几个按钮,我需要在面板中居中。这是我的密码 package application; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; import java.nio.*; import java.util

我对在java中使用GUI是完全陌生的,所以我在弄清楚如何对齐所有需要对齐的内容时遇到了一些困难。我必须在我的JFrame中对齐(一个向左,一个向右)的面板和其中一个面板中的几个按钮,我需要在面板中居中。这是我的密码

package application;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.util.*;

public class Main extends JPanel 
{
    public static void main(String[] args)
    { 
        //set the ui to the native OS
        try
        { 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException 
        | UnsupportedLookAndFeelException e)                                   
        {
        }

        JFrame frame = new JFrame("Application Name");
        Menu menu = new Menu();
        JPanel iconPanel = new JPanel();
        final JPanel grid = new JPanel(new FlowLayout());
        JButton firewallButton = new JButton("Firewall");
        JButton networkButton = new JButton("Network");
        JButton printerButton = new JButton("Printer");

        int iconPanelSizeX;
        int iconPanelSizeY;
        int gridSizeX;
        int gridSizeY;
        int gridPosition;

        //frame setting
        frame.setSize(800, 600);
        frame.setMinimumSize(new Dimension(800, 600));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //add grid and iconPanel JPanels to the frame
        frame.add(iconPanel);
        iconPanel.add(firewallButton);
        iconPanel.add(networkButton);
        iconPanel.add(printerButton);
        frame.add(grid);        

        //iconPanel settings
        iconPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
        iconPanel.setBackground(Color.gray);
        iconPanel.setLayout(new FlowLayout());
        iconPanel.setSize(new Dimension(100, 600));
        iconPanel.setVisible(true);

        //grid setting
        grid.setBackground(Color.red);
        grid.setSize(new Dimension(700, 600));
        grid.setVisible(true);

        //this is for resizing components when the user resizes the window
        int counter = 0;
        while(counter == 0)
        {
            firewallButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            networkButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            printerButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            iconPanelSizeX = frame.getWidth() / 10;
            iconPanelSizeY = frame.getHeight();
            gridSizeX = (frame.getWidth() / 10) * 9;
            gridSizeY = frame.getHeight();
            iconPanel.setSize(new Dimension(iconPanelSizeX, iconPanelSizeY));
            grid.setSize(new Dimension(gridSizeX, gridSizeY));
        }
    }
}
如您所见,第二个JPanel(网格)没有与框架的右侧对齐,iconTray中的按钮也没有居中。我意识到这两个可能都是简单的布局修复,但我不知道从哪里开始

我必须在我的JFrame中对齐需要对齐的面板(一个在左边, 右边一个)和我需要的其中一个面板上的几个按钮 要在面板中居中。这是我的密码

package application;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.util.*;

public class Main extends JPanel 
{
    public static void main(String[] args)
    { 
        //set the ui to the native OS
        try
        { 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException 
        | UnsupportedLookAndFeelException e)                                   
        {
        }

        JFrame frame = new JFrame("Application Name");
        Menu menu = new Menu();
        JPanel iconPanel = new JPanel();
        final JPanel grid = new JPanel(new FlowLayout());
        JButton firewallButton = new JButton("Firewall");
        JButton networkButton = new JButton("Network");
        JButton printerButton = new JButton("Printer");

        int iconPanelSizeX;
        int iconPanelSizeY;
        int gridSizeX;
        int gridSizeY;
        int gridPosition;

        //frame setting
        frame.setSize(800, 600);
        frame.setMinimumSize(new Dimension(800, 600));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //add grid and iconPanel JPanels to the frame
        frame.add(iconPanel);
        iconPanel.add(firewallButton);
        iconPanel.add(networkButton);
        iconPanel.add(printerButton);
        frame.add(grid);        

        //iconPanel settings
        iconPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
        iconPanel.setBackground(Color.gray);
        iconPanel.setLayout(new FlowLayout());
        iconPanel.setSize(new Dimension(100, 600));
        iconPanel.setVisible(true);

        //grid setting
        grid.setBackground(Color.red);
        grid.setSize(new Dimension(700, 600));
        grid.setVisible(true);

        //this is for resizing components when the user resizes the window
        int counter = 0;
        while(counter == 0)
        {
            firewallButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            networkButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            printerButton.setSize(new Dimension(iconPanel.getWidth(), 50));
            iconPanelSizeX = frame.getWidth() / 10;
            iconPanelSizeY = frame.getHeight();
            gridSizeX = (frame.getWidth() / 10) * 9;
            gridSizeY = frame.getHeight();
            iconPanel.setSize(new Dimension(iconPanelSizeX, iconPanelSizeY));
            grid.setSize(new Dimension(gridSizeX, gridSizeY));
        }
    }
}
我意识到这两个可能都是简单的布局修复,但我没有 从哪里开始的线索

使用比实际使用的简单
FlowLayout
更复杂的布局。我建议你用

  • GridBagLayout
  • BoxLayout

检查以获得
JFrame
的简单拆分。您可以使用
GridLayout
和1行2列

frame.setLayout(new GridLayout(1,2,3,3)); //3,3 are gaps
frame.add(grid);
frame.add(iconPanel);
对于面板中的居中组件,可以使用
FlowLayout
,默认情况下,该布局设置在
JPanels

手动操作:

grid.setLayout(new FlowLayout()); //Centered components

grid.setLayout(new FlowLayout(FlowLayout.LEFT,3,3)); //Components aligned to left

grid.setLayout(new FlowLayout(FlowLayout.RIGHT,3,3)); //Components aligned to right
这就是它的样子:

此外,几乎没有观察到:

  • 不要为组件调用setXXXSize()方法

  • 尽量避免调用
    setSize()
    对于
    JFrame
    ,调用
    pack()取而代之

  • 调用
    setVisible(true)在代码末尾

您所有的庞大代码都可以“剥离”为:


我建议你花点时间仔细检查一下。这将帮助您熟悉标准API提供的布局管理器。它需要一些经验和艰苦的工作,以找出这些是正确的工具,以获得准确的外观你想要的。一旦您熟悉了标准API提供的内容,您还应该四处寻找提供其他选项的第三方Layout Manager API

如何垂直对齐按钮

此示例在框架的默认
边框布局的
西部
区域中使用垂直线:

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

/** @see http://stackoverflow.com/a/14927280/230513 */
public class Main {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }

    private static void display() throws HeadlessException {
        JFrame frame = new JFrame("Application Name");
        JButton firewallButton = new JButton("Firewall");
        JButton networkButton = new JButton("Network");
        JButton printerButton = new JButton("Printer");

        //iconPanel settings
        Box iconPanel = new Box(BoxLayout.Y_AXIS);
        iconPanel.add(firewallButton);
        iconPanel.add(networkButton);
        iconPanel.add(printerButton);
        iconPanel.setBackground(Color.gray);
        iconPanel.setVisible(true);
        frame.add(iconPanel, BorderLayout.WEST);

        //grid setting
        JPanel grid = new JPanel() {

            @Override
            // arbitrary placeholder size
            public Dimension getPreferredSize() {
                return new Dimension(320, 230);
            }
        };
        grid.setBackground(Color.red);
        frame.add(grid, BorderLayout.CENTER);

        //frame setting
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}


谢谢,这帮了大忙。实际上有一件事我忘了问,那就是如何垂直对齐按钮-我必须在以后添加一些。你必须使用其他布局管理器。对于非常基本的对齐方式,您可以使用
GridLayout
BoxLayout
,但对于更复杂的对齐方式,我建议使用
gridbadayout
migloayout
。只需在谷歌上搜索一下,也可以看到这个。