0

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!

kleopatra
  • 51,061
  • 28
  • 99
  • 211
user1537814
  • 85
  • 1
  • 3

1 Answers1

3

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)));
Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
  • -1 for propagating setXXSize. Whatever the problem, that's _not_ the way to go in Swing, for some reasons see http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi/7229519#7229519. Instead, override getMaximum to return something reasonable (JTextField is buggy in that it returns MAX_VALUE for its height, which is simply crazy for a single line of text...) – kleopatra Jul 21 '12 at 16:42
  • @kleopatra thats no reason to downvote my answer, my answer precisly answers the question as to why you cant chain when something returns void. Leave your suggestions as comments on the original post informing the user but theres no reason to downvote me what so ever. – Jon Taylor Jul 21 '12 at 18:53
  • @kleopatra obviously you don't understand the concept of answering someones question. I have answered the question which was asked, I have not gotten anything wrong on it either. I have not given any bad advice, nor have I gotten any code wrong. Therefore there is not a single reason to be downvoted. As I said if you want to help the user then leave a comment under his question describing why you feel the method he is using can be improved and leave it at that, downvoting for this reason is frankly idiotic. Id have thought someone with so much rep would have a grasped SO by now. – Jon Taylor Jul 21 '12 at 22:34