0

I have a jbutton in a Jpanel which has FlowLayout with trailing alignment. This code actually works in ubuntu environment but when i run it in the centos enviornment, text does not fit on the button.

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
myButton = new JButton("My Text");
buttonPanel.add(myButton);

Then I add the following lines:

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
myButton = new JButton("My Text");
int width=myButton.getFontMetrics(exportButton.getFont()).stringWidth(myButton.getText());
int height=myButton.getFontMetrics(myButton.getFont()).getHeight()+10;
myButton.setPreferredSize(new Dimension(width+30, height));
buttonPanel.add(myButton);

This additional lines helped but it seems, the solution is not good.

canromero
  • 99
  • 3
  • 12
  • 3
    Setting preferred size is just going to make this worse. Try to remove all calls to setPreferredSize and rely on XxxUI's and LayoutManagers to determine preferred size's. – Guillaume Polet Nov 27 '12 at 12:41
  • how can i use UI ?? is there any example? – canromero Nov 27 '12 at 12:58
  • You don't have to do anything. XxxUI's are automatically installed when creating a Swing component. You could implement your own if you wanted but I would rather try to avoid such complex and lengthy process. Remember, get rid of all your calls to `setPreferredSize()` and you should be fine on any platform and any L&F. – Guillaume Polet Nov 27 '12 at 14:39
  • when i get rid off setPreferredSize() like in the above. then it is fine in ubuntu but in centos text on the button can not be read fully. For ex: in ubuntu I see text as "My Text". but in centos it appears like "My Tex..." – canromero Nov 27 '12 at 18:40
  • Buttons have insets and margins which you have not taken into account, this is one (of the many) reasons why setXxxSize is not recommended – MadProgrammer Nov 27 '12 at 19:01

2 Answers2

3
  • FlowLayout by default acceptiong PreferredSize that came from JComponents

  • JButton by default dont need to re_calculate of PreferredSize, let's job for proper LayoutManager, FlowLayout accepting only PreferredSize

  • most important is to call pack() before setVisible(true) (last code lines in constructor) for container (JFrame, JDialog...)

  • every JComponent can returns own proper PreferredSize, then there no reason override or set this value, this could be different in some cases for empty JPanel (pro custom painting) or JScrollPane

mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

This is most likely to happen because of different system fonts being used. You can try to override the native look and feel with a custom one. You may find this link useful.

svz
  • 4,516
  • 11
  • 40
  • 66