如何向预先存在的Java组件添加新功能?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何向预先存在的Java组件添加新功能?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2526字,纯文字阅读大概需要4分钟。
内容图文
![如何向预先存在的Java组件添加新功能?](/upload/InfoBanner/zyjiaocheng/746/16529a04b3624f6aa82096b7019eba02.jpg)
为了解释这个问题我的意思,我将使用下面的代码示例.想象一下你有这个功能.
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组件添加新功能?全部内容,希望文章能够帮你解决如何向预先存在的Java组件添加新功能?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。