Problem in repaint for Custom Component
I have created a custom JPasswordField component.
Its actually a passwordfield with elliptical shape and with black background and white forground.
The problem is it doesnt repaint the component correctly, and show a white color of the background while typing in it.
Interestingly when i put repaint() in paintComponent method it solves the problem but it makes the application very slow, as it repaints continuously.
My code is as follows:
publicclass KioskPinCodeFieldextends JPasswordField{
private Shape shape;
private Color fieldColor = Color.BLACK;
private Color textColor = Color.WHITE;
privateint maxChars = 4;
privateint fieldLength = 12;
public KioskPinCodeField(){
setOpaque(false);
setFocusable(true);
setColumns(fieldLength);
setSize(new Dimension(400, 56));
setPreferredSize(new Dimension(400, 56));
setDocument(new InputFilter(maxChars, 0, InputFilter.DIGITS,false));
setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
setForeground(textColor);
setFont(new java.awt.Font("SansSerif", 1, 28));
repaint();
}
// Paint the round background and label.
protectedvoid paintComponent(Graphics g){
// get damaged region
java.awt.Rectangle clipRect = g.getClipBounds();
int clipx = clipRect.x;
int clipy = clipRect.y;
int clipw = clipRect.width;
int cliph = clipRect.height;
g.setColor(fieldColor);
g.fillRoundRect(clipx, clipy, clipw, cliph, 25, 25);
// This call will paint the label and the focus rectangle.
super.paintComponent(g);
}
// Paint the border of the button using a simple stroke.
protectedvoid paintBorder(Graphics g){
g.setColor(fieldColor);
g.drawRoundRect(0, 0, getSize().width-1, getSize().height-1, 25, 25);
}
// Hit detection.
publicboolean contains(int x,int y){
// If the button has changed size, make a new shape object.
if (shape ==null || !shape.getBounds().equals(getBounds())){
shape =new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
}

