如何使用JButton的模型?

huangapple 未分类评论42阅读模式
英文:

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?那么我会有类似这样的代码:

  1. public final class PieceButton extends JButton {
  2. private static final long serialVersionUID = 1L;
  3. private final Piece piece;
  4. public PieceButton(Piece piece, int iconSize) {
  5. this.piece = Objects.requireNonNull(piece);
  6. setIcon(new ColorRoundIcon(iconSize, piece.getColor()));
  7. }
  8. public Piece getPiece() {
  9. return piece;
  10. }
  11. }

那么最佳(面向对象编程方面的)方法是什么?

英文:

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:

  1. public final class PieceButton extends JButton {
  2. private static final long serialVersionUID = 1L;
  3. private final Piece piece;
  4. public PieceButton(Piece piece, int iconSize) {
  5. this.piece = Objects.requireNonNull(piece);
  6. setIcon(new ColorRoundIcon(iconSize, piece.getColor()));
  7. }
  8. public Piece getPiece() {
  9. return piece;
  10. }
  11. }

So what is the best (OOP-wise) approach?

huangapple
  • 本文由 发表于 2020年4月5日 09:29:28
  • 转载请务必保留本文链接:https://java.coder-hub.com/61036947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定