Java/java

Advertisement


Question
How do l write an applet called JDrawLine that draws a Line on a form from the coordinates  Start X 10: End X 150:Start Y 150:End Y 250 using the following components: JLabel, JButton, JTextFields.

Answer
I don't see what JLabel, JButton, and JTextField have to do with drawing a line. Unless perhaps you want a bit more interactivity.

In any case you will want to create a custom component to draw the line for you (as overriding paint in JApplet is a bad idea since it will paint over your other components).

E.g.

import java.awt.*;
import javax.swing.*;
public class JDrawLine extends JApplet
{
  private int startX = 10;
  private int endX = 150;
  private int startY = 150;
  private int endY = 250;
  private class LineDrawer extends JComponent
  {
     @Override
     protected void paintComponent(Graphics g)
     {
        super.paintComponent(g);
        g.drawLine(startX, startY, endX, endY);
     }
  }

  @Override
  public void init()
  {
     setLayout(new BorderLayout()); //In case you want to add additional components
     add(new LineDrawer(), BorderLayout.CENTER);
  }
}

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.