2

I know creating textfields and labels in swing. Now I want to draw a line by plotting pixels in swing, I have read all the examples on this site as well as any other sites also but I'm not getting it. I know how to do it in applets but I want to do it in swing. Please help.

import javax.swing.*;
import java.awt.*;

class dline{
   JFrame j;
   dline(){
      j = new JFrame("Line Draw");
      j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      j.setExtendedState(Frame.MAXIMIZED_BOTH);
      j.setVisible(true);
   }
   public void paintComponent(Graphics g){
      g.drawLine(10, 25,250, 300);
   }
   public static void main(String s[]){
      SwingUtilities.invokeLater(new Runnable(){
         public void run(){
            new dline();
         }
      });
   }
}
Aubin
  • 14,617
  • 9
  • 61
  • 84
crazy4
  • 135
  • 1
  • 2
  • 10
  • Read the Swing tutorial on [Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html). – camickr Mar 16 '13 at 15:03
  • You should use paint instead of paintComponent. paintComponent is supposed used to paint Components(eg. JButton) wheras paint is used to do custom painting. – user2097804 Mar 16 '13 at 15:06

1 Answers1

4
  1. Create a class DrawingPanel which extends JPanel
  2. Move your method paintComponent() in it
  3. Add an instance of DrawingPanel to your Frame

From the JDK 7 documentation:

You can find task-oriented documentation about using JFrame in The Java Tutorial, in the section How to Make Frames.

As camickr says: Read the Swing tutorial on Custom Painting.

Community
  • 1
  • 1
Aubin
  • 14,617
  • 9
  • 61
  • 84
  • Thanks. It worked successfully. can you explain me how's it working? And how to deal with graphics in swing? – crazy4 Mar 16 '13 at 14:34
  • For a hint as to why it failed, change (in the original source) from `public void paintComponent(Graphics g){` to `@Override public void paintComponent(Graphics g){` and try to compile it. – Andrew Thompson Mar 17 '13 at 00:11