使用网格布局[或可能的其他布局]

时间:2014-08-15 01:05:26

标签: java swing layout-manager grid-layout border-layout

我正在尝试构建一个简单的GUI来处理客户订单[当然这只是为了实践]。但是,我无法使用GridLayout格式化我的组件。有人可以建议一个更好的方法并在代码中进行更改,以便我可以学习实现吗?

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
    private JLabel Title, LastName, FirstName, LawnSize, TotalCost, RunningTotal; 
    private JTextField Field1, Field2, Field3, Field4, Field5;
    private JButton Next, Quit; 
    private re x= new re(); private me xx=new me(); 
    public RectangleProgram()
    {
        setSize(500,500); 
        setTitle("Sample1"); 
        setDefaultCloseOperation(EXIT_ON_CLOSE);  
        Container pane=getContentPane();
        pane.setLayout(new GridLayout(5,2));
        Title=new JLabel("Green and Grow Mowing Company"); 
        LastName=new JLabel("Last Name: "); 
        FirstName=new JLabel("First Name: ");
        LawnSize=new JLabel("Lawn Size: "); 
        TotalCost=new JLabel("Total Cost: "); 
        RunningTotal=new JLabel ("Running Total: ");
        Field1= new JTextField (10); Field2= new JTextField(10); Field3= new JTextField(10); Field4= new JTextField(10); Field5= new JTextField(10); 
        Next= new JButton("Next"); Quit= new JButton("Quit"); 
        Next.addActionListener(x); Quit.addActionListener(xx); 
        pane.add(Title); pane.add(LastName); pane.add(Field1); pane.add(FirstName); 
        pane.add(Field2); pane.add(LawnSize); pane.add(Field3); pane.add(TotalCost); pane.add(Field4);
        pane.add(RunningTotal); pane.add(Field5); 
        pane.add(Next); pane.add(Quit); 
        setVisible(true);

    }
    public class re implements ActionListener
    {
        public void actionPerformed (ActionEvent e)
        {
            String firstname, lastname; double ans; 
            firstname=Field2.getText();
            lastname=Field1.getText(); String fullname=firstname+" "+lastname; 
            fullname="Hello "+fullname+"!"; 
            JOptionPane.showMessageDialog(null, fullname);
            ans=Double.parseDouble(Field3.getText());
            String toput="Your total is "+ans; 
            JOptionPane.showMessageDialog(null,ans); 
            Field4.setText("$"+ans); 
            Field5.setText("$"+ans); 

        }
    }
    public class me implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0); 
        }
    }
    public static void main(String[] args)
    {
        RectangleProgram x= new RectangleProgram(); 
    }





}

2 个答案:

答案 0 :(得分:1)

GridLayout是一个非常简单的布局管理器,无法做很多事情。 你可以高兴地忘掉它。我建议你学习MigLayoutGroupLayout经理并从他们中选择。这两位经理 是灵活的,并创建独立于字体大小的布局 和屏幕分辨率。 GroupLayout是内置管理员,MigLayout是 第三方经理。

布局管理是一件复杂的事情,没有捷径。

MigLayout解决方案

package com.zetcode;

import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;

public class MigLayoutSolution extends JFrame {

    public MigLayoutSolution() {

        initUI();

        setTitle("MigLayout solution");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void initUI() {

        JPanel pnl = new JPanel(new MigLayout("wrap 2, ins dialog", "[r]"));
        pnl.add(new JLabel("Green and Grow Moving Company "), "span 2, center, wrap");
        pnl.add(new JLabel("Last name:"), "gaptop u");
        pnl.add(new JTextField(15), "pushx, growx");
        pnl.add(new JLabel("First name:"));
        pnl.add(new JTextField(15), "growx");
        pnl.add(new JLabel("Lawn size:"));
        pnl.add(new JTextField(15), "growx");
        pnl.add(new JLabel("Total cost:"));
        pnl.add(new JTextField(15), "growx");
        pnl.add(new JLabel("Running total:"));
        pnl.add(new JTextField(15), "growx");
        pnl.add(new JButton("Next"), "gaptop u, sgx, split 2, span 2, right");
        pnl.add(new JButton("Quit"), "sgx");

        add(pnl);
        pack();

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MigLayoutSolution ex = new MigLayoutSolution();
                ex.setVisible(true);
            }
        });
    }
}

enter image description here

GroupLayout解决方案

package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import static javax.swing.GroupLayout.Alignment.BASELINE;
import static javax.swing.GroupLayout.Alignment.CENTER;
import static javax.swing.GroupLayout.Alignment.TRAILING;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import static javax.swing.LayoutStyle.ComponentPlacement.UNRELATED;

public class GroupLayoutSolution extends JFrame {

    public GroupLayoutSolution() {

        initUI();
    }

    private void initUI() {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        JLabel titleLbl = new JLabel("Green and Grow Moving Company");
        JLabel fnLbl = new JLabel("First name:");
        JLabel lnLbl = new JLabel("Last name:");
        JLabel lsLbl = new JLabel("Lawn size:");
        JLabel tsLbl = new JLabel("Total cost:");
        JLabel rtLbl = new JLabel("Running total:");

        JTextField field1 = new JTextField(15);
        JTextField field2 = new JTextField(15);
        JTextField field3 = new JTextField(15);
        JTextField field4 = new JTextField(15);
        JTextField field5 = new JTextField(15);

        JButton nextBtn = new JButton("Next");
        JButton quitBtn = new JButton("Quit");

        gl.setAutoCreateGaps(true);
        gl.setAutoCreateContainerGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup(CENTER)
                .addComponent(titleLbl)
                .addGroup(gl.createParallelGroup(TRAILING)
                .addGroup(gl.createSequentialGroup()
                        .addGroup(gl.createParallelGroup(TRAILING)
                                .addComponent(fnLbl)
                                .addComponent(lnLbl)
                                .addComponent(lsLbl)
                                .addComponent(tsLbl)
                                .addComponent(rtLbl))
                        .addGroup(gl.createParallelGroup()
                                .addComponent(field1)
                                .addComponent(field2)
                                .addComponent(field3)
                                .addComponent(field4)
                                .addComponent(field5)))
                .addGroup(gl.createSequentialGroup()
                        .addComponent(nextBtn)
                        .addComponent(quitBtn)))
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(titleLbl)
                .addPreferredGap(UNRELATED)
                .addGroup(gl.createParallelGroup(BASELINE)
                        .addComponent(fnLbl)
                        .addComponent(field1))
                .addGroup(gl.createParallelGroup(BASELINE)
                        .addComponent(lnLbl)
                        .addComponent(field2))
                .addGroup(gl.createParallelGroup(BASELINE)
                        .addComponent(lsLbl)
                        .addComponent(field3))
                .addGroup(gl.createParallelGroup(BASELINE)
                        .addComponent(tsLbl)
                        .addComponent(field4))
                .addGroup(gl.createParallelGroup(BASELINE)
                        .addComponent(rtLbl)
                        .addComponent(field5))
                .addPreferredGap(UNRELATED)
                .addGroup(gl.createParallelGroup()
                        .addComponent(nextBtn)
                        .addComponent(quitBtn))
        );

        pack();

        setTitle("GroupLayout example");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GroupLayoutSolution ex = new GroupLayoutSolution();
                ex.setVisible(true);
            }
        });
    }
}

enter image description here

答案 1 :(得分:0)

它闻起来像家庭作业,但因为它有可能不是。

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

public class RectangleProgram extends JFrame
{
     private JLabel Title, LastName, FirstName, LawnSize, TotalCost, RunningTotal; 
     private JTextField Field1, Field2, Field3, Field4, Field5;
     private JButton Next, Quit;     

public RectangleProgram()
{    

    re r=new re(); // the actionlistner

    setTitle("Sample1");        
    setDefaultCloseOperation(EXIT_ON_CLOSE); 

    setLayout(new GridBagLayout());

    GridBagConstraints c=new GridBagConstraints(); 

    Title=new JLabel("Green and Grow Mowing Company"); 
    LastName=new JLabel("Last Name: "); 
    FirstName=new JLabel("First Name: ");
    LawnSize=new JLabel("Lawn Size: "); 
    TotalCost=new JLabel("Total Cost: "); 
    RunningTotal=new JLabel ("Running Total: ");

    Field1= new JTextField (10);
    Field2= new JTextField(10);
    Field3= new JTextField(10);
    Field4= new JTextField(10);
    Field5= new JTextField(10); 

    Next= new JButton("Next");
    Quit= new JButton("Quit"); 

    Next.addActionListener(r); 
    Quit.addActionListener(r); 



    // notice that you have to define the constraints before placing each component
    c.gridwidth=2; // allows the title to span 2 columns
    c.gridx=0;
    c.gridy=0;        
    add(Title, c);


    c.gridwidth=1; // sets the column span back to 1 column per component
    c.gridx=0;
    c.gridy=1;
    c.anchor=GridBagConstraints.EAST; // alignment set to the east
    add(LastName, c);

    c.gridx=1;
    c.gridy=1;
    c.anchor=GridBagConstraints.WEST; // alignment set to the west
    add(Field1, c);

    c.gridx=0;
    c.gridy=2;
    c.anchor=GridBagConstraints.EAST;
    add(FirstName, c);

    c.gridx=1;
    c.gridy=2;
    c.anchor=GridBagConstraints.WEST;
    add(Field2, c);

    c.gridx=0;
    c.gridy=3;
    c.anchor=GridBagConstraints.EAST;
    add(LawnSize, c);

    c.gridx=1;
    c.gridy=3;
    c.anchor=GridBagConstraints.WEST;
    add(Field3, c);

    c.gridx=0;
    c.gridy=4;
    c.anchor=GridBagConstraints.EAST;
    add(TotalCost, c);

    c.gridx=1;
    c.gridy=4;
    c.anchor=GridBagConstraints.WEST;
    add(Field4, c);

    c.gridx=0;
    c.gridy=5;
    c.anchor=GridBagConstraints.EAST;
    add(RunningTotal, c);

    c.gridx=1;
    c.gridy=5;
    c.anchor=GridBagConstraints.WEST;
    add(Field5, c);

    c.gridx=0;
    c.gridy=6;
    c.anchor=GridBagConstraints.CENTER;
    add(Next, c);

    c.gridx=1;
    c.gridy=6;
    add(Quit, c); 

    pack(); 
    setVisible(true);

}
public class re implements ActionListener
{
    public void actionPerformed (ActionEvent e)
    {           
       if(e.getSource()==Next){               

        String firstname, lastname;
        double ans; 

        firstname=Field2.getText();
        lastname=Field1.getText();

        String fullname=firstname+" "+lastname; 
        fullname="Hello "+fullname+"!"; 

        JOptionPane.showMessageDialog(null, fullname);

        ans=Double.parseDouble(Field3.getText());

        String toput="Your total is "+ans; 

        JOptionPane.showMessageDialog(null,ans); 

        Field4.setText("$"+ans); 
        Field5.setText("$"+ans);

        }else if(e.getSource().equals(Quit))
        {               
            System.exit(0);             
        }
    }
}


public static void main(String[] args)
{
    RectangleProgram x= new RectangleProgram(); 
}
}

您应该考虑为两个按钮仅使用一个actionlistener。您也可以使用lamda expression作为退出按钮,因为它只包含一行代码。