java添加功能_如何向预先存在的Java组件添加新功能?

为了解释这个问题我的意思,我将使用下面的代码示例.想象一下你有这个功能.

private void fadeButton(JButton b, int timeToFade) {

//Fade code goes here

}

你如何将它作为一个可以运行的函数来实现

JButton b = new JButton("Press Me");

b.fadeButton(20000);

fadeButton现在看起来像

private void fadeButton(int timeToFade) {

//Fade code goes here

}

因为该函数是在按钮本身上声明的.

解决方法:

您可以使用新类扩展JButton,从而继承JButton的方法并添加添加自己的代码的功能:

public class FadingButton extends JButton {

//Constructors go here

private void fadeButton(int timeToFade) {

//Fade code goes here

}

}

您还可以使用另一个类来装饰JButton:

public class JButtonDecorator {

private JButton btn;

//Constructor here

private void fadeButton(int timeToFade) {

//Fade code goes here, hiding the held button

}

//getter and setter method for button

}

或者,如果您想要许多不同的方式来影响您的UI,您可以创建一个实用程序类,类似于上面的:

//You could use a factory pattern to make this a singleton instead of having static methods

public abstract class UIUtils {

private UIUtils{} //Don't instantiate this class

public static void fadeComponent(JComponent toFade) {

//Fade code goes here

}

//Other static utility methods

}

编辑:利用这些模式.扩展类是不言自明的,是简单继承的一个例子,所以它只是JButton的问题btn = new FadingButton();例如.以下是其他人:

要使用装饰器,请将其实例化为与您现在使用的按钮相同的范围.例如:

JButton myButton = new JButton();

//Customize button and add to UI

JButtonDecorator jbDec = new JButtonDecorator(myButton);

jbDec.fadeButton(20000);

虽然按钮是装饰器的一个字段,但它在UI中会正常运行.装饰器只是用有用的方法包装类,例如fadeButton方法.

要使用实用程序类,有两种方法.一个是两个用静态方法创建一个抽象类(如上所述),有些人认为它是坏形式,但它对简单程序有好处:

UIUtils.fadeComponent(myButton); //It's just that simple!

//The UIUtils class itself is never instantiated.

//All the methods are static, so no instances are needed.

或者,如果您想要更高级的方法,请将实用程序类设为单例.这会将实用程序类更改为:

public class UIUtils {

UIUtils singleton;

private UIUtils{} //Don't instantiate this class publicly

public static UIUtils getInstance() {

if(singleton==null) //This is the first time the method is called

singleton = new UIUtils();

return singleton; //Return the one instance of UIUtils

}

public void fadeComponent(JComponent toFade) {

//Fade code goes here

}

//Other utility methods

}

然后,您将在类级别声明UIUtils对象以在UI中使用:

UIUtils uiUtil = UIUtils.getInstance();

在代码的某处:

uiUtil.fadeComponent(myButton);

这种模式对内存更有效,并且更加面向对象,但我个人并不认为它非常适合实用程序类.

标签:java

来源: https://codeday.me/bug/20190727/1554565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值