[英]How can I change label color in Java?
我在LinkList调用“ l”中设置了一组标签,我需要更改这些标签的背景颜色。 我需要在每次颜色更改之间留出2秒的间隔,因此我尝试按如下方法使用重绘方法,但它没有给我所需的结果。 请有人可以给我解决这个问题的方法吗?
public static void changeColor(LinkedList l,JFrame f){
for (int i = 0; i < l.size(); i++) {
try {
final JLabel xx = (JLabel) l.get(i);
xx.setBackground(Color.red);
f.repaint();
xx.setText("B");
System.out.println(i);
new thread().run();
xx.setBackground(Color.GRAY);
xx.setText("A");
f.repaint();
} catch (Exception ex) {
Logger.getLogger(TestView.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
JLabel是通过defalut non-Opaque
,即使您设置了backGround(whatever),也没有为myLabel.setOpaque(true);
定义myLabel.setOpaque(true);
没有为JLabel'area
着色,另一种方法是将CustomPaint与overpaintpaintComponetn paintComponetn()
,例如
import java.awt.*;
import javax.swing.*;
public class LabelBackGround {
private JFrame frame;
public LabelBackGround() {
JLabel lblWest = new JLabel();
lblWest.setPreferredSize(new Dimension(50, 150));
lblWest.setOpaque(true);
lblWest.setBackground(Color.red);
JLabel lblEast = new JLabel();
lblEast.setPreferredSize(new Dimension(50, 150));
lblEast.setOpaque(true);
lblEast.setBackground(Color.red);
frame = new JFrame();
frame.add(new CustomColoredComponents(), BorderLayout.NORTH);
frame.add(new CustomColoredComponents(), BorderLayout.SOUTH);
frame.add(lblWest, BorderLayout.WEST);
frame.add(lblEast, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LabelBackGround gridBadFrame = new LabelBackGround();
}
});
}
}
class CustomColoredComponents extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 20);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 30);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
编辑:
您张贴的空白在Swing中的Concurency方面存在太多问题, 因此必须将BackGroung Tasks
到GUI的所有输出包装到invokeLater()
并且代码块中的最后代码行将revalidate ()
和repaint()
以填充JComponents
内部可见容器
三件事:1)通过使用setBackground设置背景色应导致它使用新颜色重新绘制自身,而无需调用重新绘制(假定它是不透明的)。 2)我建议为此使用javax.swing.Timer
类。 确保您知道此类与java.util.Timer
类之间的区别。 3)调用setBackground(null)应该恢复“默认颜色”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.