Java unreasonable jtextfield sizing problem

I looked for all such problems, but could not find a solution.

public class FormPanel extends JPanel { private JLabel namelabel; private JLabel occlabel; private JTextField nametext; private JTextField occtext; private JButton okButton; public FormPanel() { Dimension dim = getPreferredSize(); dim.width = 250; setPreferredSize(dim); namelabel = new JLabel("Name : "); occlabel = new JLabel("Occupation : "); nametext = new JTextField(); nametext.setPreferredSize(new Dimension(80,20)); occtext = new JTextField(); occtext.setColumns(20); okButton = new JButton("OK"); Border inner = BorderFactory.createTitledBorder("Add Person : "); Border outer = BorderFactory.createEmptyBorder(5,5,5,5); setBorder(BorderFactory.createCompoundBorder(inner,outer)); setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.weightx = 1; gc.weighty = 1; gc.fill = GridBagConstraints.NONE; add(namelabel,gc); gc.gridx = 1; gc.gridy = 0; add(nametext,gc); gc.gridy = 1; gc.gridx = 0; add(occlabel,gc); gc.gridy = 1; gc.gridx = 1; add(occtext,gc); gc.gridy = 2; gc.gridx = 1; add(okButton,gc); } } 

nametext and occtext extremely small. I tried the new JTextField (20) and the string version, I tried setPreferredSize as the above class, and I also tried setColumn, but none of them work.

+6
source share
2 answers

Get setPreferredSize(dim); of setPreferredSize(dim); . Let the GUI itself by calling pack() in the top-level window, and your problem will most likely disappear. You limit the size of the container, which may be smaller than the best for it, and thereby GridBagLayout will then smooth out its components, including your JTextFields, in a bad way.

+6
source

If using pack() might be a good idea to set dim.height .

 Dimension dim = getPreferredSize(); dim.width = 500; dim.height = 200; setPreferredSize(dim); namelabel = new JLabel("Name : "); nametext = new JTextField(); occlabel = new JLabel("Occupation : "); occtext = new JTextField(); okButton = new JButton("OK"); Border inner = BorderFactory.createTitledBorder("Add Person : "); Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5); setBorder(BorderFactory.createCompoundBorder(inner, outer)); GridBagLayout gl = new GridBagLayout(); GridBagConstraints gc = new GridBagConstraints(); setLayout(gl); gc.fill = GridBagConstraints.HORIZONTAL; gc.gridwidth = 1; add(namelabel, gc); gc.gridy = 1; add(occlabel, gc); gc.gridx = 1; gc.gridy = 0; gc.weightx = .5; add(nametext, gc); gc.gridy = 1; add(occtext, gc); gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.EAST; gc.gridy = 2; gc.gridx = 1; gc.weightx = 0; gc.insets = new Insets(10,0,0,0); add(okButton, gc); 
0
source

Source: https://habr.com/ru/post/979595/


All Articles