Syntax error in Java applet

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • danielmessick
    New Member
    • Mar 2010
    • 9

    Syntax error in Java applet

    I'm having errors on lines 10 and 21 and am not sure why.....




    import javax.swing.*;
    import java.awt.*;
    import java.awt.event. *;
    public class Main extends JApplet implements MouseListener {
    int x=0;int y=0;
    JTextField jtf=new JTextField(" ");
    public void init(){
    Container c=getContentPan e();
    c.setLayout(nul l);
    jtf.setBounds(x ,y,jtf.getPrefe rredSize…
    c.setBackground (Color.RED);
    c.add(jtf);
    c.addMouseListe ner(this);
    }
    public void mouseExited(Mou seEvent me){}
    public void mouseEntered(Mo useEvent me){}
    public void mouseReleased(M ouseEvent me){}
    public void mousePressed(Mo useEvent me){
    x=me.getX();
    y=me.getY();
    jtf.setBounds(x ,y,jtf.getPrefe rredSize ();
    repaint();
    }
    public void mouseClicked(Mo useEvent me){}
    }
  • anurag275125
    New Member
    • Aug 2009
    • 79

    #2
    1. First of all you have to set the layout of the applet to FlowLayout in order to see the components in applet. If still you wanna use no layout then you have to set the content pane to JLayeredPane.
    2. You have to pass the width and height of the component in the setBounds method.

    Try this code---

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /* <applet
    code=Main.class
    width=400
    height=400
    >
    </applet> */
    
    public class Main extends JApplet implements MouseListener 
    {
    	int x=0;int y=0;
    	JTextField jtf=new JTextField(" ");
    	public void init()
    	{
    		Container c=getContentPane();
    		c.setLayout(new FlowLayout());       // you didn't set any layout 
    		jtf.setBounds(x,y,jtf.getPreferredSize ().width,getPreferredSize ().height);
    		c.setBackground(Color.RED);
    		c.add(jtf);
    		c.addMouseListener(this);
    	}
    	public void mouseExited(MouseEvent me){}
    	public void mouseEntered(MouseEvent me){}
    	public void mouseReleased(MouseEvent me){}
    	public void mousePressed(MouseEvent me)
    	{
    		x=me.getX();
    		y=me.getY();
    		jtf.setBounds(x,y,jtf.getPreferredSize ().width,getPreferredSize ().height);  // you didn't pass width and height of the text field
    		repaint();
    	}
    	public void mouseClicked(MouseEvent me){}
    }
    Best of Luck....

    Comment

    • danielmessick
      New Member
      • Mar 2010
      • 9

      #3
      @ anurag275125

      Thanks man!! it worked just fine!

      Comment

      Working...