Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Dennis Castillo
Dennis Castillo
16,018 Points

How do I display graphics on Panel without an events?

Greetings folks,

Just practicing coding on Java using NetBeans 8.1, using GUI or drag and drop object interface. I have a problem displaying graphics on Panel, I have this code:

private void myPanel() {
        Graphics g = myPanel.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(5)); 
        g2.drawLine(10, 10, 10, 165);
        g2.drawLine(330, 165, 10, 165);
        g2.setColor(Color.LIGHT_GRAY);
        g2.drawLine(10, 10, 330, 10);
        g2.drawLine(330, 165, 330, 10);
    }

but it won't display, I probably missing something but i don't know what it is and don't know how to use it.

I switch to an event, add some button and put this code in it:

private void btnCalculateMouseClicked(java.awt.event.MouseEvent evt) {                                          
        Graphics g = myPanel.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(5)); 
        g2.drawLine(10, 10, 10, 165);
        g2.drawLine(330, 165, 10, 165);
        g2.setColor(Color.LIGHT_GRAY);
        g2.drawLine(10, 10, 330, 10);
        g2.drawLine(330, 165, 330, 10);
    }  

And it did work, but this is an event. but what if don't need an event just displaying instantly once the program runs?

Thanks :)