1

I'm trying to set a multi-line text to a JButton, I googled about it and I found that I must use HTML for that, so here is my code :

jButton1.setText("<html>Ajouter une commande<br>nexterne à partir d'une<br>commande interne</html>");

This JButton is contained by a JToolBar. When I run the program, the button is expanded when the JFrame is expanded too; and when I resize the the JFrame the button is resized too.

Here is an image when the JFrame is expanded :

enter image description here

and here when I resize the JFrame :

enter image description here

You can notice that the button, which is called Vérifier le stock, doesn't change it's size after resizing the JFrame and this is how I want my button to act. I also want the button to take exactly the size of its text.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Aimad Majdou
  • 563
  • 4
  • 13
  • 22
  • 3
    I'm not sure how the HTML works in terms of setting the preferred size of the button. But once you determine the preferred size you will then need to set the minimum and maximum size of the button equal to the preferred size. This should prevent the layout manager of the toolbar from changing the size of the button. – camickr Jun 08 '13 at 23:04
  • 1
    See [*How to Use BoxLayout*](http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#size) for examples of @camickr's suggestion. – trashgod Jun 09 '13 at 00:54
  • 1
    Or try your hands on [GridBagLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html). Using `GridBagLayout` you can restrict how `JComponent` will react to resize of the parent container. Here is a small [example](http://stackoverflow.com/a/11166903/1057230) – nIcE cOw Jun 09 '13 at 03:25
  • 1
    I just set the minimum and maximum size of the button as @camickr has suggested, and it works fine :) – Aimad Majdou Jun 09 '13 at 10:03

1 Answers1

3

The default layout of JToolBar is BoxLayout. As an alternative, consider another layout that relies on the component's preferred size, such as FlowLayout. There's an example here.

Addendum: If you want to stay with the default BoxLayout, follow @camickr's suggestion regarding the minimum and maximum size, as shown in How to Use BoxLayout: Specifying Component Sizes.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    If this is not helpful, please edit your question to include an [sscce](http://sscce.org/) that shows your approach. You can access posted images via `URL`, as shown [here](http://stackoverflow.com/a/10862262/230513); use `UIManager` icons, as shown [here](http://stackoverflow.com/a/12228640/230513); or use synthetic images as shown [here](http://stackoverflow.com/a/15982915/230513). – trashgod Jun 08 '13 at 23:14
  • I just set the minimum and maximum size of the button as @camickr has suggested, and it works fine :) – Aimad Majdou Jun 09 '13 at 10:03