简体   繁体   中英

Threading with Swing

basically, I have a program that has a class to create a basic GUI, and another class that extends Canvas . This Canvas class is added to a JPanel in the usual fashion myPanel.add(object) . Now, in this class, I want to have methods to move objects such as rectangles.

My questions are these; is there a way to essentially have this JPanel or its added object (myCanvas) running on a separate thread?

Also, in the following method:

public void paint(Graphics g){
    g.setColor(Color.black);
    g.drawRect(0, 0, 50, 50);
}

Is there a way to have these operations split into multiple methods? Ie multiple methods that draw to the Canvas?

Thanks in advance.

Store a list of drawable objects somewhere (perhaps your Canvas class, but I'd advise that being external to your logic...) and use your other thread(s) to update this list of objects.

Your drawing loop can simply clear your canvas (or at least areas that need to be redrawn) and draw those. Ideally your screen-render should be fast enough to facilitate a complete redraw, caching sub-sections as necessary.

Don't use a Canvas is a Swing applicaton. Use a JPanel or JComponent and override the paintComponent() method. Also don't forget the super.paintComponent(g) at the start of the method.

See the section in the Swing tutorial on Performing Custom Painting for more information.

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