如何制作自定义JButton类?

时间:2017-05-19 08:47:28

标签: java swing jbutton

您正在搜索使用Java Swing制作自定义按钮的解决方案。 我有一个例子它应该如何,但它不显示按钮文本。有人知道错误在哪里吗?

这是JButton Class

    package custombutton;

import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.border.LineBorder;

public class CustomButton extends JButton implements MouseListener {

    Dimension size = new Dimension(206, 30);

    boolean hover = false;
    boolean click = false;
    String text;

    public CustomButton(String text) {
        setVisible(true);
        setFocusable(true);
        setContentAreaFilled(false);
        setBorderPainted(true);
        setBorder(new LineBorder(Color.BLACK, 3));

        setButtonText(text);


        addMouseListener(this);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);


        g.setColor(new Color(255, 255, 255));

        g.fillRect(0, 0, 206, 30);


        g.setFont(Font.decode("arial-24"));

        FontMetrics metrics = g.getFontMetrics();

        int width = metrics.stringWidth(getButtonText());

        g.drawString(text, 103 - width / 2, 15);

    }

    @Override
    public Dimension getPreferredSize() {
        return size;
    }

    @Override
    public Dimension getMaximumSize() {
        return size;
    }

    @Override
    public Dimension getMinimumSize() {
        return size;
    }

    public void setButtonText(String text) {
        this.text = text;
    }

    public String getButtonText() {
        return text;
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        hover = true;
    }

    @Override
    public void mouseExited(MouseEvent e) {
        hover = false;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        click = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        click = false;
    }

    @Override
    public void mouseClicked(MouseEvent e) {}
}

这里是Main:

package custombutton;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

    public Main() {
        JPanel panel = new JPanel();

        setTitle("Custom Button");

        setSize(400, 100);
        setResizable(false);

        panel.setBackground(Color.GRAY);
        CustomButton button = new CustomButton("Hallo");
        panel.add(button);
        add(panel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

}

1 个答案:

答案 0 :(得分:2)

我认为问题出在setButtonText(text);,而不是你应该使用setText(text);