I new to java's applet programming & there is a problem in my program

This is my program:

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

/*<applet code=Rect height=600 width=800></applet>*/

public class Rect extends JApplet implements ActionListener
{
JLabel jl1,jl2,jl3,jl4;
JTextField jt1,jt2,jt3,jt4;
JButton jb;
int x1,x2,y1,y2;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
jl1=new JLabel("x1 : ");
jl2=new JLabel("y1 : ");
jl3=new JLabel("x2 : ");
jl4=new JLabel("y2 : ");
jt1=new JTextField(5);
jt2=new JTextField(5);
jt3=new JTextField(5);
jt4=new JTextField(5);
jb=new JButton("Draw");
jb.addActionListener(this);
c.add(jl1);
c.add(jt1);
c.add(jl2);
c.add(jt2);
c.add(jl3);
c.add(jt3);
c.add(jl4);
c.add(jt4);
c.add(jb);
}
public void actionPerformed(ActionEvent ae)
{
    String s=ae.getActionCommand();
    x1=Integer.parseInt(jt1.getText());
    y1=Integer.parseInt(jt2.getText());
    x2=Integer.parseInt(jt3.getText());
    y2=Integer.parseInt(jt4.getText());
    repaint();
}
public void paint(Graphics g)
{
    g.drawLine(x1,y1,x2,y2);
}
}

I have did everything perfect but it shows some imperfection by disappearing the labels, textfields & buttons

Is there anyone can help me with my problem?????

Recommended Answers

All 9 Replies

You need to make the setVisible property of Container to be true.Thenall the textboxes,labels etc will be visible.

c.setVisible(true);

You have to add the component to the main frame.

super.add(c);

You have overidden JApplet's paint method, which is the method responsible for ensuring the contents are painted. That's why they don't get painted. Add a call to super.paint(g) as the first line of your paint mathod. This will ensure that everything in the applet gets painted before you draw your line.
Read this for more info, including the use of paintComponent rather than paint:
http://java.sun.com/products/jfc/tsc/articles/painting/#callbacks

The code works for me as is.

That's bizzare. I just copied the code. pasted it into eclipse and ran as applet, and got the expected bad result which is no visible text fields. and no visible button until the appropriate area is clicked. adding super.paint(g); fixed it.
Are you saying that you see the button and entry fields?

Yes. I executed the appletviewer: D:\Java\jdk1.6.0_02\bin\appletviewer.exe Rect.java

commented: it is truly bizarre because my friends also didn't got the output as expected +2

EVen more bizarre! I get the same bad result (no visible fields or button) from using the appletviewer as well (JDK 1.7.0_03 Win 64).

Thnx for helping Mr. JamesCherill adding

super.paint(g);

fixed it.

& about NormR1 seeing textfields it a bizzare as said my JamesCherill

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.