0

i have a jlable.and i'm going to draw a graph on it.but i realized that a line crated by draw line method ,disappear when resizing frame.

this is my code.i want to know how to avoid from disappearing when resize.i want to stay line even resize jframe.

  void graph(JComponent jcom,int thick,int height,int xpos,int ypos,Color col){
        Graphics2D gfx=(Graphics2D) jcom.getGraphics();
        gfx.setStroke(new BasicStroke(thick));
        gfx.setPaint(col);
        gfx.drawLine(xpos, ypos, xpos, ypos-height);
    }  

button click code

graph(jLabel1, 10, 100, 200, 200, Color.GREEN);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60

1 Answers1

3
  1. You can create your own class which extends from JLabel and has an extra method to decide if it must paint the line or not.

    In the overridden paintComponent() method of this new class, draw your line after the super.paintComponent() call.

  2. apply the logic from suggestion 1 in the parent component of you JLabel. (not sure if this will work in all situations)

Community
  • 1
  • 1
Conffusion
  • 4,335
  • 2
  • 16
  • 28
  • A common component for custom rendering can be found in a `JPanel`. OTOH a `JLabel` using a `BufferedImage` to paint on. As each new element is added, the technique used by the OP will work (with a slight tweak and one or two additional lines of code). – Andrew Thompson Aug 04 '14 at 10:08
  • @conffusion and Andrew Thompson .i still don't achieve this.however i have a problem about that.if i create a custom class which extend a JLabel ,i think it's act as a label.in my application i have to update my graph manytimes.so when i update my graph according to your answer ,do i need to create new instances of this label?is that mean delete my existing jlable and add new one to panel?or am i wrong ? – Madhawa Priyashantha Aug 06 '14 at 11:49
  • 'paintComponent' is called when Swing decides to repaint the component. If some external data changes, you can ask Swing to repaint the component by calling the Component.repaint() method. The real call to the paint() method is managed by swing and is done by the UI thread, so don't call paint() yourself. (http://stackoverflow.com/questions/4396583/java-swing-repaint-vs-invalidate) – Conffusion Aug 06 '14 at 11:54