我想用图像和提示创建一些更好看的JTextFields。为此,我制作了一个覆盖paintComponent方法的装饰器。我使用装饰器的原因是我想将它应用于其他类型的JTextField,如JPasswordField。用图像和提示装饰JTextField
这是我到目前为止;
如被看见在左边的表格的问题是,即使我已经使用了一个JPasswordField中的的paintComponent似乎忽略了我认为是密码的paintComponent这大概确实的密码屏蔽符号。
所以问题是,我如何避免重复JTextFields和JPasswordFields的代码,但仍然具有不同的功能,如密码掩码。
这是装饰者代码;
public class JTextFieldHint extends JTextField implements FocusListener{
private JTextField jtf;
private Icon icon;
private String hint;
private Insets dummyInsets;
public JTextFieldHint(JTextField jtf, String icon, String hint){
this.jtf = jtf;
setIcon(createImageIcon("icons/"+icon+".png",icon));
this.hint = hint;
Border border = UIManager.getBorder("TextField.border");
JTextField dummy = new JTextField();
this.dummyInsets = border.getBorderInsets(dummy);
addFocusListener(this);
}
public void setIcon(Icon newIcon){
this.icon = newIcon;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int textX = 2;
if(this.icon!=null){
int iconWidth = icon.getIconWidth();
int iconHeight = icon.getIconHeight();
int x = dummyInsets.left + 5;
textX = x+iconWidth+2;
int y = (this.getHeight() - iconHeight)/2;
icon.paintIcon(this, g, x, y);
}
setMargin(new Insets(2, textX, 2, 2));
if (this.getText().equals("")) {
int width = this.getWidth();
int height = this.getHeight();
Font prev = g.getFont();
Font italic = prev.deriveFont(Font.ITALIC);
Color prevColor = g.getColor();
g.setFont(italic);
g.setColor(UIManager.getColor("textInactiveText"));
int h = g.getFontMetrics().getHeight();
int textBottom = (height - h)/2 + h - 4;
int x = this.getInsets().left;
Graphics2D g2d = (Graphics2D) g;
RenderingHints hints = g2d.getRenderingHints();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.drawString(hint, x, textBottom);
g2d.setRenderingHints(hints);
g.setFont(prev);
g.setColor(prevColor);
}
}
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
@Override
public void focusGained(FocusEvent arg0) {
this.repaint();
}
@Override
public void focusLost(FocusEvent arg0) {
this.repaint();
}
}
而这是我创造的领域;
JTextField usernameField = new JTextFieldHint(new JTextField(),"user_green","Username");
JTextField passwordField = new JTextFieldHint(new JPasswordField(),"bullet_key","Password");
希望我没有完全在这里错误的方向去!
谢谢!
编辑:再次看到它,很明显,调用super.paintComponent(g)将要调用JTextFields paintcomponent,但我无法看到如何解决这个问题,而无需重复代码。
你是说Border Border = BorderFactory ....只是+1 – mKorbel 2011-05-22 21:44:19
你可以创建一个CompoundBorder。使用原始边框作为外部边框,然后使用带有图标的MatteBorder作为内部边框 – camickr 2011-05-22 22:07:32
清晰直接,谢谢 – mKorbel 2011-05-22 23:03:52