This is because after drawing the border you did not clear your graphic settings.
Basically, Swing uses the same graphics that you received in the method paintBorderto draw everything that lies on the panel. Therefore, if you set the stroke, composite, font, color, etc., Be sure to return the previously used settings, otherwise you may see such unexpected behavior.
, , , // , , .
, , , , . , , , 100% , ( , ).
:
public class Box extends JPanel
{
public Box ()
{
super ();
DashedBorder dashedBorder = new DashedBorder ();
this.setBorder ( new TitledBorder ( dashedBorder, "title", TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION ) );
this.setLayout ( new GridLayout ( 5, 1 ) );
for ( int i = 1; i <= 15; i++ )
{
this.add ( new JCheckBox ( "" + i ) );
}
}
class DashedBorder extends AbstractBorder
{
@Override
public void paintBorder ( Component comp, Graphics g, int x, int y, int w, int h )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setColor ( Color.black );
final Stroke os = g2d.getStroke ();
g2d.setStroke ( new BasicStroke ( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{ 5 }, 0 ) );
g2d.drawRect ( x, y, w - 1, h - 1 );
g2d.setStroke ( os );
}
}
public static void main ( String[] args )
{
JFrame frame = new JFrame ();
JPanel p = new JPanel ();
p.setLayout ( new BorderLayout () );
Box box = new Box ();
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setSize ( 400, 400 );
frame.setContentPane ( p );
p.add ( box, BorderLayout.CENTER );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
}
, , , . , "" .
, , /, , :
public static Stroke setupStroke ( final Graphics2D g2d, final Stroke stroke )
{
return setupStroke ( g2d, stroke, true );
}
public static Stroke setupStroke ( final Graphics2D g2d, final Stroke stroke, final boolean shouldSetup )
{
if ( shouldSetup && stroke != null )
{
final Stroke old = g2d.getStroke ();
g2d.setStroke ( stroke );
return old;
}
else
{
return null;
}
}
public static void restoreStroke ( final Graphics2D g2d, final Stroke stroke )
{
restoreStroke ( g2d, stroke, true );
}
public static void restoreStroke ( final Graphics2D g2d, final Stroke stroke, final boolean shouldRestore )
{
if ( shouldRestore && stroke != null )
{
g2d.setStroke ( stroke );
}
}
, :
final Stroke stroke = GraphicsUtils.setupStroke ( newStroke );
GraphicsUtils.restoreStroke ( g2d, stroke );