-
November 13th, 2015, 07:28 AM
#1
problem with Drawing a line
hi
"at first sorry about my bad grammer"
I create a class named Drawing that extends a JPanel and implements KeyListener :
Code:
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Drawing extends JPanel implements KeyListener
{
private int width;
private int height;
public Drawing()
{
addKeyListener(this);
}
private void DrawLine(Point SP,Point EP){
Graphics g=getGraphics();
g.drawLine(SP.x, SP.y, EP.x, EP.y);
g.dispose();
}
public void DrawAxis(){
System.out.print("Axis is drawn ....");
width=this.getWidth();
height=this.getHeight();
DrawLine(new Point(0,height/2),new Point(width,height/2));
DrawLine(new Point(width/2,0),new Point(width/2,height));
}
@Override
public void keyPressed(KeyEvent event) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent event) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent event) {
//char c=event.getKeyChar();
DrawAxis();
}
}
this is the main program :
Code:
import javax.swing.JFrame;
public class Example1
{
public static void main(String[] args) {
JFrame jf=new JFrame();
jf.setSize(500, 500);
Drawing d=new Drawing();
d.setFocusable(true);
//***********************************
d.DrawAxis();
//***********************************
jf.add(d);
jf.setVisible(true);
}
}
by this codes when i press 'h' key on the keyboard , two line ( vertical and horizontal ) is drawn on the JPanel . now, how can i change this code to draw the lines on the main program , not by pressing the keyboard . i want to call DrawAxis() out of Drawing class . when i call it in the main program nothing is happen.
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
-
November 13th, 2015, 12:42 PM
#2
Re: problem with Drawing a line
The code uses a non-standard way to do its drawing. Normally drawing is done in an override of the JPanel's paintComponent() method. See the tutorial: http://docs.oracle.com/javase/tutori...ing/index.html
Norm
-
November 14th, 2015, 07:12 AM
#3
Re: problem with Drawing a line
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|