java根据jframe中的条件在特定区域上绘制颜色
我想通过在区域上标记颜色来指示站点的状态。Graphics2D类用于绘制颜色。它必须不断更新。我正在使用计时器,但它不工作。感谢您的帮助
import javax.swing.*;
import java.awt.*;
import redis.clients.jedis.Jedis;
public class Station1 {
public Station1(){
Gradient gradient = new Gradient();
JFrame f = new JFrame("Input Carousel");
f.setLayout(new BorderLayout());
JLabel label = new JLabel();
ImageIcon icon = new ImageIcon(getClass().getResource("images/input carousel.jpg"));
label.setIcon(icon);
gradient.add(label);
f.add(gradient);
f.pack();
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Station1();
}
});
}
class Gradient extends JPanel{
public Graphics2D g2D ;
@Override
public void paintComponent(Graphics g){
g2D = (Graphics2D)g;
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
g2D.setComposite(alphaComposite);
new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try{
Jedis jedis = new Jedis("localhost");
if(jedis.get("b1").equals("1"))
{
g2D.setColor(Color.GREEN);
g2D.fillRect(208, 172, 47, 75);
}
else if(jedis.get("b1").equals("e"))
{
g2D.setColor(Color.RED);
g2D.fillRect(208, 172, 47, 75);
}
}
catch(Exception e)
{
}
}
}).start();
}
}
}
如果我在没有定时器的情况下运行代码,它就会工作。如果我用定时器,它不会画任何颜色。 请给我建议这个问题的解决方案
# 1 楼答案
该代码有几个明显的问题:
建议:
super.paintComponent(g);
,通常在它的第一行李>例如,请查看下面的代码。请注意,我无法访问您的绝地职业(以及您使用绝地职业的原因),因此创建了一个“模拟”职业。此外,我没有访问您的图像,因此使用了此演示程序的公开图像。我也加快了你的计时器