Extending for Behavior

Sometimes you have to extend
to get the behavior you want...

    private void createButtons() {
        oneButton = new JButton("One");
        twoButton = new JButton("Two");
        treButton = new JButton("Tre");     

        // This doesn't work with
        // some layout managers; 
        // they won't respect it.

        Dimension size = oneButton
                           .getPreferredSize();
        size.width = 200;

        oneButton.setMinimumSize(size); 
        twoButton.setMinimumSize(size); 
        treButton.setMinimumSize(size); 
    }

...you could create a named subclass...

    class WideButton extends JButton {
        public WideButton(String text) {
            super(text);
            setBorder(BorderFactory
                     .createLineBorder(Color.BLUE, 2));
        }
        public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            size.width = 200;
            return size;
        }
    }

...or use an anonymous inner class.

    private JButton createWideButton(String text) {
        JButton button = new JButton(text) {
            public Dimension getMinimumSize() {
                Dimension size = super.getMinimumSize();
                size.width = 200;
                return size;
            }
        };
        button.setBorder(BorderFactory
                     .createLineBorder(Color.BLUE, 2));
        return button;
    }