How to make non-border arrow buttons with Java Swing?

Tags: , ,



I’m using Java Swing to make a UI and the idea is to make it look like the native OS (in this case, Windows). I’ve used:

setLookAndFeel(getSystemLookAndFeelClassName());

And everything is good so far, except for one little detail. I’m trying to use the arrow buttons to hide/show a JTextArea like the ones described in MS’s documentation, the ones with no border as shown here:

enter image description here

I’ve tried using BasicArrowButton as shown below:

BasicArrowButton arrowButton = new BasicArrowButton(EAST);
        arrowButton.addActionListener((e) -> {
            if (textArea.isVisible()) {
                textArea.setVisible(false);
                arrowButton.setDirection(EAST);
            } else {
                textArea.setVisible(true);
                arrowButton.setDirection(SOUTH);
            }
        });

But I only get the ones with borders, as shown here:

enter image description here

I’ve already tried playing around with borders and backgrounds but had no luck.

Is there a neat way to get this working?

Thanks.

Answer

Use the setBorderPainted method.

You don’t need to use BasicArrowButton; you can use a regular JButton, and thus adhere to the current look-and-feel:

JButton leftButton = new JButton("u25c2");
JButton rightButton = new JButton("u25b8");
JButton upButton = new JButton("u25b4");
JButton downButton = new JButton("u25be");

leftButton.setBorderPainted(false);
rightButton.setBorderPainted(false);
upButton.setBorderPainted(false);
downButton.setBorderPainted(false);

(Those characters are the “small arrow” characters from the Geometric Shapes block of the Unicode specification.)

You probably also want to hide the focus outline and enable rollover:

leftButton.setFocusPainted(false);
rightButton.setFocusPainted(false);
upButton.setFocusPainted(false);
downButton.setFocusPainted(false);

leftButton.setRolloverEnabled(true);
rightButton.setRolloverEnabled(true);
upButton.setRolloverEnabled(true);
downButton.setRolloverEnabled(true);

Alternatively, instead of calling setRolloverEnabled, you may want to add each button to a JToolBar, which will enable rollover, and in some look-and-feels, will leave the button transparent unless the mouse is rolled over it.



Source: stackoverflow