问题
When dedicating a class to a particular Swing component, is it better to extend
that particular component, or construct it internally and provide a reference?
public class Foo extends JComponent{
}
OR
public class Foo{
public JComponent getComponent(){
}
}
EDIT
This is what I mean by dedicating
public class Foo{
private static Foo INSTANCE;
public static Foo getInstance(){
if(INSTANCE == null){
INSTANCE = new Foo();
}
}
public void createAndShowComponent(){
//do stuff
}
}
Inside createAndShowComponent()
, I create a JComponent
with all its components and their respective listeners without exposing the internals of the component I just created.
回答1:
+1 for Composition over extension. It makes the API much cleaner since you only expose what methods are important for your new component
回答2:
I agree with jzd it all depends.
Technically speaking, if you are dealing with GUI in my opinion it is best to build components when you need them, by extending for example JComponent. This way you can simply reuse them.
Personally I would never use the 2nd option in my class. I would only have a class return another component only if there is a very good reason for doing so, e.g. to enable user to modify a button look in your complex calendar component.
For a very simple reason each component class should know what it has this component for, and it should control the view accordingly to what is happening. Thus you would have appropriate methods.
回答3:
I would say extending it would be better. Being able to use all its properties and using it like it is that object makes it a lot simpler to use. Just my personal Opinion. Both ways are good.
If you are dedicating the entire class to it. Might as well make it that by inheritence.
回答4:
If your object IS a component, than extend it. If not, then use composition.
回答5:
It really depends on what you are doing. If you want to include your new class on a JPanel for example, you will need to extend the component. If your code can add the component to the correct place on the GUI, then you don't have to extend it.
回答6:
I would say none of them. Swing components are very (very) rich and can be customized for visualisation (L&F) and behaviour (events) in any manner. Another point is to create a group of different components and lay them out in a JPanel.
来源:https://stackoverflow.com/questions/6155743/whats-the-rule-of-thumb-regarding-swing-component-extension