简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM