有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让这个定制的JButton工作?

我看了这么多线索,但没有一条能帮到我。 这是我的代码:

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时是否不允许这样做,但如果不允许,我不知道如何修复它。有人有解决办法吗


共 (1) 个答案

  1. # 1 楼答案

    一个主要问题是:没有将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方法
    • 在覆盖中调用super的paintComponent方法
    • 覆盖组件的getPreferredSize
    • 不要忽略传递到构造函数参数中的字符串。你可能想把它传递给super的构造函数
    • 如果不使用继承来做任何你想做的事情,也就是说,不扩展JButton,你可能会好得多。如果你能给我们更详细的整体问题,我们可以提供帮助