Java Tutorial for Beginners - 44 - GUI - Graphics and the Paint method

preview_player
Показать описание
In this tutorial we will take a first look at graphics.
Рекомендации по теме
Комментарии
Автор

This is by far the best tutorial on this topic. Helped me out a lot. Cheers

samraspin
Автор

One of the few who got all the way here! :D

manicho
Автор

Awesome tutorials, helped a lot while reviewing stuff for a programming exam!

hubertuswine
Автор

I have two questions here...
1) why can't paint right onto JFrame(Why the Panel)? I tried and have to change the 
paintComponent method to another name (paint(Graphics g) to get it to put the rectangle in there, but it does....

2) frame.add(this):  is the reason for this is that since we extend JPanel, our graphic is being created on the panel, and frame.add(this) adds "this panel" or is that logic off?

punated
Автор

Is there a way to edit the paintComponent() method of your JPanel without extending off of it?

nailmirror
Автор

I like creating graphics in JFrame as compared to an Applet and my question is in Applet I can use repaint() but in this way(i.e. when using paintComponent())
how do I use repaint() or a
some function like it??

Senshiii
Автор

Source:
import java.awt.*;
import javax.swing.*;

// 1. Added components to our JFRAME
// 2. We can also add graphics but NOT to JFRAME - need to use JPANEL

public class Rectangle extends JPanel {
JFrame frame;
    
    public void fireUpScreen () { 
        
    frame = new JFrame ();
    frame.setVisible(true);
    frame.setSize (600, 600);
   
    frame.add(this);
    }
    
public void paintComponent (Graphics g) {
    
// paintComponent is the method used to paint - think of JPanel as our canvas
g.setColor(Color.BLUE);
g.fillRect(0, 0, 200, 100);
    
}
    public static void main(String[] args) {
        Rectangle go = new Rectangle ();
        go.fireUpScreen();
    }

}

EJMedia
Автор

I'm very confused about 2 things here:
1. Is this method paintComponent inherited from Jpanel's super classes, or is it a method that you have custom written (Your oen function)?
2. When Rectangle class is instantiated as go(), I don't see how this painComponent method gets invokes anywhere from the main method. How does the control even reach here? I was thinking that the only way this can be invoked is by go.paintComponent(Graphics g)?

sraj
Автор

Why don't you call paintComponent method?

chrisszeremet