创建两个圆角字段,JTextField 和 JPasswordField



好的,我有以下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);
    }
}

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

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);

您无法更改 jpasswordfield 继承的类,因此不,如果不重复代码,就无法执行此操作。

最新更新