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

mathieu_b
  • 383
  • 1
  • 5
  • 19
  • 1
    please did you bothering with [Trail: 2D Graphics](http://docs.oracle.com/javase/tutorial/2d/index.html) – mKorbel Oct 09 '13 at 07:40

2 Answers2

3

Override the JPanel's paintComponent(Graphics g) method. IN the method you have access to a valid Graphics instance. The method called on each paint.

But may be it's better to add a JLabel to the panel. The label initially has no text and when you have a message just call setText(messageText) of the label.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
0

You should create subclasses for your JFrame and JPanel, and override the methods you want. You could try something like:

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();
        
    }

}

Also, there are a lot of great books/tutorials about this. You should read one.

Edit: You should also read about all the JComponents (JButtons, JLabels...). They're rather useful.

Promitheas Nikou
  • 511
  • 4
  • 14