【问题标题】:Java JComponent doesn't refreshJava JComponent 不刷新
【发布时间】:2013-05-09 21:42:34
【问题描述】:

我的班级组件有问题。问题是我的椭圆没有改变它们的颜色。 if 函数在 Counter 类中观察 OVF 标志。当 OVF=true 时,椭圆应该是红色的,当 OVF=false 时,椭圆应该是白色的。在我的 GUI 中,我只能看到红色椭圆(即使 OVF=false)。我尝试添加 repaint() 命令,但红色椭圆只开始闪烁。这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.util.Observable;


public class Komponent extends JComponent
{
Counter counter3;
public Komponent()
{
    counter3=new Counter();
}
public void paint(Graphics g) 
{
 Graphics2D dioda = (Graphics2D)g;
 int x1 = 85;
 int x2 = 135;
 int y = 3;
 int width = (getSize().width/9)-6;
 int height = (getSize().height-1)-6;

 if (counter3.OVF = true)
 {
 dioda.setColor(Color.RED);
 dioda.fillOval(x1, y, width, height);
 dioda.fillOval(x2, y, width, height);
 }
if (counter3.OVF = false)
{
 dioda.setColor(Color.WHITE);
 dioda.fillOval(x1, y, width, height);
 dioda.fillOval(x2, y, width, height);
}
}
public static void main(String[] arg)
{
 new Komponent();
}
}

该代码有什么问题?

【问题讨论】:

  • 不要覆盖paint,建议您改用paintComponent。您还应该调用 super.paintComponent (或 super.paint 在您的情况下)。查看Custom Painting了解更多详情
  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing colors components jcomponent


【解决方案1】:

如果应该是:

if (counter3.OVF == true) { // watch out for = and ==
    // red
}
if (counter3.OVF == false) {
    // white
}

或者更简单:

if (counter3.OVF) {
    // red
} else {
    // white
}

或者最简单的:

dioda.setColor(counter3.OVF ? Color.RED : Color.WHITE);
dioda.fillOval(x1, y, width, height);
dioda.fillOval(x2, y, width, height);

【讨论】:

  • 谢谢你,你是对的。但是现在椭圆还是白色的,也许我应该添加 repaint() 函数。
  • 您的所有答案都很好,谢谢 :) 但我仍然只能看到白色椭圆 :(
  • @user2283763 在paint 中尝试System.out.println(counter3.OVF);,检查counter3.OVF 的值。
  • 我知道了,当我数到它溢出时,标志 OVF 设置为 true
猜你喜欢
  • 2013-12-08
  • 2018-08-26
  • 2017-11-10
  • 1970-01-01
  • 2013-10-07
  • 2011-05-09
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
相关资源
最近更新 更多