简体   繁体   中英

How to make Round JButtons in Java

First, I am a Web Developer and a novice Java programmer. My boss is asking me to make this button in an application:

在此输入图像描述

My custom button class must extend JButton or BasicButtonUI so that it can be reused.

I did some research on Stack Overflow, but I did not understand the answers, especially with the time restraints from my boss.

You should create your own component for this.

Override the paintComponent method on a JPanel, and inside the paintComponent method draw (ie fill) a rounded rectangle2D in the color gray :

RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(x, y, w, h, 10, 10);
g.fill(roundedRectangle);

(The last two values determine the curvature. Play around until you get what you want)

Now move the x,y and reduce width and height so that when you draw the next rectangle, it sits inside the gray rectangle. Set the graphics color to blue then do something like this :

RoundRectangle2D roundedRectangle2 = new RoundRectangle2D.Float(x + 5, y + 5, w - 10, h - 10, 10, 10);
g.fill(roundedRectangle2);

You will also need to add text. Adding text requires an x and y position. The exact x and y position can be tricky to calculate, so you may need to use FontMetrics to get some more information about the rectanglar shape of the string. Fontmetrics has methods like stringWidth() and getHeight() which will help you determine what your x and y should be.

g.drawString("Click Me", x, y);

Finally you need to have a mouse motion listener on your panel. The listener needs to find when the mouse is over the button and then redraw the component.

Your rectangle can be cast to a shape object, and a calculation can be made as to whether the mouse is in the shape. Eg :

shape.contains(x,y)

If it contains, change the color, then call repaint() or updateUI() on the panel.

Note: your color object should be kept as a class level field in the class, so that it can be changed via the mouseover.

Hope this helps!

If you don't want to draw the images by yourself using the graphics API or you can't becaue the images come from a graphic designer, than you can use them as ImageIcon objects and use setRolloverIcon() and setIcon() .

In this case I would do it this way

class ButtonRollover {

    private String normalImagePath;
    private String rolloverImagePath;

    public ButtonRollover(String normalImagePath, String rolloverImagePath) {
        this.normalImagePath = normalImagePath;
        this.rolloverImagePath = rolloverImagePath;
    }

    public void apply(AbstractButton abstractButton) {
        abstractButton.setBorderPainted(false);
        abstractButton.setBackground(new Color(0, 0, 0, 0));
        abstractButton.setRolloverIcon(createImageIcon(rolloverImagePath));
        abstractButton.setIcon(createImageIcon(normalImagePath));
    }

    private ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
}

and than use it. Eg

public class Main extends JFrame {

    public static void main(String[] args) {
        Main main = new Main();
        main.setBackground(Color.WHITE);
        main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        main.setSize(640, 480);

        Container contentPane = main.getContentPane();

        ButtonRollover buttonRollover = new ButtonRollover("/bt_normal.png",
                "/bt_hover.png");

        JButton btn = new JButton();
        buttonRollover.apply(btn);

        contentPane.add(btn);
        main.setVisible(true);
    }
}

Just put the image files in the classpath.

There are ways to do it.

1) JButton has inbuilt API setIcon. You could set ImageIcon here.

2) You could add mouse listener (Mouse entered, Mouse exited) change the icons to the needed ones.

3) Make a button round - Refer for creating the curvy buttons.

public class Main extends JFrame {

    public static void main(String[] args) {
        Main main = new Main();
        main.setBackground(Color.WHITE);
        main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        main.setSize(640, 480);

        Container contentPane = main.getContentPane();

        ButtonRollover buttonRollover = new ButtonRollover("/bt_normal.png",
                "/bt_hover.png");

        JButton btn = new JButton();
        buttonRollover.apply(btn);

        contentPane.add(btn);
        main.setVisible(true);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM