首页 > 编程知识 正文

字符串的占位符,java获取字段类型

时间:2023-05-03 10:56:35 阅读:150012 作者:4990

I ' mtryingtocreateaguiwithswing.myproblemis,I have a textfield,butiwantittohavea ' placeholder ' (likeinhtml ).ireadhere

sincemycodeisgeneratedifoundoutthatineedtousethe ' customcreationcode ' tooverridethecodethatwasgenerated

hereiswhatihaveputinthe ' customcreationcode ' field

new javax.swing.JTextField (

{

String test=super.getText (;

String hint='Username ';

公共语音(graphicsg ) )。

{

if(test==null||test.length ()1) )。

g.setcolor(color.red;

g.drawstring(hint,0,0 );

}

g.setcolor(color.black );

super.paint(g );

}

}

thisgeneratesthefollowingoutput

jvax.swing.jtextfield username=new javax.swing.jtextfield (

{

String test=super.getText (;

String hint='Username ';

公共语音(graphicsg ) )。

{

if(test==null||test.length ()1) )。

g.setcolor(color.red;

g.drawstring(hint,0,0 );

}

g.setcolor(color.black );

super.paint(g );

}

(;

fornowiseethetextfieldbutthereisnothinginit,maybeineedtoaddsomefunctionontosomeevent,but I am not sure。

iwouldbegratefulifanyonecouldlendahand。

解决方案

I found this on the oracle forums。

publicclasstextfieldwithpromptextendsjtextfield {

@Override

protectedvoidpaintcomponent (Java.awt.graphicsg )。

super.paintcomponent(g );

if(gettext ).isEmpty! (focus manager.getcurrentkeyboardfocusmanager ().getfocus owner (=this ) ) ) )。

graphics2dG2=(graphics2d ) g.create );

G2.setbackground(color.gray );

G2.setfont(getfont ).Derivefont ) font.italic );

G2.drawstring('zip ',5,10 ); //figure out x,yfromfont ' sfontmetricsandsizeofcomponent。

g2.dispose (;

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。