简体   繁体   English

为什么我的字符串不显示在窗口中?

[英]Why isn't my string being displayed in the window?

I am trying to create a simple application that shows a red circle that when clicked displays different messages under it. 我正在尝试创建一个简单的应用程序,该应用程序显示一个红色圆圈,单击该圆圈时会显示不同的消息。 I believe that this part of the code: 我相信这部分代码:

g.drawString("DO NOT PRESS", 100, 100);

is coded correctly but no text is displayed on the window that opens. 编码正确,但打开的窗口上不显示任何文本。 Here is the full code so far: 到目前为止,这是完整的代码:

import java.awt.Graphics;

import javax.swing.JFrame;

public class BigRedButton extends JFrame {

    public BigRedButton() {

        setTitle("Big Red Button");
        setSize(500, 500);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

    public void graphics(Graphics g) {

        g.drawString("DO NOT PRESS", 100, 100);
}
    public static void main(String[] args){

        new BigRedButton();
    }
}
  1. There is no such method graphics in JFrame , so nothing is calling it. JFrame没有这样的方法graphics ,所以没有任何东西在调用它。
  2. You should avoid painting directly to top level containers, apart from everthing else, they're not double buffered and will flicker when painted. 您应该避免直接绘制到顶级容器,除了其他外,它们不是双缓冲的,并且在涂漆时会闪烁。 You should, instead, create a custom component (extending from something like JPanel ) and override it's paintComponent method. 相反,您应该创建一个自定义组件(从JPanel扩展)并覆盖它的paintComponent方法。
  3. You should take the time to read through Performing Custom Painting , Painting in AWT and Swing and 2D Graphics 你应该花点时间阅读表演自定义绘画AWT和Swing绘画以及2D图形

Also, while your reading up, you should have a read through Initial Threads 另外,在阅读时,您应该阅读初始主题

Amendment 修订

As pointed out by Andrew, you should use the @Override annotation to ensure that the method you think you are overriding is actually the method being overridden in the first place. 正如Andrew所指出的,您应该使用@Override注释来确保您认为重写的方法实际上是首先被覆盖的方法。 This would stop the program from being compiled and save lots of lost time trying to figure out why things aren't working the way you expect them. 这将阻止程序编译,并节省大量的时间,试图弄清楚为什么事情没有按照你期望的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM