I want to customize the height and width of the JTextField objects. I have tried with the setSize method, passing width and height as dimensions and as int as well. But none of them seems to work. Am I missing something, like some mandatory method call on the panel or something so that the size customization would be effective? Please help. Thanks in advance.
EDIT: Here is a bit of the code:
public class WestPanel extends JPanel{
private JLabel dateL;
private JTextField date;
public WestPanel(){
setBackground(Color.white);
setLayout(new GridLayout(1,2,0,0));
dateL=new JLabel("Date: ");
date=new JTextField("dd/mm/yyyy");
date.setSize(60,10);
add(dateL);
add(date);
//....remaining code....//
Let the layout manager take care of the dimensions of your Swing components, but if you absolutely must, use
setPreferredSize
in combination with a layout manager that respects that property.The
setSize()
method only works when setting the layout manager to null.JTextField can not be set size, infact, you should use a JTextArea instead.
As suggested in comments, use size hints in the text field constructor, and an appropriate layout manager.
Size of your components in Swing will depend on the type of layout manager you are using. If you want full control of UI, you can use a Freeflow layout.
Read the full story here: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
I'm not sure this answers the original poster's questions, but hopefully it will be helpful to other Swing developers.
Most people want the labels and components to line up, like in the following dialog I created.
I use the Swing layout manager GridBagLayout to create this type of layout. Rather than lots of explanation, here's the code that created this dialog.
The EscapeDialog class I extend just lets me use the Esc key to close the dialog, as if I left clicked on the Cancel button.
There are two things I'll make note of. The first is the addComponent method, which simplifies adding components to a GridBagLayout.
The second is the setButtonSizes method, which makes all of the button sizes uniform. Even though they are JButton components, and not JTextField components, you can do something similar if you want to make JTextField components the same size.