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 (;
}
}