user1537814
user1537814

Reputation: 85

Setting JTextField while creating its object in a single Java statement

I am creating a JPanel and setting a layout as follows:

JPanel jpObj= new JPanel();
jpObj.setLayout(new BoxLayout(jpObj, BoxLayout.Y_AXIS));

and then adding a JTextField to my JPanel as follows:

jpObj.add(new JTextField("300000"));

I would like to specify the height of the JTextField without having to write seperate lines of code. For example,

JTextField textField = new JTextField("600000");
textField.setMaximumSize(new Dimension(1000,50) );
jpObj.add(textField);

Is there a way to specify the height of my JTextField while creating its object? The following attempt doesn't seem to work for me.

jpObj.add(new JTextField("300000").setMaximumSize(new Dimension(1000,50)));

Thanks in advance!

Upvotes: 0

Views: 414

Answers (1)

Jon Taylor
Jon Taylor

Reputation: 7905

No since setMaximumSize has a return of void.

You should do it as you already described.

JTextField textField = new JTextField("600000");
textField.setMaximumSize(new Dimension(1000,50) );
jpObj.add(textField);

Potentially I guess you could create your own method which could create, set height and return a JTextField object as follows then this could be done in one line.

private JTextField createJTextField(String text, Dimension dimenstion) {
    JTextField textField = new JTextField(text);
    textField.setMaximumSize(dimenstion);
    return textField;
}

Then you could call it as follows:

jpObj.add(createJTextField("item1",new Dimension(200,300)));
jpObj.add(createJTextField("item2",new Dimension(500,100)));

Upvotes: 3

Related Questions