要动态改变LineBorder(),您需要重写它的paintBorder()方法。
以下是关键代码片段:
lineBorder = new LineBorder(color, 7) {
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
final boolean doSimple = true;
if (doSimple) {
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
};
以下是一个教学例子:
public class LineBorder_ColorChange {
static JTextPane textPane = new JTextPane();
static JScrollPane scrollPane;
static Color color = new Color(150, 255, 243);
static Border emptyBorder = new EmptyBorder(3, 3, 4, 4);
static Border lineBorder;
static Border border;
static JButton jButton = new JButton("Change Color");
static Random random = new Random();
public static void main(final String[] args) {
final JFrame jFrame = new JFrame();
lineBorder = new LineBorder(color, 7) {
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
final boolean doSimple = false;
if (doSimple) {
g.setColor(color);
g.fillRect(x, y, width, height);
}
else {
if ((this.thickness > 0) && (g instanceof Graphics2D)) {
final Graphics2D g2d = (Graphics2D) g;
final Color oldColor = g2d.getColor();
g2d.setColor(color);
Shape outer;
Shape inner;
final int offs = this.thickness;
final int size = offs + offs;
if (this.roundedCorners) {
final int arc = offs + size;
outer = new RoundRectangle2D.Float(x, y, width, height, arc, arc);
inner = new RoundRectangle2D.Float(x + offs, y + offs, width - size, height - size, arc, arc);
}
else {
outer = new Rectangle2D.Float(x, y, width, height);
inner = new Rectangle2D.Float(x + offs, y + offs, width - size, height - size);
}
final Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD);
path.append(outer, false);
path.append(inner, false);
g2d.fill(path);
g2d.setColor(oldColor);
}
}
}
};
border = new CompoundBorder(emptyBorder, lineBorder);
scrollPane = new JScrollPane(textPane);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
color = new Color(random.nextInt(142), random.nextInt(142), random.nextInt(142));
Toolkit.getDefaultToolkit().beep();
jFrame.repaint();
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scrollPane.setBorder(border);
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jFrame.getContentPane().setLayout(new BorderLayout());
jFrame.getContentPane().add(jButton, BorderLayout.SOUTH);
jFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
jFrame.setSize(200, 200);
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
});
}
}