【问题标题】:Creating two RoundedFields, JTextField and JPasswordField创建两个 RoundedFields,JTextField 和 JPasswordField
【发布时间】:2012-08-18 18:43:11
【问题描述】:

好的,我有以下 JTextField 类。它创建一个圆形 JTextField。现在我想为我的 JPasswordField 使用相同的设置,因为我认为 JPasswordField 继承自 JTextField 我可以执行以下操作:JPasswordField new_field = new RoundField(SOME Parameters); 但这是一场大灾难。有什么方法可以使 JPasswordField 舍入而不重复代码?

    public class RoundField extends JTextField {
    public RoundField(String text, int x, int y, int width, int height) {
        setText(text);
        setBounds(x, y, width, height);
        setForeground(Color.GRAY);
        setHorizontalAlignment(JTextField.CENTER);
        setOpaque(false);
        setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
    }

    protected void paintComponent(Graphics g) {
        g.setColor(getBackground());
        g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
        super.paintComponent(g);
    }
}

P.S:如有必要,可以将 setText 移出构造函数。

【问题讨论】:

  • 在同一个问题中看到标签 'java' 和 'multiple-inheritance' 让我的眼睛很痛...... :)

标签: java inheritance multiple-inheritance


【解决方案1】:

InPursuit 是对的。你不能使用继承来解决你的问题。

但是如果使用工厂设计模式来代替呢?您将创建一个外部类来处理您当前在 RoundField 的构造函数中所做的所有 UI 修改。

例如:

class BorderUtil {

    @SuppressWarnings({ "unchecked", "serial" })
    public static <T extends JTextField> T createTextField(T field, String text, int x, int y, int width,
            int height) {

        T f = null;
        if (field instanceof JPasswordField) {
            f = (T) new JPasswordField(text) {
                @Override
                protected void paintComponent(Graphics g) {
                    g.setColor(getBackground());
                    g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
                    super.paintComponent(g);
                }
            };
        } else {
            f = (T) new JTextField(text) {
                @Override
                protected void paintComponent(Graphics g) {
                    g.setColor(getBackground());
                    g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
                    super.paintComponent(g);
                }
            };
        }

        f.setBounds(x, y, width, height);
        f.setForeground(Color.GRAY);
        f.setHorizontalAlignment(JTextField.CENTER);
        f.setOpaque(false);
        f.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
        return f;
    }
}

通过这种方式,您可以避免大部分重复,并获得清晰的信息。

要调用方法,真的很简单:

JPasswordField pf = BorderUtil.createTextField(yourPasswordField, "Text", 0, 0, 10, 10);

【讨论】:

  • 哈哈是的,我只是想创建另一个类并使用泛型。很好的答案!非常感谢!
  • 快速提问:在创建字段时,yourPasswordField 参数我该放什么?
  • 我想我明白了...我发送一个新的 JTextField() 或 JPasswordField()
【解决方案2】:

您不能更改 jpasswordfield 继承的类,所以不,如果不重复代码,就无法做到这一点。

【讨论】:

  • 有没有办法使用 Java 泛型来做到这一点?
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多