我是一名高中 AP 计算机科学学生,正在使用 Java 进行独立学习项目。我选择为钢琴初学者编写一个应用程序,其中计算机显示键盘的图片,并突出显示一个音符。然后,用户选择与突出显示的键对应的注释名称,计时器会计数到零,然后报告用户的分数。
我的 View 即将完成,但我无法在屏幕上显示计时器。
计时器由模型创建,并在单独的线程中运行,每秒指示 Controller 更新计时器,该计时器调用 View 中的方法,该方法又在对象 TimerUpdateComponent 中设置一个值,然后验证以显示新文本。
至少,理论上是这样。计时器工作完美 - 每秒打印到控制台,就像我要求的那样 - 但当我运行 View 时,什么也没有出现。因此,我想我会做大师所做的事情并找出差异,所以我直接从 Horstmann 和 Cornell 的 [I]Core Java - Volume I[/I] 复制了这段代码,它应该显示字符串“Hello, World!”在面板的中心:
public void paintComponent(Graphics g){<br>
Graphics2D g2 = (Graphics2D) g;<br>
String message = "Hello, World!";<br>
Font f = new Font("Serif",Font.BOLD,36);<br>
g2.setFont(f);
//measure the size of the message
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds(message, context);
//set (x,y) to top-left corner of text
double x = (getWidth() - bounds.getWidth())/2;
double y = (getHeight() - bounds.getHeight())/2;
//add ascent to y to reach the baseline
double ascent = -bounds.getY();
double baseY = y + ascent;
//draw the message
g2.drawString(message, (int)x, (int)y);
g2.setPaint(Color.LIGHT_GRAY);
//draw the baseline
g2.draw(new Line2D.Double(x, baseY,x - bounds.getWidth(), baseY));
//draw the enclosing rectangle
Rectangle2D rect = new Rectangle2D.Double(x,y,bounds.getWidth(), bounds.getHeight());
g2.draw(rect);
}
}
令我惊讶的是,这段代码也没有显示字符串!我认为该字符串对于相当小的面板来说可能太大了,所以它只显示了空白,但我尝试将字体大小更改为 10,但这也不起作用。
所以现在我真的:chomp: ing。我唯一能想到的是这本书已经过时了(Sun 自 2008 年以来是否改变了 Swing 的工作方式?我对此表示怀疑。)或者犯了严重的编码错误(在第八版中?)所以我创建了一个单独的文件并从书中复制了整个 .java 文件,效果很好。
请帮助我!
此外,这是我的原始方法主体,以防您想查看:
String message = time/60+":"+time%60;<br>
Graphics2D g2 = (Graphics2D) g;<br>
FontRenderContext context = g2.getFontRenderContext();<br>
Rectangle2D bounds = g2.getFont().getStringBounds(message, context);<br>
double x = (getWidth() - bounds.getWidth()) / 2;<br>
double y = (getHeight() - bounds.getHeight() / 2);<br>
g2.drawString(message,(int)x,(int)y);<br>
最佳答案
第一次重新绘制后,您将在灰色背景上绘制灰色文本。
但是为什么不只使用 JLabel 并在每次计时器触发时调用 setText,而是自己完成所有这些操作?
关于java - JComponent 不显示文本 - Swing 正在攻击我!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2039436/