Search code examples
javaswinglayoutjpasswordfield

JPasswordBox field is to big. How do I make it smaller?


I am Completely new to writing Java. I am creating an interface that gathers a list of all the internet connections in the area. The user selects one on them, enters the password then the person can connect to the password. I have a problem with the Password field... It is to big for a password box.

enter image description here

How do I fix that? Here is the code.

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

public class Network_Interface
{
    JFrame frame;
    JPanel panel;

    public static void main (String[] args)
    {
        Network_Interface OBJECT_GUI = new Network_Interface();
        OBJECT_GUI.INIT();
    }

    public void INIT()
    {
        //frame and panel
        JFrame FRAME = new JFrame();
        JPanel PANEL = new JPanel();
        //init fields and labels
        JButton BUTTON_REFRESH = new JButton("Refesh List");
        JButton BUTTON_CONNECT = new JButton("Connect to network");
        JPasswordField  FIELD_PASSWORD = new JPasswordField(15);
        JLabel LABEL_PASSWORD = new JLabel("Enter Password of selected newtork.");
        JList LIST_NETWORKS = new JList(GET_NETWORKS());
        //event listeners
        BUTTON_REFRESH.addActionListener(new REFRESH_LISTENER());
        BUTTON_CONNECT.addActionListener(new CONNECT_LISTENER());
        //panel handling
        PANEL.setLayout(new BoxLayout(PANEL, BoxLayout.Y_AXIS));
        PANEL.add(LIST_NETWORKS);
        PANEL.add(BUTTON_REFRESH);
        PANEL.add(LABEL_PASSWORD);
        PANEL.add(FIELD_PASSWORD);
        PANEL.add(BUTTON_CONNECT);
        FRAME.getContentPane().add(BorderLayout.CENTER, PANEL);
        FRAME.setSize(500,500);
        FRAME.setVisible(true);
    }
    public String[] GET_NETWORKS()
    {
        //read file
        String[] ARRAY_NETWORKS= new String[2];
        ARRAY_NETWORKS[0] = "Frnkthtnk100";
        ARRAY_NETWORKS[1] = "CheesecakeFactory";
        return ARRAY_NETWORKS;
    }
    class REFRESH_LISTENER implements ActionListener
    {
        public void actionPerformed(ActionEvent EVENT)
        {
            //idk to do at this point
        }
    }
    class CONNECT_LISTENER implements ActionListener
    {
        public void actionPerformed(ActionEvent EVENT)
        {
            //IDk at this point
        }
    }
}

Solution

  • 1) Easy way : replace FRAME.setSize(500,500); by FRAME.pack();. It will adjust the frame to the size of the components. But it will change the size of the frame.

    2)If you want to keep the frame size, you can specify the maximum size of JPasswordField FIELD_PASSWORD so that it doesn't be extended to the maximum in the JPanel.

    JPasswordField FIELD_PASSWORD = new JPasswordField(15);
    FIELD_PASSWORD.setMaximumSize(new Dimension(FIELD_PASSWORD.getMaximumSize().width, FIELD_PASSWORD.getMinimumSize().height));