我需要一个基本的简单Java布局方法

时间:2012-05-22 11:26:40

标签: java swing user-interface layout

我已经在互联网上检查了FlowLayoutGroup等等,所有这些都是无用的例子。我只需要一个基本的方法来为我的Java应用程序做一个好的布局。我会告诉你我的代码:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test1 {

    //Step1 - Declaring variables
    private static JFrame myFrame;
    private static JPanel myPanel;
    private static JLabel titleLabel=null;
    private static JLabel logIn=null;
    private static JLabel username=null;
    private static JLabel password=null;
    private static JTextField usernameField=null;
    private static JPasswordField passwordField=null;
    private static Color myColor=new Color(0, 102, 204);
    private static Font myFont11=new Font("Tahoma", 1, 11);
    private static Font myFont12bold=new Font("Tahoma", Font.BOLD, 12);
    private static Font myFont11bold=new Font("Tahoma", Font.BOLD, 11);

    //Step2 - Creating Components
    public void createComponents() {


        //Title Label
        titleLabel=new JLabel("My Program");
        titleLabel.setForeground(Color.white);
        titleLabel.setFont(myFont12bold);
        //titleLabel.setVisible(false); //hide it or show it
        //--------------------------------------------------------


        logIn=new JLabel("Log in");
        logIn.setFont(myFont11bold);
        logIn.setForeground(Color.white);
        username=new JLabel("Username");
        username.setLabelFor(usernameField);
        username.setFont(myFont11);
        username.setForeground(Color.white);
        password=new JLabel("Password");
        password.setLabelFor(passwordField);
        password.setFont(myFont11);
        password.setForeground(Color.white);
        usernameField=new JTextField(10);
        usernameField.setBorder(new LineBorder(null, 0, false));
        passwordField=new JPasswordField(10);
        passwordField.setBorder(new LineBorder(null, 0, false));

        //Panel
        myPanel=new JPanel();
        myPanel.setBackground(myColor);
        myPanel.add(titleLabel);       
        myPanel.add(logIn);
        myPanel.add(mySeparator2);
        myPanel.add(username);
        myPanel.add(usernameField);
        myPanel.add(password);
        myPanel.add(passwordField);
        //----------------------------------------------------------

    //Step3 - Main Function
    public static void main(String[] arg) {

        //Frame
        myFrame=new JFrame();

        myFrame.setPreferredSize(new Dimension(400,300));//width:400px, height:300px
        myFrame.setLocationRelativeTo(null);//to show at center of screen
        myFrame.setTitle("My Program");
        Test1 prog=new Test1();
        prog.createComponents();
        myFrame.add(myPanel);
        myFrame.pack();//this alone will not give the frame a size
        myFrame.setVisible(true);
        //----------------------------------------------------------------------

    }

}

这是一个基本的gui,它有一些标签和一些文本字段,.pack()方法它们将显示在同一行上,我只需要一个简单的小方法来制作一个好的布局

6 个答案:

答案 0 :(得分:4)

由于许多原因,代码中的static个变量太多不是理想的解决方案。尝试使用不同的方法,除非您不考虑为Factory Class制作一个Project。看看这个修改过的版本,这还不错:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test1 {

    //Step1 - Declaring variables
    private JFrame myFrame;
    // Added by me
    private JPanel contentPane;
    private JPanel myPanel;
    private JLabel username=null;
    private JLabel password=null;
    private JTextField usernameField=null;
    private JPasswordField passwordField=null;
    private Color myColor=new Color(200, 102, 204);
    private Font myFont11=new Font("Tahoma", 1, 11);
    private Font myFont12bold=new Font("Tahoma", Font.BOLD, 12);
    private Font myFont11bold=new Font("Tahoma", Font.BOLD, 11);

    //Step2 - Creating Components
    public void createComponents() {

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        contentPane.setLayout(new GridBagLayout());
        contentPane.setBorder(BorderFactory.createTitledBorder("My Program"));

        username=new JLabel("Username");
        username.setLabelFor(usernameField);
        username.setFont(myFont11);
        username.setForeground(Color.white);
        password=new JLabel("Password");
        password.setLabelFor(passwordField);
        password.setFont(myFont11);
        password.setForeground(Color.white);
        usernameField=new JTextField(10);
        usernameField.setBorder(new LineBorder(null, 0, false));
        passwordField=new JPasswordField(10);
        passwordField.setBorder(new LineBorder(null, 0, false));

        //Panel
        myPanel=new JPanel();
        myPanel.setOpaque(true);
        myPanel.setBorder(BorderFactory.createTitledBorder("Login"));
        myPanel.setBackground(myColor);
        myPanel.setLayout(new GridLayout(2, 2, 2, 2));
        myPanel.add(username);
        myPanel.add(usernameField);
        myPanel.add(password);
        myPanel.add(passwordField);
        //----------------------------------------------------------
        contentPane.add(myPanel);

        myFrame=new JFrame();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //myFrame.setPreferredSize(new Dimension(400,300));//width:400px, height:300px
        myFrame.setLocationRelativeTo(null);//to show at center of screen
        myFrame.setTitle("My Program");
        //myFrame.add(myPanel);
        myFrame.setContentPane(contentPane);
        myFrame.pack();//this alone will not give the frame a size
        myFrame.setVisible(true);
    }   

    //Step3 - Main Function
    public static void main(String[] arg) {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new Test1().createComponents();
            }
        });
    }

}

这是输出:

LOGIN WINDOW

答案 1 :(得分:3)

1)你有关于debuging,java约定和包装方法和类的问题,你有问题和

2)添加一个新的大括号

    }//add this one

    public static void main(String[] arg) {


    }
} 

3)在Initail Thread中构建了Swing GUI,然后你的主类应该是

public static void main(String[] arg) {
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            myFrame = new JFrame();

            myFrame.setPreferredSize(new Dimension(400, 300));//width:400px, height:300px
            myFrame.setLocationRelativeTo(null);//to show at center of screen
            myFrame.setTitle("My Program");
            Test1 prog = new Test1();
            prog.createComponents();
            myFrame.add(myPanel);
            myFrame.pack();//this alone will not give the frame a size
            myFrame.setVisible(true);
        }
    });
}

4)setSize JFrame然后pack();的使用是反效果使用pack()而不是setSize

5)如果您要将更多相似的JComponents放在那里,您可以查看SpringLayoutGridBagLayout

答案 2 :(得分:2)

对于那些类型的UI(标签 - 编辑器组件),我发现FormLayout {{1}}是最好的,并且非常容易使用。

答案 3 :(得分:2)

看起来你正在登录表格...
您可以使用两行和一列的网格布局在一行上它将包含标签,文本字段,如果您不想将事件处理程序提供给最后一个文本字段,则第二个也与附加一个按钮相同

这是我设计的一个简单登录表单的代码,不使用任何拖放工具

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

public class LoginFrame extends JFrame{
    User user;
    private JPanel buttonPanel;
    JButton btnLogin;
    JButton btnRegister;
    JButton btnExit;
    JPanel panelUser;
    JPanel panelPwd;
    JLabel nameLabel;
    final JTextField txtUserName;
    final JPasswordField txtPwd;

    public LoginFrame() {
        user = new User();
        setTitle("Demo for next Button frame");
        setSize(370, 169);
        JPanel masterPanel = new JPanel(); 
        buttonPanel  = new JPanel();


        btnLogin = new JButton("Log in");
        btnExit = new JButton("Exit");
        btnRegister = new JButton("Register");

        buttonPanel.add(btnLogin);
        buttonPanel.add(btnExit);
        buttonPanel.add(btnRegister);

        panelUser = new JPanel();
        panelPwd = new JPanel();

        nameLabel = new JLabel("user name");
        txtUserName = new JTextField("", 20);
        JLabel pwdLabel = new JLabel("password");
        txtPwd = new JPasswordField("", 20);

        panelUser.add(nameLabel);
        panelUser.add(txtUserName);
        panelPwd.add(pwdLabel);
        panelPwd.add(txtPwd);

        masterPanel.add(panelUser);
        masterPanel.add(panelPwd);
        masterPanel.add(buttonPanel);
        add(masterPanel, BorderLayout.CENTER);

        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                user.setUserName(JOptionPane.showInputDialog(null,"Enter user name you want"));
                user.setPassword(JOptionPane.showInputDialog(null,"Enter password you want"));
                JOptionPane.showMessageDialog(null, "now log in with your user name and password");
                user.saveFile();
            }
        });

        btnLogin.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){

                if(txtUserName.getText().equals(user.getUserName()) && (new String(txtPwd.getPassword())).equals(user.getPassword())){
                                dispose();
                                user.saveLog();
                                TimeFrame tFrame = new TimeFrame(user.getUserName());
                                tFrame.setVisible(true);
                                tFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

                                // Determine the new location of the window
                                int w = tFrame.getSize().width;
                                int h = tFrame.getSize().height;
                                int x = (dim.width-w)/2;
                                int y = (dim.height-h)/2;

                                // Move the window
                                tFrame.setLocation(x, y);

                        } else {
                            JOptionPane.showMessageDialog(null,"User name or password don't match","Acces Denied", JOptionPane.ERROR_MESSAGE);
                        }
            }

        });

        btnExit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                dispose();
            }
        });


    }
}

你可以看到代码......

有基本布局作为流程布局摆动应用程序和gridlayout的默认布局 在流布局中,添加到框架中的组件从右向左流动,每次更改框架的大小时,它们的方向都会发生变化,因此趋向于流动,因此称为流程布局

在网格布局中,组件对齐到n x m维的网格中 n:行数和n:它类似于网格的列数因此,如果你调整窗口大小,名称就不会在网格布局中发生,因为它是为同一目的而设计的......  the output combined of the flow layout and the girf layout is shown here fyi:标有网格2x2的框架是网格布局的输出,其他框架是o / p的流程布局请研究按钮排列的不同,改变窗口的大小 欢呼声

答案 4 :(得分:1)

你不使用IDE吗? JDeveloper和Netbeans是具有拖放功能的出色解决方案

答案 5 :(得分:0)

您可以使用windowBuilder eclipse插件,它有助于以您想要的方式形成布局。 例如,我使用windowbuilder创建了一个简单的布局,以这种方式形成代码

import java.awt.Color;import java.awt.EventQueue;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.GroupLayout;import javax.swing.GroupLayout.Alignment;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JProgressBar;import javax.swing.JTextField;import javax.swing.LayoutStyle.ComponentPlacement;import javax.swing.SwingConstants;import javax.swing.border.EmptyBorder;import javax.swing.event.MenuEvent;import javax.swing.event.MenuListener;public class LoginFrame2 extends JFrame implements ActionListener,MenuListener{private static final long serialVersionUID=1L;private JPanel contentPane;private JTextField userNameTextField;private JPasswordField passwordField;private JButton btnChangePassword;private JProgressBar progressBar;private JCheckBox chckbxShowPassword;private static final Color GREEN_COLOR=new Color(107,142,35);private static final Color RED_COLOR=new Color(255,0,0);private JLabel lblStatusmessage,lblProgressstatus;private JPanel footerPanel;private JLabel lblFooter;private JMenuBar menuBar;private JMenu mnConfigure;public static void main(String[]args){EventQueue.invokeLater(new Runnable(){public void run(){try{LoginFrame2 frame=new LoginFrame2();frame.setVisible(true);}catch(Exception e){e.printStackTrace();}}});}
public LoginFrame2(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,455,350);menuBar=new JMenuBar();setJMenuBar(menuBar);mnConfigure=new JMenu("Configure");mnConfigure.addMenuListener(this);menuBar.add(mnConfigure);contentPane=new JPanel();contentPane.setBorder(new EmptyBorder(5,5,5,5));setContentPane(contentPane);JPanel topPanel=new JPanel();JPanel centerPanel=new JPanel();JPanel bottomPanel=new JPanel();footerPanel=new JPanel();GroupLayout gl_contentPane=new GroupLayout(contentPane);gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,gl_contentPane.createSequentialGroup().addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addComponent(bottomPanel,GroupLayout.DEFAULT_SIZE,438,Short.MAX_VALUE).addComponent(footerPanel,GroupLayout.PREFERRED_SIZE,438,Short.MAX_VALUE).addComponent(topPanel,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,438,Short.MAX_VALUE).addComponent(centerPanel,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,438,Short.MAX_VALUE)).addContainerGap()));gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addComponent(topPanel,GroupLayout.PREFERRED_SIZE,37,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(centerPanel,GroupLayout.DEFAULT_SIZE,154,Short.MAX_VALUE).addPreferredGap(ComponentPlacement.RELATED).addComponent(bottomPanel,GroupLayout.PREFERRED_SIZE,61,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(footerPanel,GroupLayout.PREFERRED_SIZE,14,GroupLayout.PREFERRED_SIZE).addGap(1)));lblFooter=new JLabel("Developer : KEA3");lblFooter.setHorizontalAlignment(SwingConstants.RIGHT);lblFooter.setFont(new Font("Tahoma",Font.PLAIN,8));GroupLayout gl_footerPanel=new GroupLayout(footerPanel);gl_footerPanel.setHorizontalGroup(gl_footerPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_footerPanel.createSequentialGroup().addGap(100).addComponent(lblFooter,GroupLayout.PREFERRED_SIZE,338,GroupLayout.PREFERRED_SIZE).addContainerGap(GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)));gl_footerPanel.setVerticalGroup(gl_footerPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_footerPanel.createSequentialGroup().addComponent(lblFooter,GroupLayout.PREFERRED_SIZE,14,GroupLayout.PREFERRED_SIZE).addContainerGap(GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)));footerPanel.setLayout(gl_footerPanel);progressBar=new JProgressBar();lblProgressstatus=new JLabel("progressStatus");lblProgressstatus.setFont(new Font("Tahoma",Font.BOLD,11));lblProgressstatus.setHorizontalAlignment(SwingConstants.CENTER);GroupLayout gl_bottomPanel=new GroupLayout(bottomPanel);gl_bottomPanel.setHorizontalGroup(gl_bottomPanel.createParallelGroup(Alignment.TRAILING).addGroup(gl_bottomPanel.createSequentialGroup().addContainerGap().addComponent(lblProgressstatus,GroupLayout.DEFAULT_SIZE,412,Short.MAX_VALUE).addContainerGap()).addComponent(progressBar,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,438,Short.MAX_VALUE));gl_bottomPanel.setVerticalGroup(gl_bottomPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_bottomPanel.createSequentialGroup().addContainerGap().addComponent(progressBar,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(lblProgressstatus).addContainerGap(GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)));bottomPanel.setLayout(gl_bottomPanel);JLabel lblAlias=new JLabel("Alias :");lblAlias.setFont(new Font("Tahoma",Font.BOLD,11));lblAlias.setHorizontalAlignment(SwingConstants.RIGHT);JLabel lblPassword=new JLabel("Password :");lblPassword.setFont(new Font("Tahoma",Font.BOLD,11));lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);userNameTextField=new JTextField();userNameTextField.setColumns(10);passwordField=new JPasswordField();chckbxShowPassword=new JCheckBox("Show Password");chckbxShowPassword.setFont(new Font("Tahoma",Font.BOLD,11));btnChangePassword=new JButton("Change Password");GroupLayout gl_centerPanel=new GroupLayout(centerPanel);gl_centerPanel.setHorizontalGroup(gl_centerPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_centerPanel.createSequentialGroup().addGroup(gl_centerPanel.createParallelGroup(Alignment.TRAILING,false).addComponent(lblPassword,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addGroup(Alignment.LEADING,gl_centerPanel.createSequentialGroup().addContainerGap().addComponent(lblAlias,GroupLayout.PREFERRED_SIZE,151,GroupLayout.PREFERRED_SIZE))).addPreferredGap(ComponentPlacement.UNRELATED).addGroup(gl_centerPanel.createParallelGroup(Alignment.LEADING).addComponent(btnChangePassword).addComponent(chckbxShowPassword).addComponent(passwordField,GroupLayout.DEFAULT_SIZE,251,Short.MAX_VALUE).addComponent(userNameTextField,GroupLayout.DEFAULT_SIZE,251,Short.MAX_VALUE)).addContainerGap()));gl_centerPanel.setVerticalGroup(gl_centerPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_centerPanel.createSequentialGroup().addGap(21).addGroup(gl_centerPanel.createParallelGroup(Alignment.BASELINE).addComponent(lblAlias).addComponent(userNameTextField,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addPreferredGap(ComponentPlacement.UNRELATED).addGroup(gl_centerPanel.createParallelGroup(Alignment.BASELINE).addComponent(lblPassword).addComponent(passwordField,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(18).addComponent(chckbxShowPassword).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(btnChangePassword).addContainerGap(15,Short.MAX_VALUE)));btnChangePassword.addActionListener(this);centerPanel.setLayout(gl_centerPanel);lblStatusmessage=new JLabel("Status Message");lblStatusmessage.setFont(new Font("Tahoma",Font.BOLD|Font.ITALIC,13));lblStatusmessage.setHorizontalAlignment(SwingConstants.CENTER);JLabel lblHeader=new JLabel("Header\r\n");lblHeader.setFont(new Font("Tahoma",Font.BOLD,13));lblHeader.setHorizontalAlignment(SwingConstants.CENTER);GroupLayout gl_topPanel=new GroupLayout(topPanel);gl_topPanel.setHorizontalGroup(gl_topPanel.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING,gl_topPanel.createSequentialGroup().addGap(10).addGroup(gl_topPanel.createParallelGroup(Alignment.LEADING).addComponent(lblStatusmessage,Alignment.TRAILING,GroupLayout.DEFAULT_SIZE,428,Short.MAX_VALUE).addComponent(lblHeader,Alignment.TRAILING,GroupLayout.DEFAULT_SIZE,428,Short.MAX_VALUE)).addContainerGap()));gl_topPanel.setVerticalGroup(gl_topPanel.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING,gl_topPanel.createSequentialGroup().addComponent(lblHeader).addPreferredGap(ComponentPlacement.RELATED,7,Short.MAX_VALUE).addComponent(lblStatusmessage)));topPanel.setLayout(gl_topPanel);contentPane.setLayout(gl_contentPane);lblStatusmessage.setVisible(false);lblProgressstatus.setVisible(false);progressBar.setVisible(false);}@Override
public void actionPerformed(ActionEvent e){System.out.println("Ding"+e.getActionCommand());}@Override
public void menuCanceled(MenuEvent arg0){}@Override
public void menuDeselected(MenuEvent arg0){}@Override
public void menuSelected(MenuEvent arg0){new ConfigureDialog(this).setVisible(true);}}

您甚至可以从现有的jframe打开弹出窗口

    import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import javax.swing.GroupLayout;import javax.swing.GroupLayout.Alignment;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.LayoutStyle.ComponentPlacement;import javax.swing.border.EmptyBorder;import javax.swing.filechooser.FileFilter;import javax.swing.filechooser.FileNameExtensionFilter;public class ConfigureDialog extends JDialog implements ActionListener{private static final long serialVersionUID=1L;private final JPanel contentPanel=new JPanel();private JTextField driverPathTextField;private JLabel lblDriverPath;private JButton btnBrowse;public static void main(String[]args){try{ConfigureDialog dialog=new ConfigureDialog(new JFrame());dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);dialog.setVisible(true);}catch(Exception e){e.printStackTrace();}}
public ConfigureDialog(JFrame parent){super(parent,"",true);if(parent!=null){Dimension parentSize=parent.getSize();Point p=parent.getLocation();setLocation(p.x+parentSize.width+100,p.y+parentSize.height/1);}
setBounds(100,100,479,141);getContentPane().setLayout(new BorderLayout());contentPanel.setBorder(new EmptyBorder(5,5,5,5));getContentPane().add(contentPanel,BorderLayout.CENTER);{lblDriverPath=new JLabel("Driver Path : ");}
{driverPathTextField=new JTextField(System.getProperty("web.ie.driver"));driverPathTextField.setColumns(10);}
btnBrowse=new JButton("Browse");GroupLayout gl_contentPanel=new GroupLayout(contentPanel);gl_contentPanel.setHorizontalGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPanel.createSequentialGroup().addContainerGap().addComponent(lblDriverPath).addPreferredGap(ComponentPlacement.RELATED).addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING).addComponent(btnBrowse).addComponent(driverPathTextField,GroupLayout.DEFAULT_SIZE,207,Short.MAX_VALUE)).addContainerGap()));gl_contentPanel.setVerticalGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPanel.createSequentialGroup().addGap(5).addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE).addComponent(driverPathTextField,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(lblDriverPath)).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(btnBrowse).addContainerGap(21,Short.MAX_VALUE)));contentPanel.setLayout(gl_contentPanel);{JPanel buttonPane=new JPanel();buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));getContentPane().add(buttonPane,BorderLayout.SOUTH);{JButton okButton=new JButton("OK");okButton.setActionCommand("OK");okButton.addActionListener(this);buttonPane.add(okButton);getRootPane().setDefaultButton(okButton);}
{JButton cancelButton=new JButton("Cancel");cancelButton.setActionCommand("Cancel");cancelButton.addActionListener(this);buttonPane.add(cancelButton);}}
btnBrowse.addActionListener(this);}@Override
public void actionPerformed(ActionEvent e){if("Cancel".contains(e.getActionCommand())){dispose();}else if("Browse".contains(e.getActionCommand())){JFileChooser fileopen=new JFileChooser();FileFilter filter=new FileNameExtensionFilter("exe file","exe");fileopen.addChoosableFileFilter(filter);fileopen.setAcceptAllFileFilterUsed(false);fileopen.setFileFilter(filter);fileopen.setFileSelectionMode(JFileChooser.FILES_ONLY);int ret=fileopen.showOpenDialog(this);if(ret==JFileChooser.APPROVE_OPTION){File file=fileopen.getSelectedFile();System.out.println(file);driverPathTextField.setText(file.getPath());}}else if("OK".contains(e.getActionCommand())){System.setProperty("web.ie.driver",driverPathTextField.getText());dispose();}}}

我知道这篇文章的篇幅会更长......如果有人想要了解相关信息,我的回答可能会有所帮助......;)