自定义 JFrame class 按钮不加载参数,简单的错误?

Custom JFrame class button doesn't load parameters, simple mistake?

我试图创建一个更整洁的 Jframe 程序,所以我决定创建一个 CustomButton class 这样我就不必在主程序上写出所有按钮设置,但是参数不要在自定义 class.

中更改

这就是我在主菜单中创建按钮的方式 class:

    CustomButton button = new CustomButton("Hello World",2,20,5,5);
    button.addActionListener(this);
    button.setActionCommand("id:1");

    add(button);

自定义按钮 Class:

package com.ezranestel.classes;

import javax.swing.JButton;

public class CustomButton extends JButton{

private static final long serialVersionUID = 1L;
public String buttonID;



public CustomButton(String buttonText,int sizeX, int sizeY,int locationX, int locationY) {
    JButton button = new JButton(); 
    button.setName(buttonText);
    button.setSize(sizeX, sizeY);
    button.setLocation(locationX, locationY);
    System.out.println("Creating a button"+buttonText);
}
}

当 运行 控制台说它正在创建按钮时 (System.out),但它已创建并且大小和名称都没有改变。

您的问题是您的 CustomButton class 没有扩展任何东西,它只是制作了一个按钮并且没有对它做任何事情。这是您的 class 的一个版本,应该可以使用。

public class CustomButton extends JButton{
public CustomButton(String buttonText,int sizeX, int sizeY,int locationX, int locationY)  {
    super(buttonText);
    this.setSize(sizeX, sizeY);
    this.setLocation(locationX, locationY);
}

}

请参阅顶部 class 如何扩展 JButton?这使它成为 JButton 的一个版本,并创建了一个有效的按钮来执行操作。按照您设置它的方式,您创建了一个 JButton 而不对其进行任何操作,完全独立于您的 CustomButton,因此当您将 CustomButton 添加到框架时,JVM 没有关于添加什么的信息。