Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Don't use <a href="https://stackoverflow.com/q/7229226/230513"><code>setPreferredSize()</code></a> when you really mean to override <a href="https://stackoverflow.com/a/7229662/230513"><code>getPreferredSize()</code></a>. <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html" rel="nofollow noreferrer"><code>BoxLayout</code></a> works well for this: "For a top-to-bottom box layout, the preferred width of the container is that of the maximum preferred width of the children." In the example below, <code>BorderLayout.LINE_END</code> adopts the container's preferred width. Each button overrides <code>getMaximumSize()</code> to effectively remove the upper limit on the button's width. The result works well across platforms.</p> <p><img src="https://i.stack.imgur.com/2FnDL.png" alt="image"></p> <pre><code>import java.awt.*; import javax.swing.*; /** * @see https://stackoverflow.com/a/20085489/230513 */ public class TestViewer { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new ButtonPanel(), BorderLayout.LINE_END); frame.pack(); frame.setSize(500, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private static class ButtonPanel extends Box { public ButtonPanel() { super(BoxLayout.Y_AXIS); this.add(createButton("Button 1")); this.add(createButton("Button 2")); this.add(createButton("Long Button 3")); this.add(createButton("Button 4")); this.add(createButton("Button 5")); } private JButton createButton(String name) { final JButton b = new JButton(name) { @Override public Dimension getMaximumSize() { return new Dimension( Short.MAX_VALUE, getPreferredSize().height); } }; b.setAlignmentX(0.5f); return b; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload