Search code examples
javajtextfield

JTextField is Too big in the event handled JFrame


I'm new to JAVA Programming and I'm trying to make a memory modification GUI program below is the code. MY JTextField is too big any suggestions on how to fix this problem? also I would appreciate if an alternate way was found to do the mentioned task. Thank you for your time

JMenuBar menubar;
JMenu data,array,linkedlist,strings,stacks,tree,graphs,queues;
JMenuItem dtypeint,dtypefloat,dtypechar;

public GUI(){
    super("Data Structures Assignment");
    System.out.println("Select the Above mentioned Options for Memory Modification");
    setLayout(new FlowLayout());
    menubar = new JMenuBar();
    add(menubar);

    data = new JMenu("Basic Data Types");
    menubar.add(data);

    array = new JMenu("Arrays");
    menubar.add(array);

    linkedlist = new JMenu("Linked List");
    menubar.add(linkedlist);

    strings = new JMenu("Strings");
    menubar.add(strings);

    stacks = new JMenu("Stacks");
    menubar.add(stacks);

    tree = new JMenu("Tree");
    menubar.add(tree);

    graphs = new JMenu("Graphs");
    menubar.add(graphs);

    queues = new JMenu("Queues");
    menubar.add(queues);

    dtypeint = new JMenuItem("Integer");
    data.add(dtypeint);

    dtypefloat = new JMenuItem("Float");
    data.add(dtypefloat);

    dtypechar = new JMenuItem("Character");
    data.add(dtypechar);

    setJMenuBar(menubar);

    thehandler handler = new thehandler();
    dtypeint.addActionListener(handler);
    dtypefloat.addActionListener(handler);
    dtypechar.addActionListener(handler);
}
private class thehandler implements ActionListener{
    public void actionPerformed(ActionEvent event){

        if(event.getSource()==dtypeint){
            setLayout(new GridLayout());
            Frame F = new JFrame();
            F.setVisible(true);
            F.setSize(200,200);
            final JTextField item1;
            item1 = new JTextField("Word Size");
            item1.setColumns(15);
            F.add(item1);

        }
    }
}

}


Solution

    • Remove F.setSize(200,200).
    • After your F.add(item1) line, add F.pack().
    • Finally, move the F.setVisible(true) line so it comes after the F.pack() line; you should not show a Frame until you have finished building it.

    The pack() method sets a window's size to accommodate the preferred sizes of the components it contains.