0

I'm trying to display a message in a JPanel. I've used the drawString() function of the Graphics class. Here's my code :

public class Frame {
    JFrame frame;
    JPanel panel;
    Graphics graph;

    Frame() {
        frame = new JFrame();
        panel = new JPanel();

        frame.setTitle("My wonderful window");
        frame.setSize(800, 600);
        frame.ContentPane(panel);
        frame.setVisible(true);
    }

    void displayMessage(String message) {
        graph = new Graphics();

        graph.drawString(message, 10, 20);
    }
}

I've this error : error: Graphics is abstract; cannot be instantiated

4

2 回答 2

3

覆盖JPanel'paintComponent(Graphics g)方法。在该方法中,您可以访问有效的 Graphics 实例。对每种油漆调用的方法。

但可能最好JLabel在面板中添加一个。标签最初没有文本,当您有消息时,只需调用setText(messageText)标签。

于 2013-10-09T07:40:05.203 回答
0

您应该为您的JFrameand创建子类JPanel,并覆盖您想要的方法。您可以尝试以下方法:

package test;

import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Frame extends JFrame {

    public static final String message = "HELLO WORLD!!!";
    
    public class Panel extends JPanel {
        
        public void paintComponent(Graphics graph) {
            graph.drawString(message, 10, 20);
        }
        
    }
    
    public Frame() {
        
        Panel panel = new Panel();
        this.setTitle("My wonderful window");
        this.setSize(800, 600);
        this.setContentPane(panel);
        this.setVisible(true);
        
    }
    
    public static void main(String[] args) {
        
        new Frame();
        
    }

}

此外,还有很多关于这方面的好书/教程。你应该读一本。

编辑:您还应该阅读所有 JComponents(JButtons、JLabels...)。它们相当有用。

于 2021-07-07T16:12:21.653 回答