简体   繁体   English

Java Swing面板布局

[英]Java Swing Panel layout

I am working on a Java project for college that involves us setting up a TCP Server and Client. 我正在为大学开发一个Java项目,涉及我们设置TCP服务器和客户端。 I have that part working and now to add more of a feel to my project I want to add a GUI. 我有这个部分工作,现在为我的项目添加更多的感觉我想添加一个GUI。

We have not begun learning about GUI's in Java yet. 我们还没有开始学习Java中的GUI。 However I want to try as I think it would be a useful exercise. 但是我想尝试,因为我认为这将是一个有用的练习。 I have a very basic GUI set up and the appropriate ActionListener set for the button. 我有一个非常基本的GUI设置和为该按钮设置的相应ActionListener。 My next problem is positioning my panels so they look neat and tidy on the Frame... 我的下一个问题是定位我的面板,使它们在框架上看起来整洁整洁......

At the moment I have all the components in one panel as seen below: 目前,我将所有组件放在一个面板中,如下所示:

public ClientGUI(){

    //Initialise Frame
    frame = new JFrame("TCP Client");

    //Initialise Panel 1 & Components
    p1 = new JPanel();

    //Set Layout
    p1.setLayout(new GridLayout(1,2));

    //Label 1 - For TextArea
    l1 = new JLabel("Chat Log");
    p1.add(l1);

    //TextArea - To display conversation
    t1 = new JTextArea(10,10);
    p1.add(t1);

    //Label 2 - For TextField
    l2 = new JLabel("Message");
    p1.add(l2);

    //Message Box - For user input
    t2 = new JTextField(10);
    p1.add(t2);

    //Button 1 - To send message
    b1 = new JButton("Send");
    p1.add(b1);

    //Add panels to frame
    frame.add(p1);

    //Frame properties...
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setVisible(true);

    //Add Event listener to button
    b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ev){
            //do something
            t1.setText(t2.getText());
        }
    });

I would love for it to look something like the rough wireframe below. 我希望它看起来像下面粗糙的线框。

期望的布局

I'd appreciate any feedback anyone might have! 我很感激任何人可能有任何反馈! Thanks very much. 非常感谢。

What you want is called the BoxLayout , which feeds UI elements in columns or rows. 你想要的是BoxLayout ,它以列或行的形式提供UI元素。 And then you can nest them one inside another, eg have one horizontal box layout panel as an element in another that is vertical (kind of like nested HTML tables). 然后你可以将它们嵌套在另一个中,例如将一个水平框布局面板作为另一个垂直的元素(有点像嵌套的HTML表格)。 So all of your elements would go in a top level vertical BoxLayout and the line that has JLabel2 and JTextField would be its own horizontal BoxLayout nested in the top level vertical layout. 所以你的所有元素都会进入顶层垂直BoxLayout,而拥有JLabel2和JTextField的行将是它自己的水平BoxLayout嵌套在顶层垂直布局中。 Here is a pretty decent tutorial about layout managers and it includes the BoxLayout. 是一个关于布局管理器的相当不错的教程,它包括BoxLayout。

There are many different ways, and many different LayoutManager s to use. 有许多不同的方法,以及许多不同的LayoutManager使用。 Read up some more on them here: 在这里阅读更多内容:

Here is an example I made which uses GridBagLayout : 以下是我使用GridBagLayout的示例:

在此输入图像描述

//necessary imports
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class Test {

    /**
     * Default constructor for Test.class
     */
    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        /**
         * Set look and feel of app
         */
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }
        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() {

        JFrame jFrame = new JFrame("Chat Test");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setResizable(false);

        //Initialise Panel 1 & Components
        JPanel p1 = new JPanel(new GridBagLayout());
        JPanel p2 = new JPanel(new GridBagLayout());
        //Label 1 - For TextArea
        JLabel l1 = new JLabel("Chat Log");
        //TextArea - To display conversation
        final JTextArea t1 = new JTextArea(10, 10);
        JScrollPane pane = new JScrollPane(t1);
        //Label 2 - For TextField
        JLabel l2 = new JLabel("Message");
        //Message Box - For user input
        final JTextField t2 = new JTextField(10);
        //Button 1 - To send message
        JButton b1 = new JButton("Send");

        GridBagConstraints gc = new GridBagConstraints();

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.weightx = 1;
        gc.gridx = 0;
        gc.gridy = 0;
        p1.add(l1, gc);

        gc.gridx = 0;
        gc.gridy = 1;
        p1.add(pane, gc);

        GridBagConstraints gc2 = new GridBagConstraints();
        gc2.fill = GridBagConstraints.HORIZONTAL;
        gc2.weightx = 1;
        gc2.gridx = 0;
        gc2.gridy = 0;
        gc2.ipadx = 10;
        p2.add(l2, gc2);

        gc2.gridx = 1;
        gc2.gridy = 0;
        p2.add(t2, gc2);

        gc2.gridx = 1;
        gc2.gridy = 1;
        p2.add(b1, gc2);

        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ev) {
                //do something
                t1.setText(t2.getText());
            }
        });

        jFrame.add(p1, BorderLayout.CENTER);
        jFrame.add(p2, BorderLayout.SOUTH);

        //pack frame (size JFrame to match preferred sizes of added components and set visible
        jFrame.pack();
        jFrame.setVisible(true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM