如何向预先存在的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); 这种模式对内存更有效,并且更加面向对象,但我个人并不认为它非常适合实用程序类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |