Ali Bassam
Ali Bassam

Reputation: 9969

I need a basic simple Java layout method

I've checked the internet about FlowLayout, Group etc., all with unhelpful examples. I just need a basic way to do a good layout for my Java application. I'll show you my code:

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);
        //----------------------------------------------------------------------

    }

}

This is a basic gui which has some labels and some textfields, with the .pack() method they will be shown on the same line, I just need a small simple way to make a good layout

Upvotes: 3

Views: 7033

Answers (6)

pathfinder
pathfinder

Reputation: 127

You can use windowBuilder eclipse plugin which helps in forming out a layout in what ever way you wanted to have. For example i've created a simple layout using windowbuilder which forms the code in this way

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

you can even open a pop-up from existing 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();}}}

I know the post is while longer... just incase if anyone wants info regarding this,my answer might be helpful... ;)

Upvotes: 0

thewhitetulip
thewhitetulip

Reputation: 3309

on what it seems is that you are having a login form...
you can use grid layout of two rows and one column
on one row it will contain label, textfield, second also the same with additional a button if you dont want to give event handler to the last text field

here is the code of one simple login form i designed without using any drag and drop tools

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


    }
}

you can see the code...

there are basic layouts as flow layout the default layout of swing applications and gridlayout
in flow layout the components you add to the frame flow from right to left their orientation changes every time you change the size of the frame in such a way that the tend to flow hence called the flow layout

in grid layout the components are aligned into a grid of n x m dimension n: the number of rows and n: the number of columns it resembles a grid hence the name if you resize the window nothing will happen in a grid layout as it is designed for the same purpose... the output combined of the flow layout and the girf layout is shown here fyi: the frame marked with grid of 2x2 is the output of grid layout rest other frames are o/p of flow layout pls study the difference in the arrangement of buttons on changing the size of the window cheers

Upvotes: 2

Robin
Robin

Reputation: 36611

For those type of UI's (label - editor component) I find the FormLayout of JGoodies one of the best, and very easy to use.

Upvotes: 2

MaVRoSCy
MaVRoSCy

Reputation: 17849

y dont you use an IDE? JDeveloper and Netbeans are excellent solutions with drag and drop functionality

Upvotes: 1

nIcE cOw
nIcE cOw

Reputation: 24626

Too many static variables inside your code is not an ideal solution for many a reasons. Try to use a different approach, until and unless you not thinking about making one Factory Class for your Project. Have a look at this modified version, is this good enough :

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

}

Here is the output :

LOGIN WINDOW

Upvotes: 4

mKorbel
mKorbel

Reputation: 109823

1) you have an issue with debuging, java conventions and packaging methods and classes, you have and issues with

2) add a new curly brace

    }//add this one

    public static void main(String[] arg) {


    }
} 

3) built the Swing GUI in Initail Thread, then your main class should be

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 and then usage of pack(); is contraproductive use pack() rather than setSize

5) you have look at SpringLayout, or GridBagLayout in the case that you will put there more the similair JComponents,

Upvotes: 3

Related Questions