【问题标题】:Method to return a desire Component返回一个期望组件的方法
【发布时间】:2021-06-01 16:00:31
【问题描述】:

我想创建一个基于我的参数 Component 返回 JTextField/JPasswordField 的方法,并且我希望在组件初始化后覆盖paintmethod,有什么解决方案吗?
这是我的代码:

public static Component Create(int size,int x, int y, int width, int height, Component type) {
        Component element;
        if (type instanceof JTextField) {
            element = new JTextField(size);
        }else if (type instanceof JPasswordField) {
            element = new JPasswordField(size);
        }
        element{
              /**
             * 
             */
            private static final long serialVersionUID = 1L;
            @Override protected void paintComponent(Graphics g) {
                    if (!isOpaque() && getBorder() instanceof RoundedCornerBorder) {
                      Graphics2D g2 = (Graphics2D) g.create();
                      g2.setPaint(getBackground());
                      g2.fill(((RoundedCornerBorder) getBorder()).getBorderShape(
                          0, 0, getWidth() - 1, getHeight() - 1));
                      g2.dispose();
                    }
                    super.paintComponent(g);
                  }
                  @Override public void updateUI() {
                    super.updateUI();
                    setOpaque(false);
                    setBorder(new RoundedCornerBorder());
                  }
                };
                element.setBounds(x, y,width, height);
                element.setBackground(culoare);
                
        return element;
    }

【问题讨论】:

    标签: java methods overriding


    【解决方案1】:
    public static Component Create(int size , Component type){
        Component elment;
        //example of instantiation
        elment = new CustomPaintJPassword(size); // new CustomPaintJPassword
            return elment;
    }
    class CustomPaintJTextField extends JTextField{
     public CustomPaintJTextField(int columns){
         super(columns);
     }
    @Override
    public void paint(Graphics g) {
        /*
         * write paint here
         */
        super.paint(g);
    }
    }
    class CustomPaintJPassword extends JPasswordField{
    
    public CustomPaintJPassword(int columns){
        super(columns);
    }
    
    
    @Override
    public void paint(Graphics g) {
        /*
         * write Paint method here
         */
        super.paint(g);
    }
    }
    

    这允许您编写自己的绘制方法,同时仍保留 Parent 类的实现。这对你来说是一个更少的想法来实现你想要的。我强烈建议你对java多态和类扩展做一些研究。Java polymorphism

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      相关资源
      最近更新 更多