我怎样才能使这个自定义 JButton 工作?

How can I make this custom JButton work?

我浏览了很多线程 - none 对我有帮助。 这是我的代码:

package myProjects;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.*;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class LukeButton extends JButton{
public static void main(String[] args){
    JFrame frame = new JFrame();
    frame.setTitle("Luke");
    frame.setSize(300, 300);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    LukeButton lb = new LukeButton("Text");
    lb.addActionListener(e->{
        System.out.println("Clicked");
    });

    frame.setVisible(true);
}
public LukeButton(String text){

}
public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D)g;

    Shape rec = new Rectangle2D.Float(10, 10, 60, 80);

    g2.setColor(Color.BLACK);
    g2.setStroke(new BasicStroke(2));
    g2.draw(rec);
    g2.setColor(Color.BLUE);
    g2.fill(rec);
    }
}

而应该存在的矩形却不存在。我不知道在扩展 JButton 时是否不允许这样做,但如果不允许,我不知道如何修复它。有人有解决办法吗?

一个主要问题:您没有将 LukeButton 实例添加到 GUI。解决方案:通过容器的add(lb)方法添加。

public static void main(String[] args) {
    LukeButton lb = new LukeButton("Text");
    JPanel panel = new JPanel();
    panel.add(lb);

    JFrame frame = new JFrame();
    frame.add(panel);

其他问题:

  • 您应该覆盖 paintComponent 方法而不是 paint 方法
  • 在override中调用super的paintComponent方法
  • 覆盖组件的 getPreferredSize。
  • 不要忽略传递给构造函数参数的字符串。您可能希望将其传递给超级的构造函数。
  • 您可能最好不要使用继承来做您想做的任何事情,也就是说,不要扩展 JButton。如果您可以向我们提供有关整体问题的更多详细信息,我们可以提供帮助。