英文:
How do I use a JButton's Model?
问题
Java Swing基于(大致的)MVC概念构建,其UI组件通常与某种模型相关联。
那么JButton
的模型是什么?我对Java Swing不太熟悉。它是javax.swing.DefaultButtonModel
类的实例吗?还是javax.swing.ButtonModel
接口的实现?
此外,一些人表示我们应该很少扩展Java Swing组件。
因此,在这种情况下,我在一个简单的颜色猜测游戏中引入了“方块按钮”(piece button)的概念,它是一个与Piece
关联的按钮(piece只是表示单一颜色的元素,我也可以使用Color
)。它不应该扩展JButton
,因为它不会修改其任何功能。在这种情况下,使用组合也似乎没有意义。
那么我该怎么办?我应该将Piece
添加到按钮的模型中吗?如果是这样,应该如何做到?
还是应该忽略之前的说法,反而扩展JButton
?那么我会有类似这样的代码:
public final class PieceButton extends JButton {
private static final long serialVersionUID = 1L;
private final Piece piece;
public PieceButton(Piece piece, int iconSize) {
this.piece = Objects.requireNonNull(piece);
setIcon(new ColorRoundIcon(iconSize, piece.getColor()));
}
public Piece getPiece() {
return piece;
}
}
那么最佳(面向对象编程方面的)方法是什么?
英文:
Java Swing builds on the (approximate) concept of MVC and its UI components usually have some kind of Model associated to them.
So what is the Model for a JButton
? I'm not very familiar to Java Swing. Is it an instance of the javax.swing.DefaultButtonModel
class? Or an implementation of the javax.swing.ButtonModel
interface?
Also, some people say we should rarely extend a Java Swing component.
So within that spirit I have the concept of a "piece button" in a simple color-guessing game which is a button tied to a Piece
(the piece simply represents a single color, I could as well have used Color
instead). It should not extend JButton
because it is not modifying any of its functionality. Also using composition doesn't seem to make sense in that case.
So what should I do? Should I add Piece
to the button's Model? If so, how should I do that?
Or should I ignore the previous statements and extend JButton
instead? I would then have something like this:
public final class PieceButton extends JButton {
private static final long serialVersionUID = 1L;
private final Piece piece;
public PieceButton(Piece piece, int iconSize) {
this.piece = Objects.requireNonNull(piece);
setIcon(new ColorRoundIcon(iconSize, piece.getColor()));
}
public Piece getPiece() {
return piece;
}
}
So what is the best (OOP-wise) approach?
专注分享java语言的经验与见解,让所有开发者获益!
评论