【问题标题】:I need a basic simple Java layout method我需要一个基本的简单Java布局方法
【发布时间】:2012-05-28 21:21:04
【问题描述】:

我在网上查过FlowLayout、Group 等,所有这些都是无用的例子。我只需要一种基本方法来为我的 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() 方法它们将显示在同一行,我只需要一个简单的小方法来制作一个好的布局

【问题讨论】:

  • 还要查看嵌套布局。

标签: java swing user-interface layout


【解决方案1】:

您可以使用 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();}}}

我知道这篇文章的时间更长......如果有人想了解这方面的信息,我的回答可能会有所帮助......;)

【讨论】:

【解决方案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();
            }
        });


    }
}

你可以看到代码...

有基本布局,如流式布局、swing 应用程序的默认布局和网格布局
在流布局中,您添加到框架中的组件从右到左流动,每次您更改框架的大小时,它们的方向都会发生变化,从而倾向于流动,因此称为流布局

在网格布局中,组件对齐到 n x m 尺寸的网格中 n:行数和 n:列数 它类似于网格,因此如果您调整窗口大小,则在网格布局中不会发生任何事情,因为它是为相同目的而设计的...... 仅供参考:标有2x2网格的框架是网格布局的输出其余框架是流布局的o / p请研究改变窗口大小按钮排列的差异 干杯

【讨论】:

    【解决方案3】:

    对于那些类型的 UI(标签 - 编辑器组件),我发现 FormLayout 和 JGoodies 是最好的之一,而且非常易于使用。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 先学习如何使用基本布局管理器不是更好吗?
      • 当然是。 ide 只会帮助您快速做某事。如果你想深入,这并不总是正确的方法
      【解决方案5】:

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

      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();
                  }
              });
          }
      
      }
      

      这是输出:

      【讨论】:

      • 你不知道如何从命令提示符运行你的程序吗?首先转到命令提示符上的Test1.java 文件的位置。现在写javac Test1.java 然后写java Test1
      【解决方案6】:

      1) 您在调试、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 for JFrame 然后使用 pack(); 是相反的使用 pack() 而不是 setSize

      5) 您可以查看SpringLayout 或GridBagLayout,以防您将更多类似的 JComponents 放在那里,

      【讨论】:

        猜你喜欢
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多