JApplet question

Can someone please tell me why the background color doesn't appear when I run this code?
package javaapplication2;
import java.awt.*;
import javax.swing.JApplet;
public class may19f extends JApplet {
    public void paint (Graphics page)
        setBackground(Color.orange);
        page.setColor(Color.black);
        page.drawRect(40,40,60,60);
        page.drawOval(20, 20, 30, 30);
        page.drawOval(90, 20, 30, 30);
}

cotton.m wrote:
For starters you are over-riding the wrong method. JApplet means Swing. And custom Swing painting means overriding paintComponent. See the [_Swing Tutorial_|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]
Although JApplet, not being a JComponent, lacks that method. But that's just a sign from JGod not to have the applet class do the painting!

Similar Messages

  • JApplet question,please help me!

    In an Applet , I want to make an orgination diagram which extends from top to bottom(its mechanism partly like JTree, but it differs appearance ) for example, the top is directorate,under directorate is general manager,
    under general manager is each department..., every node is in a retangle, when in the rectangle and right click mouse,it will show the pop menu,you can select add or delete the node. how auto arrange the node?
    of course in the first the user should add node from the top node,and so on.
    How design the node??? Please tell me.
    Any good idea would be nice!

    Why is it an "JApplet question, can you do it in a JFrame ?
    Noah

  • A question about JApplet

    Hi there,
    I import a jar in my JApplet program, but when I open the html file, a error message appeared in Java console,
    java.lang.NoClassDefFoundError: class name xxxx
    xxxx
    xxxx
    xxxx
    I copied the .jar file to JRE\lib\, even my current directory and add the directory to classpath. I restart my computer too.
    What's the problem?
    Thanks
    Vq

    Hi vinsonq!
    Don't need to translate jar file to JRE\lib, simplify placing this at user folder to better maintenance. The error certainly is due to HTML tag parameters, check codebase assignment and remeber to use <Object tag, not <applet.
    Best regards.

  • Newb question re: JApplet

    heya,
    i have the following applet that is damned to work. any advice as to why:
    a) the JLabel and JTextField aren't displaying properly(the label doesn't show at all)
    b) the "\n" escape doesn't create a new line - rather, an empty square indicating an escape seq.
    c) the applet doesn't clear its' contents upon reciept of a new action event.
    basically, the applet asks for an integer and should then display a square built of asterisks with the sides equal to the entered value. simple and basic.
    any tips would be greatly appreciated. on my 3rd bottle of Advil.... =(
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawSqaure extends JApplet
                                   implements ActionListener {
       JLabel lblGetInput;
       JTextField txtGetInput;
       int intUserInput = 0;
       public void init()
          Container c = getContentPane;
          c.setLayout(new FlowLayout);
          lblGetInput = new JLabel("Enter an integer: ");
          txtGetInput - new JTextField(5);
          txtGetInput.addActionListener(this);
          c.add(lblGetInput);
          c.add(txtGetInput);
       public void actionPerformed(ActionEvent e)
          intUserInput = Integer.parseInt(txtGetInput.getText());
          repaint();
       public void paint(Graphics g)
           squareOfAsterisks(g, intUserInput);
       public void squareOfAsterisks(Graphics g, int side)
          String output = "";
          for (int row = 0; row < side; row++) {
               for (int column = 0; column < side; column++) {
                    output += "* ";
               output += "\n"
          g.drawString(output, 20, 40)
    }again, any tips/suggestions any of you have would be greatly appreciated. thanks
    mirirom

    kk,
    i included the call to the superclass constructor super(g] as suggested, however, i kept getting a compile error stating call to super must be first statement in constructor.
    i was able to rewrite the custom method squareOfAsterisks() so that it would display the shape properly. yet the applet still won't show the JLabel, nor will it clear the square previously drawn when a new value is entered.
    the code changes are below
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawSquare extends JApplet implements ActionListener{
       JLabel lblGetInput;
       JTextField txtGetInput;
       int intGetInput;
       public void init()
          Container c = getContentPane();
          c.setLayout(new FlowLayout());
          lblGetInput = new JLabel("Enter an integer: ");
          txtGetInput = new JTextField(5);
          txtGetInput.addActionListener(this);
          c.add(lblGetInput);            c.add(txtGetInput);
       public void actionPerformed(ActionEvent e)
          intGetInput = Integer.parseInt(txtGetInput.getText());
          repaint();
       public void paint(Graphics g)
          //super(g)   causes error
          squareOfAsterisks(g, intGetInput);
       public void squareOfAsterisks(Graphics g, int side)
          for (int row = 0; row < side; row++) {      // columns loop
             for (int column= 5; column < (side + 5); column++) {   // rows loop
                 g.drawString("*", row * 10, column * 10); 
    }in addition, i created another applet that has not GUI components. the data is entered via a JOptionPane. still the same result (less the label problem since there isn't one) -- the applet doesn't "clear" what was drawn before.
    ugh.. i never imagined this as being as difficult as its turned out to be. thanks for your suggestion Trev =)

  • Question about JApplet?

    Hello,
    On the internet I saw an JApplet, which allow the user spin around a scene. The link is here:
    http://www.bbc.co.uk/nottingham/360/students/university/hugh_stewart_hall.shtml
    This was a building from my old university, in the scene we can also move up and down.
    Could anyone advise of an example code on the web which achieves this type of effect? Would this involve Java2D api?
    Thank you

    I think this mostly involves a special photography technique (a 360� pic) and an image that's scrolled endlessly. Go ask your local photographer about something like that, maybe you can hire him to do it for you. Then you scan it and load it into your applet, showing only a part of it. Then start scrolling and there you are.

  • Dumb question about JApplet

    Hi,
    I am trying to run an applet from my hard drive. I can get the HTML file pointing to the JApplet file ok, but it can't handle my lib files. ie. I want all the jar files in my lib directory to be seen by my java applet.
    anyone have any ideas?
    cheers,
    Oliver

    The APPLET tag has an ARCHIVE attribute.
    Kind regards,
      Levi

  • Question about JTextPane, JEditorPane in JApplet?

    Hello,
    I was hoping to display the results of a small piece of html code in a JApplet, I know in the jdk we can use a JTextPane or JEditorPane to display the results of html. But can we use the JTextPane or JEditorPane in a JApplet.
    Thanks

    That really depends on:
    1) whether the HTML is well formed. JEditorPane has problems with any html that is not well formed. For example, <b><p>test</b></p> is not well formed.
    2) whether you want to write your own html viewer
    3) whether you can ensure that users will have a JVM version recent enough to use the JEditorPane - 1.3 is probably the first version it was introduced.

  • Need to convert JApplet to JFrame

    I need to write code for where I have 60 balls bouncing around inside a window. The client will then be able to select a button and it will pull out a ball with the number 1-60 written on it. The user will be able to do this up to 7 times. Each time it is done the past numbers that have already appeared can not reappear. What I am stuck on right now is geting my balls into a JFrame. Can anyone give advice or show how to. I currently have my 60 balls running in a JApplet. Here is the JAVA code and the HTML code. Thanks!
    Here is the JAVA code
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    class CollideBall{
    int width, height;
    public static final int diameter=20;
    //coordinates and value of increment
    double x, y, xinc, yinc, coll_x, coll_y;
    boolean collide;
    Color color;
    Graphics g;
    Rectangle r;
    //the constructor
    public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c){
    width=w;
    height=h;
    this.x=x;
    this.y=y;
    this.xinc=xinc;
    this.yinc=yinc;
    color=c;
    r=new Rectangle(150,80,130,90);
    public double getCenterX() {return x+diameter/2;}
    public double getCenterY() {return y+diameter/2;}
    public void alterRect(int x, int y, int w, int h){
    r.setLocation(x,y);
    r.setSize(w,h);
    public void move(){
    if (collide){  
    double xvect=coll_x-getCenterX();
    double yvect=coll_y-getCenterY();
    if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
    xinc=-xinc;
    if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
    yinc=-yinc;
    collide=false;
    x+=xinc;
    y+=yinc;
    //when the ball bumps against a boundary, it bounces off
    if(x<6 || x>width-diameter){
    xinc=-xinc;
    x+=xinc;
    if(y<6 || y>height-diameter){
    yinc=-yinc;
    y+=yinc;
    //cast ball coordinates to integers
    int x=(int)this.x;
    int y=(int)this.y;
    //bounce off the obstacle
    //left border
    if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //right border
    if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //upper border
    if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    //bottom border
    if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    public void hit(CollideBall b){
    if(!collide){
    coll_x=b.getCenterX();
    coll_y=b.getCenterY();
    collide=true;
    public void paint(Graphics gr){
    g=gr;
    g.setColor(color);
    //the coordinates in fillOval have to be int, so we cast
    //explicitly from double to int
    g.fillOval((int)x,(int)y,diameter,diameter);
    g.setColor(Color.white);
    g.drawArc((int)x,(int)y,diameter,diameter,45,180);
    g.setColor(Color.darkGray);
    g.drawArc((int)x,(int)y,diameter,diameter,225,180);
    public class BouncingBalls extends Applet implements Runnable {
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    CollideBall ball[];
    //Obstacle o;
    //how many balls?
    static final int MAX=60;
    boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
    boolean shiftNW,shiftSW,shiftNE,shiftSE;
    int xtemp,ytemp,startx,starty;
    int west, north, east, south;
    public void init() {  
    Buffer=createImage(getSize().width,getSize().height);
    gBuffer=Buffer.getGraphics();
    ball=new CollideBall[MAX];
    int w=getSize().width-5;
    int h=getSize().height-5;
    //our balls have different start coordinates, increment values
    //(speed, direction) and colors
    for (int i = 0;i<60;i++){
    ball=new CollideBall(w,h,50+i,20+i,1.5,2.0,Color.white);
    /* ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
    ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
    ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
    ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
    ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
    ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
    ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
    ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
    ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
    ball[10]=new CollideBall(w,h,330,10,-2.1,-2.0,Color.gray);
    ball[11]=new CollideBall(w,h,220,230,-1.2,-1.8,Color.gray);
    ball[12]=new CollideBall(w,h,230,60,-2.3,-2.5,Color.gray);
    ball[13]=new CollideBall(w,h,320,230,-2.2,-1.8,Color.gray);
    ball[14]=new CollideBall(w,h,130,300,-2.7,-3.0,Color.gray);
    ball[15]=new CollideBall(w,h,210,90,-2.0,-1.8,Color.gray);*/
    public void start(){
    if (runner == null) {
    runner = new Thread (this);
    runner.start();
    /* public void stop(){
    if (runner != null) {
    runner.stop();
    runner = null;
    public void run(){
    while(true) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    try {runner.sleep(15);}
    catch (Exception e) { }
    //move our balls around
    for(int i=0;i<MAX;i++)
    ball[i].move();
    handleCollision();
    repaint();
    boolean collide(CollideBall b1, CollideBall b2){
    double wx=b1.getCenterX()-b2.getCenterX();
    double wy=b1.getCenterY()-b2.getCenterY();
    //we calculate the distance between the centers two
    //colliding balls (theorem of Pythagoras)
    double distance=Math.sqrt(wx*wx+wy*wy);
    if(distance<b1.diameter)
    return true;
    return false;
    private void handleCollision()
    //we iterate through all the balls, checking for collision
    for(int i=0;i<MAX;i++)
    for(int j=0;j<MAX;j++)
    if(i!=j)
    if(collide(ball[i], ball[j]))
    ball[i].hit(ball[j]);
    ball[j].hit(ball[i]);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    gBuffer.setColor(Color.lightGray);
    gBuffer.fillRect(0,0,getSize().width,getSize().height);
    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
    //paint our balls
    for(int i=0;i<MAX;i++)
    ball[i].paint(gBuffer);
    g.drawImage (Buffer,0,0, this);
    Here is the HTML code
    <html>
    <body bgcolor="gray">
    <br><br>
    <div align="center">
    <applet code="BouncingBalls.class" width="1000" height="650"></applet>
    </div>
    </body>
    </html>

    In the future, Swing related questions should be posted in the Swing forum.
    First you need to convert your custom painting. This is done by overriding the paintComponent() method of JComponent or JPanel. Read the Swing tutorial on [Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Box in JApplet?!

    Just a quick question.. I have no problems with using Box Layout in a Java application, but the minute I try to use Box in an applet nothing appears! Can I use Box in JApplets?!
    Thanks :-)

    I found the answer in
    http://www.jguru.com/faq/view.jsp?EID=27423

  • Help please, not able to load images in a subclass of a japplet

    I've created this board for a project, but now I am stuck, I cannot seem to get images to appear, instead they come up as a nullpointerexception:
    public class Board extends JLayeredPane implements MouseListener, MouseMotionListener{
         private Container contentPane;
         private JLayeredPane jlp;     
         private boolean pieceSelected;
         private timepanel time;
         Image bimage;
         ImageIcon board;
         JLabel brd;
         Image pimage;
         ImageIcon piece;
         JLabel pce;
         private Graphics g;
         private pieceLayout pieces;
         private String piecename;
         private JLabel jl;
         boolean selected;
         private int offset;
         boolean changepos;
         boolean moving;
         private int brdwidth;
         private int brdheight;
         private Timer countdown;
         private updateTimer ut;
         private String cb;
         private clientinterface ci;
         private JFrame j;
         private int playerturn;
         public Board(clientinterface ci, JFrame j, Hashtable images, ArrayList names,
         ImageIcon brdicon, URL cb)
              j.setSize(500,450);
              countdown = new Timer();
              selected = false;
              jlp = this;
              jlp.setPreferredSize(new Dimension(500, 450));
              changepos = false;
              //contentPane = getContentPane();
              //this.setPreferredSize(new Dimension(500,400));
              jlp.setBounds(0,0,500,450);
              jlp.setLocation(0,0);
              jlp.setOpaque(true);
              jlp.setLayout(null);
              System.out.println(this.getSize() + "(((())))" );
              if(j.getWidth() > 400)
                   offset = j.getWidth() - 400;
              else
                   offset = 0;
              System.out.println("Width is: " +  j.getWidth() + " height: " + j.getHeight());     
              brdwidth = j.getWidth()-offset;
              brdheight = j.getHeight();
              System.out.println(images.size());     
              System.out.println(j.getWidth() + " " + j.getHeight() + " " + offset);
              brd = new JLabel(brdicon);
              brd.setBounds(0,0,j.getWidth()-offset, j.getHeight());
              brd.setSize(new Dimension(400,400));
              brd.setLocation(0,0);
              brd.setOpaque(true);
              jlp.add(brd, new Integer(-5));
              jlp.setBounds(0,0,j.getWidth(), j.getHeight());
              jlp.setVisible(true);
              time = new timepanel(jlp);
              time.setLocation(j.getWidth()-offset, 0);
              System.out.println(images.toString() + "++++++++");
              pieces = new pieceLayout(jlp, j.getWidth()-offset, names, cb);
              pieces.setLocation(0,0);
              pieces.setPreferredSize(new Dimension(400,400));
              pieces.setBounds(0,0,400,400);
              pieces.setVisible(true);
              time.setBounds(400,0, 100, 400);
              time.setVisible(true);
              ut = new updateTimer(time);
              jlp.add(pieces, new Integer(2));
              jlp.add(time, new Integer(2));
              //this.add(jlp);
              j.setLayeredPane(jlp);
              addMouseMotionListener(this);
              addMouseListener(this);
              //j.getContentPane().add(jlp);
              //j.setContentPane(this);
              j.validate();
              //j.getContentPane().setLayout(null);
              //j.setContentPane(this);
              j.paintAll(j.getGraphics());
         public void run()
              //this.repaint();
              this.paintAll(this.getGraphics());
              time.repaint();
         public void mouseDragged(MouseEvent e)
              JLabel temp;
              moving = true;
              //pce.setLocation(e.getX(), e.getY());
              //pieces.getPiece(pieces.translatecoords(e.getX(),e.getY())).setLocation(e.getX(),e.getY());
              int piecepos = pieces.translatecoords(e.getX(), e.getY());
              /*if(pieces.hasPiece(piecepos) && moving)
                   pieces.setSelected(piecepos);
                   temp = pieces.getPiece(piecepos);
                   //pieces.movePiece(e.getX(), e.getY());
                   temp.setLocation(e.getX(), e.getY());
              //this.repaint();
         public void mouseClicked(MouseEvent e)
              Point xpoin;
              System.out.println("Hello, clicked");
              /*pce.setLocation(e.getX(), e.getY());
              Point p = pce.getLocation();
              System.out.println(p.toString());*/
              System.out.println("\n" + e.getX() + " " + e.getY());
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mouseReleased(MouseEvent e)
              if(selected)
                   Point xp;
                   int x = e.getX();
                   int y = e.getY();
                   int bp = pieces.translatecoords(x,y);
                   xp = pieces.posToPoint(bp);
                   pieces.snapToSquare(xp.x, xp.y, bp);
                   selected = false;
                   moving = false;
                   //pieces.updateBoard(bp, piecename);
         public void mouseMoved(MouseEvent e)
         public void mousePressed(MouseEvent e)
              Point xpoin;
              int pos = pieces.translatecoords(e.getX(),e.getY());
              System.out.println("\n" + pieces.translatecoords(e.getX(),e.getY()));
              if(pieces.hasPiece(pos, e.getX(), e.getY()))
                        piecename = pieces.getName(pos);
                        System.out.println("Found a piece!");
                        pieces.setSelected(pos);
                        xpoin = pieces.posToPoint(pos);
                        selected = true;
         public void paintComponent(Graphics g)
              //super.paintComponents(g);
              //System.out.println("Painting");
              time.repaint();
         public void start()
              countdown.schedule(ut, 0, 1000);
         public void setupBoard()
                   //setSize(getSize().width < 400 ? 400 : getSize().width,
                   //getSize().height < 400 ? 400 : getSize().height);
                   //getLayeredPane().add(brd, new Integer(-5));
         public void sendInfo(String info)
              //parse information
         public class pieceLayout extends JLayeredPane
              JLabel pce1;
              private JLabel selected;
              private Hashtable pieceList;
              private ArrayList names;
              private int width;
              private Hashtable piecesOnBoard;
              private char boardstate[]= {'R','N','B','Q','K','B','N','R',
                                                 'P','P','P','P','P','P','P','P',
                                                 'p','p','p','p','p','p','p','p',
                                                 'r','n','b','q','k','b','n','r'
              private String posnm[]       = {
                                                       "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
                                                       "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
                                                       "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
                                                       "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
                                                       "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
                                                       "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
                                                       "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
                                                       "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"
              JLayeredPane thePane;
              private Hashtable ht;
              private Hashtable board;
              private Hashtable b2p;
              private Hashtable p2b;
              private Hashtable piecePos;
              private Hashtable objToName;
              private Hashtable posnames;
              private URL codebase;
              public pieceLayout(JLayeredPane p, int twidth, ArrayList pnames, URL cb)
                   pieceList = new Hashtable(20);
                   codebase = cb;
                   names = pnames;
                   selected = new JLabel();
                   piecesOnBoard = new Hashtable(32);
                   ht = new Hashtable(6);
                   board = new Hashtable(64);
                   b2p = new Hashtable(64);
                   p2b = new Hashtable(64);
                   piecePos = new Hashtable(64);
                   objToName = new Hashtable(32);
                   posnames = new Hashtable(64);
                   fillnames();
                   getImages();
                   setImages();
                   width = twidth;
                   thePane = p;
                   System.out.println(piecesOnBoard.size());
                   showBoard();
              private void fillnames()
                   int size = posnm.length;
                   for(int i = 0; i < size; i++ )
                        posnames.put(new Integer(i), new String(posnm));
                   showPos();
              private void getImages()
                   Pattern p = Pattern.compile(".+\\.GIF");
                   Pattern p1 = Pattern.compile(".+\\.gif");
                   Pattern p2 = Pattern.compile("board.+");
                   Pattern p3 = Pattern.compile(".+board.+");
                   for(int i = 0; i < names.size(); i++)
                        Matcher m = p.matcher((String)names.get(i));
                        Matcher m1 = p1.matcher((String)names.get(i));
                        Matcher m2 = p2.matcher((String)names.get(i));
                        Matcher m3 = p3.matcher((String)names.get(i));
                        if(m.matches() || m1.matches())
                             //System.out.println("Files are: " + dirs[i].getName());
                             if(!m2.matches() && !m3.matches())
                                  String piecename = new String((String)names.get(i));
                                  //     System.out.println("Files were: " + dirs[i].getName());
                                  Image tpimage = Toolkit.getDefaultToolkit().createImage(piecename);
                                  Image pimage = tpimage.getScaledInstance(35,35, Image.SCALE_DEFAULT);
                                  //ImageIcon piece = new ImageIcon(pimage);
                                  pieceList.put(new String(piecename), pimage);
                   System.out.println(pieceList.toString());
                   System.out.println(pieceList.size() + "((**))(())");
              private void setImages()
                   int listsize = names.size();
                   if(!pieceList.isEmpty())
                        int index = 0;
                        for(int i = 0; i < listsize; i++)
                             String pieceName = (String)names.get(index);
                             String hKey = getHashKey(pieceName);
                             System.out.println(hKey);
                             if((hKey.compareTo("blackking") == 0) || (hKey.compareTo("blackqueen") == 0) ||
                             (hKey.compareTo("whiteking") == 0) || (hKey.compareTo("whitequeen") == 0))
                                  Image tpiece = (Image)pieceList.get(new String(hKey));
                                  ImageIcon piece = new ImageIcon(tpiece);
                                  pce1 = new JLabel(piece);
                                  piecesOnBoard.put(new String(hKey), pce1);
                             else
                                  System.out.println("multiples " + hKey);
                                  createMultiples(hKey, pieceName);
                             if(i == listsize-1)
                                  index = 0;
                             else
                                  index++;
                             System.out.println(pieceName + " " + hKey + "1234567890");
              private void createMultiples(String key, String hname)
                   JLabel piecet;
                   String name;
                   if(key == "blackpawn" || key == "whitepawn")
                        name = key;
                        for(int i = 0; i < 8; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                   else if(key == "blackknight" || key == "whiteknight")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackbishop" || key == "whitebishop")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             System.out.println(piece.toString());
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackrook" || key == "whiterook")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
    Hopefully this will format alright, but my question is, is that why is it giving me this error... it happens in the create multiples function(the last function in this code block) this is a jlayeredpane which is called by a JApplet. Any ideas on the loading? Its in the getImages() fuction.

    These are the lines it dies on.... the System.out.println(piece.toString()); precisely. I don't know if I am not getting the images from the directory right... or if I need to make sure this is in a JAR file or not.
    {                    name = key;                    for(int i = 0; i < 2; i++)                    {                         System.out.println(name+i);                         String tempname = name+i;                         Image piece = (Image)pieceList.get(new String(name));                         System.out.println(piece.toString());                         ImageIcon pieces = new ImageIcon(piece);                         piecet = new JLabel(pieces);                         piecesOnBoard.put(new String(tempname), piecet);                    }                    if(!ht.containsKey(new String(key)))                    {                         ht.put(new String(key+0), new Integer(0));                    }                    

  • Need help with Java, have a few questions about my Applet

    Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
    Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that?  How can I get it only calculate that information once unless the user changes it etc?
    My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
    Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
    And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
    I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
              Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM

    // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         // The method that will perform specific actions defined below
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              buff = new StringBuffer();
              // Outcome of pressing the calculate button
              if (source == calculate)
                   // Used to call upon the user chosen selection
                   int selection = selections.getSelectedIndex();
                   // If statement to call upon Loan One's Method
                   if (selection == 0)
                        Double data = (Double)calculateLoanOne();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Two's Method
                   else if (selection == 1)
                        Double data = (Double)calculateLoanTwo();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Three's Method
                   else if (selection == 2)
                        Double data = (Double)calculateLoanThree();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // Outcome of pressing the clear button
                   else if (source == clearButton)
                        enterPrincipal.setText("");
                        displayMonthlyPayment.setText("");
                        selections.setSelectedIndex(0);
                        txtArea.setText("");
                   // Outcome of pressing the quit button
                   else if (source == exitButton)
                        System.exit(1);
         // Method used to validate user input
         private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;

  • Can a JApplet access a file to be read?

    I think I recall reading or hearing somewhere that a JApplet cannot, for "security reasons", access any files on the computer it is running on unless it is the 'original' or the one where the code is stored. What I would like to do is have a file that will be only read (not written to) by a JApplet and use the information for the applet. If I always run the JApplet with a browser on the computer where I have the code stored, will it allow me to access this file or will it still prevent me? Or can I just have the file stored in the same folder as the applet in my webpage directory so that it will be able to access it there and display it for all others on different computers?
    Thanks in advance for any insights!

    Hello forum,
    Lot of confusion's on this topic.
    Here is my understanding.The question is "Can a JApplet access a file to be read?". Answer is "No". But workaround is there.Then where the confusion is.
    I have seen kartik181 mentioned about using digital signature from verisign/similar to grant access to your local file system!
    The question asked by aachi is " ........Is it so? What is the purpose of digital signatures then?"
    Also aachi mentioned about policy file. That means to get an access to local file is something you have to do with policy file.
    bharthy explained the same in detail with some example.
    Now look at the original question posted by the author littleB.
    The answer I got from jdk 1.2 sand box model..
    "There is no longer a built-in concept that all local code is trusted. Instead, local code (e.g., non-system code, application packages installed on the local file system) is subjected to the same security control as applets, although it is possible, if desired, to declare that the policy on local code (or remote code) be the most liberal, thus enabling such code to effectively run as totally trusted. The same principle applies to signed applets and any Java application."
    So if you want to do your applet (whether you store locally or remotely in the path of webserver) you would end up an easy way of changing policy file by allowing more easily to do the specific job.
    Hope it gives a bit clear picture of it.

  • Load Image into JApplet

    Hello to all Java expect coder, i would like to load an image to an applet but after it flash once time then it just disappear.
    Below is my code :
    * SodaVendingMachineApplet.java
    * Created on June 8, 2008, 4:08 PM
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.ImageIcon.*;
    * @author  nicholas_tse
    public class SodaVendingMachineApplet extends javax.swing.JApplet {
        private ImageIcon  soda;
        private ImageIcon  lemon;
        private ImageIcon  orange;
        private Graphics g;
         // To draw image
        @Override
        public void paint(Graphics g)
            soda = new ImageIcon("D:/Java/SodaMachine/cola_5.jpg");
            soda.paintIcon(this, g, 30, 40);
        /** Initializes the applet SodaVendingMachineApplet */
        @Override
        public void init() {
            try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        initComponents();
            } catch (Exception ex) {
                ex.printStackTrace();
        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            jRadioButton4 = new javax.swing.JRadioButton();
            jRadioButton5 = new javax.swing.JRadioButton();
            jRadioButton6 = new javax.swing.JRadioButton();
            jLabel1.setText("Soda");
            jLabel2.setText("Lemon");
            jLabel3.setText("Orange");
            jRadioButton1.setText("Regular");
            jRadioButton2.setText("Diet");
            jRadioButton3.setText("Regular");
            jRadioButton4.setText("Diet");
            jRadioButton5.setText("Regular");
            jRadioButton6.setText("Diet");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(16, 16, 16)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jRadioButton2)
                                    .addGap(18, 18, 18))
                                .addComponent(jRadioButton1)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(38, 38, 38)
                            .addComponent(jLabel1)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(61, 61, 61)
                            .addComponent(jLabel2))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(49, 49, 49)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jRadioButton4)
                                .addComponent(jRadioButton3))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(47, 47, 47)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jRadioButton6)
                                .addComponent(jRadioButton5)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(63, 63, 63)
                            .addComponent(jLabel3)))
                    .addContainerGap(107, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(69, 69, 69)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jRadioButton2))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jRadioButton4))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton5)
                            .addGap(23, 23, 23))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(23, 23, 23)
                            .addComponent(jRadioButton6)))
                    .addContainerGap(175, Short.MAX_VALUE))
        }// </editor-fold>                       
        // Variables declaration - do not modify                    
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JRadioButton jRadioButton4;
        private javax.swing.JRadioButton jRadioButton5;
        private javax.swing.JRadioButton jRadioButton6;
        // End of variables declaration                  
    }The image just flash once.
    I create using NetBeans IDE via JApplet forms.
    I know how to createa button and don't know how to adjust the location. Please help.
    Thanks for your help.

    In the future, Swing related questions should be posted in the Swing forum.
    Swing is different than AWT. The design of your applet is wrong.
    You should not be overriding the paint() method of the applet.
    In Swing you add components to the content pane. So in your case you would add a JPanel with your image to the content pane of the applet.
    Search the Swing forum and you will find examples of adding a "background image" to a panel.
    I know how to createa button and don't know how to adjust the location. Please help. Then don't use an IDE. Learn how to Layout Managers and design the GUIs on your own. Spend your time learning Java, not the IDE.
    Read the JButton API and you will find a link to the Swing tutorial that give an example of using buttons on a frame.

  • HELP!!!! connecting database to JApplet

    I have posted earlier and received help repainting panels on my JApplet. However, my applet doesn't retrieve data from an Access database which is also on the server in the same folder.
    When I run the class as an application on my local pc it works fine but as an applet on the server it doesn't retrieve the data. It doesn't retrieve anything. It doesn't even connect to the driver properly. My code to connect is like so:
    <code>
    //connects to database
    String dataSourceName = "http://fiji.agere.com/indrani/db1.mdb";
    String dbURL = "jdbc:odbc:" + dataSourceName;
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    }catch(Exception e){System.out.println("Could not connect to driver.");}
    try{   
    Connection con = DriverManager.getConnection(dbURL, "","");
    Statement stmt = con.createStatement();
    ResultSet result = stmt.executeQuery("SELECT Function FROM function_description ORDER BY Function ASC");
    }catch (SQLException e){System.out.println(e.getMessage());}
    </code>
    I put the code in the Init method and in myactionPerformed method.

    I have very limited experience in this area but I have got to make up for a dumb question asked elsewhere by me! So here goes, the datasource name looks wrong. It is in an internet format (HTTP...) rather than a simple file path and name. If this code is running on the actual server that the mdb file is on then I would think that the format would be similar to that of your application code.

  • JApplet does not resize correctly

    Hello,
    I'm trying to practice with JLayeredPane in JApplet.
    The problem is that when i resize the applet JButton b3 is painted "as a background", and still works as a JButton.
    Why doesn't it resize correctly as the other JComponent do?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JLayeredPaneDemo extends JApplet {
         public void paint(Graphics g) {
              final JLabel l1 = new JLabel("LABEL 1",JLabel.CENTER);
              final JLabel l2 = new JLabel("LABEL 2",JLabel.CENTER);
              final JLabel l3 = new JLabel("LABEL 3",JLabel.CENTER);
              resize(400,300);
              l1.setOpaque(true);
              l1.setBackground(Color.blue);
              l1.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l2.setOpaque(true);
              l2.setBackground(Color.green);
              l2.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l3.setOpaque(true);
              l3.setBackground(Color.yellow);
              l3.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l1.setBounds(0,0,100,100);
              l2.setBounds(30,30,100,100);
              l3.setBounds(60,60,100,100);
              getLayeredPane().add(l1,new Integer(1));
              getLayeredPane().add(l2,new Integer(2));
              getLayeredPane().add(l3,new Integer(3));
              JButton b1 = new JButton("LABEL 1 ON TOP");
              JButton b2 = new JButton("LABEL 2 ON TOP");
              JButton b3 = new JButton("LABEL 3 ON TOP");
              b1.setBounds(220,0,150,40);
              b2.setBounds(220,40,150,40);
              b3.setBounds(220,80,150,40);
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l2)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l2)+1));
                        else
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l3)+1));
              b2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l3)+1));
              b3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l2))
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l2)+1));
              add(b1);
              add(b2);
              add(b3);
    }If i use the init() method instead of the paint(Graphics g) method JButton b3 is painted as large as possible since the beginning.
    thanx in advance :)

    Swing related questions should be posted in the Swing forum.
    If i use the init() method instead of the paint(Graphics g) methodWell, thats the proper way to write a Swing applet. The code for building the GUI should be in the init() method. You never need to override the paint() method of the JApplet.
    Components will not be automatically resized when the size of the applet changes. A layered pane does not use a layout manager, therefore it is up to you to manually change the size of each component. You can add a ComponentListener to the applet to be notified when the size changes.

Maybe you are looking for

  • Stock balances by month

    Hi All Is there a report one can run to get stock balances by month for the periods that have already passed Thanks Vishnu

  • How can i get upload music from one acct to another

    How can I upload music from one acct to another

  • How can I copy a file with all attributes

    Is there a way within Java to copy a file, with all its file attributes? I have seen a number of custom methods posted on these forums for copying the contents of a file to a new file with the same name in another location. The problem is that these

  • Mass ceation of payment terms

    HI All I have to copy several payment terms from one sap system to another sap system ...is there any automated way of doing this? Thanks in advance

  • COPA Docs, values not updated

    Hi, I have few Sales orders where billing is completed and COPA document vales still zero. I found that The condition type VPRS having zero value, because the material's accounting tab is not extended. Now i have values in accounting tab. Kindly guid