user3066227
user3066227

Reputation: 23

Correctly draw a rectangle on a JFrame

This thing is really getting on my nerves, that I simply can't understand why the way I think it should work isn't good and why it is good the other way. I would really appreciate your help. Thanks.

So here are my thoughts on how it should work:

public class Proba {   
    public static void main(String[] args) { 
        GUI gui = new GUI(); 
    } 
} 

import java.awt.Graphics; 
import javax.swing.JFrame; 

public class GUI { 
    JFrame ablak;

    public void paint(Graphics g){
        g.drawRect(20,20,100,100);
    }

    public GUI(){ 
        ablak = new JFrame("Graphics proba"); 
        ablak.setSize(400,300); 
        ablak.setVisible(true); 
        ablak.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
}

But this is not working, while this works:

public class Proba { 
    public static void main(String[] args) { 
        GUI gui = new GUI(); 
    } 
} 

import java.awt.Graphics; 
import javax.swing.JFrame; 

public class GUI { 
    JFrame ablak;
    Grid grid = new Grid();

    public GUI(){ 
        ablak = new JFrame("Graphics proba"); 
        ablak.setSize(400,300); 
        ablak.setVisible(true); 
        ablak.add(grid);
        ablak.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Grid extends JPanel {

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.drawRect(20,20,100,100);
    }
}

Upvotes: 0

Views: 480

Answers (2)

user2849738
user2849738

Reputation:

Just make the class GUI extends JFrame or you can do this :
In GUI builder you add one last line
paint(ablak.getGraphics());

Upvotes: 0

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

Your second way is the correct way. You draw on a JPanel, not a JFrame.

Here's one change you should make. This puts the GUI components on the Event Dispatch thread (EDT).

public class Proba { 
    public static void main(String[] args) { 
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GUI(); 
            }           
        });
    } 
} 

Upvotes: 2

Related Questions