如何调用以 Graphics g 作为参数的方法?

How do I call a method which has Graphics g as its parameters?

所以我正在制作一个游戏,在有人获胜后,我想要一个 运行 的方法,它显示 "x has won" 或 "y has won"。现在我的问题是,如果我制作方法来绘制包含胜利消息的字符串,那么我的 IDE 不允许我这样做,因为我显然不能 运行 以 Graphics g 作为参数的方法.

有没有其他方法可以在 JFrame 屏幕上显示消息?

这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;`  
//nothing wrong here :P  
public class Demonstration extends JFrame {
    private JButton b1;
    private JButton b2;
    public Demonstration () {
        //My constructor
        JPanel panel = new JPanel();
        panel.setLayout(null);
        add(panel);
        handler h = new handler();
        b1 = new JButton("yes");
        b2 = new JButton("no");
        //A sub - class to handle events. Created below
        b1.setBounds(34, 34, 34, 34);
        //random
        panel.add(b1);
        b1.addActionListener(h);
        b2.setBounds(56, 56, 56, 56);
        // random again
        panel.add(b2);
        b2.addActionListener(h);
        setTitle("Demonstration");
        setBackground(Color.BLACK);
        setDefaultCloseOperation(3);
        setSize(720, 720);
        setVisible(true);
    }
}

那是我的面板。

public static void main (String[] args) {
     new Demonstration();
}

所以让我们说我稍后制作了处理程序 class 我希望它成为 运行 一段代码,其中包含点击按钮的 if / else (.getSource() ) 并且我想使用 Graphics 重新设计界面并打印出胜利消息,我该怎么做?

当然,您可以 运行 将 Graphics 作为参数的方法。任何 Swing 应用程序都会这样做。您也可以手动执行此操作,但在那种情况下,问题通常是如何获得正确的 Graphics 实例以在您想要绘制的位置进行绘制。

有时您想做的是扩展一些 JComponent(通常是 JPanel)并覆盖它的 paintComponent(Graphics) 方法。该方法接收到的 Graphics 对象适用于在该组件上绘制。然后确保该组件的一个实例位于应用程序的顶级 windows.

之一管理的组件中

或者,有时可能适合更改不同组件中的 数据 ,例如 JLabelJButton 的文本,或者JTextArea.

的内容

还要考虑显示某种风格的公告消息,弹出对话框可能是合适的。有多种方法可以构建和显示这样的对话框,但 JOptionPane 提供了一些可能对您有用的快捷方式。

Is there any other way to display a message on a JFrame screen?

不要尝试自定义绘画。

我会使用 JOptionPane.

阅读 Swing 教程中有关如何制作对话框的部分以了解更多信息。

您将使用简单的 JOptionPane.showMessageDialog(...) 方法。