How to use jpanel with paint (or redraw)

I am new to paint / graphics and am wondering how to add JPanel to my code so that all graphics are on JPanel and not on JFrame.

In other words, I'm trying to create a graphical interface that will allow me to do this: on the right side they show the pleasant movement of the lines on the JPanel on the LEFT side, add a JTextArea (on JPanel), which will show the coordination of the graphics.

  • This is a simplification of a big problem, but I think the code here is easier to understand.

Thanks!!!

(picture below, moving lines or just running code)

import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Line2D; import javax.swing.JFrame; public class Test extends JFrame implements Runnable { private Line2D line; public Test() { super("testing"); this.setBounds( 500, 500, 500, 500 ); this.setVisible( true ); } public void paint( Graphics g ) { Graphics2D g2 = (Graphics2D) g; g2.draw(line); } @Override public void run() { int x=50; while (true) { try { Thread.sleep( 50 ); line = new Line2D.Float(100+x, 100+x, 250-x, 260+x%2); x++; repaint(); if (x==5000) break; } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main (String args[]) { Thread thread = new Thread (new Test()); thread.start(); } } 

enter image description here

+3
java swing jpanel jframe repaint
source share
2 answers
  • Instead of implementing Runnable install an ActionListener that calls repaint() . Call him from Swing Timer .
  • There are two ways to do this.
    • Extend JComponent or JPanel
    • Draw a BufferedImage and add it to ImageIcon in ImageIcon .
  • If you are expanding a component, use JComponent if you do not need to add additional children, or JPanel if you do. For both, override paintComponent(Graphics) instead of paint(Graphics) .
  • BufferedImage may be the best choice for this use case, as it seems to animate the (supposedly intentionally persistent) string sequence.
  • The EDT must have Swing GUIs running.
  • Do not call setBounds ! Instead, set the preferred size for the custom component, use reasonable values ​​for the text area constructor and combine them with layouts (and the corresponding padding and borders), then call pack() in the frame after adding all the components.
  • There is NPE if the JRE calls repaint() before starting Thread .

.. What was the question? Correctly, if we can conclude that the question is: "How to combine other components with a custom colored component?" - use a nested layout. see Example of nested layout .

Jaqap.png

If you use BufferedImage as your backup storage, you can put it as an image in this example, except that you don't specify JTable above, as well as JSplitPane .

+5
source share

Read the Swing tutorial on Custom Painting for the right way to do this.

+2
source share

All Articles