Java-创建自定义字段

Java-创建自定义字段,java,oop,Java,Oop,我有一个CustomTextField和CustomPasswordField类。第一个扩展了JTextField,第二个扩展了JPasswordField类。两者的内部代码相同,但只有超类不同。我怎样才能把一节课改成两节课呢?大概是这样的: class CustomTextField extends JTextField{ public CustomTextField(int col){ super(col); } @Overri

我有一个CustomTextField和CustomPasswordField类。第一个扩展了JTextField,第二个扩展了JPasswordField类。两者的内部代码相同,但只有超类不同。我怎样才能把一节课改成两节课呢?大概是这样的:

class CustomTextField extends JTextField{
      public CustomTextField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}

class CustomPasswordField extends JPasswordField{
      public CustomPasswordField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}
class InputField extends JPasswordField{
      // code and paintComponent override
}
JTextField field = new InputField();
提前谢谢

更新:

我可以这样延伸:

class CustomTextField extends JTextField{
      public CustomTextField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}

class CustomPasswordField extends JPasswordField{
      public CustomPasswordField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}
class InputField extends JPasswordField{
      // code and paintComponent override
}
JTextField field = new InputField();
。。。每次我需要这样的文本字段时,都要转换到JTextField:

class CustomTextField extends JTextField{
      public CustomTextField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}

class CustomPasswordField extends JPasswordField{
      public CustomPasswordField(int col){
             super(col);
      }

      @Override
      public void paintComponent(Graphics g){
            // Drawing custom shape with transparent color
            super.paintComponent(g);
      }
}
class InputField extends JPasswordField{
      // code and paintComponent override
}
JTextField field = new InputField();

但它的行为似乎仍然像它使用的JPasswordField*而不是字符

T是泛型类型,而不是真正的类。它只是被调用方调用您时将设置的类型的占位符。如果他打电话给你,T将是字符串

这不是你想要的,但可能是你想要的:

您可以在类型中使用继承,因此可以定义T必须与其他类相关 及


使用,您可以确保传递给您的任何类型至少是某物或从某物扩展而来的类。

您可以扩展泛型类,但不能扩展泛型类型。如果你解释一下你想用它完成什么,也许我们可以帮助你找到正确的解决方案。我该如何实现这个-实现什么?你不能。你想干什么?不要告诉我们你是如何试图解决问题的,告诉我们问题所在。JPasswordField扩展了JTextField,这样你就可以扩展JPasswordField,并且你也可以使用JTextField拥有的任何方法?编辑你的问题,以包含你的评论文本。这才是你真正要问的问题。