Java applet to draw grid

Hi, I have an exam Tuesday and an assignment Ive done before is to draw a chessboard pattern, but a past question has been to draw a grid pattern with red horizontal lines and blue vertical ones.
It must display an input dialog asking the user how many lines to draw along each side and the pattern should size itself to fit exactly with the applet area.
It says to use setColor(Color c) and fillRect(x1,y1,x2,y2): draws lines between (x1, y1) and (x2,y2)
Here's my code for the chessboard:
import java.awt.*;
import java.applet.*;
public class Q2_chessboard extends Applet {
     public void paint(Graphics g)
          int row, column, x, y;
          //for every row on the board
          for (row = 0;  row < 8;  row++ )
               //for every column on the board
               for (column = 0;  column < 8;  column++)
                    //Coordinates
                    x = column * 20;
                    y = row * 20;
                    //square is red if row and col are either both even or both odd.
                    if ( (row % 2) == (column % 2) )
                         g.setColor(Color.red);
                    else
                         g.setColor(Color.black);
                    g.fillRect(x, y, 20, 20);
}But Ive tried for ages and cant turn this code into the code needed for the past question.
I know I have to use:
          //Gets size of Applet
          int appletHeight = getSize().height;
          int appletWidth = getSize().width;But cant wrap my head around it where to use it.
I had replaced the numerical values of row and column with
          input = JOptionPane.showInputDialog("Enter number lines to draw on each side:");
          lines = Integer.parseInt(input);but it came asked twice and I couldnt expand the applet without it asking for input again.

Came up with this:
import java.awt.*;
import java.applet.*;
import javax.swing.JOptionPane;
public class VertLines extends Applet {
     public void paint(Graphics g)
          String input;
          int lines;
          input = JOptionPane.showInputDialog("Enter number of lines to draw on each side:");
          lines = Integer.parseInt(input);
          int horizontal, vertical, x, y;
          //Gets size of Applet
          int appletWidth = getSize().width;
          int appletHeight = getSize().height;
          //for every horizontal on the board
          for (horizontal = 0;  horizontal < lines;  horizontal++ )
               //Coordinates
               y = horizontal*(appletWidth/10);
               g.setColor(Color.red);
               g.drawLine(0, y, appletWidth, y);
          for (vertical = 0;  vertical < lines;  vertical++ )
               //Coordinates
               x = vertical*(appletHeight/10);
               g.setColor(Color.blue);
               g.drawLine(x, 0, x, appletHeight);
}Doesnt really do 'exactly' what I want but its the closest ive gotten and ive had to use two different loops and drawLine instead of drawRect.
The input dialog still comes up twice too.

Similar Messages

  • How i use java applet data grid i have many record i need show in grid

    hi master
    sir i have many record i want show all record in applet grid how i use grid in applet
    please send me sample code of java class how send many record to grid and applet code how use applet grid
    thanks
    aamir

    Duplicate post:
    how use the jtable in java applete
    Aamir,
    If you use JApplet then you can use JTable. Just do an Internet search for "JTable" and "applet".
    Good Luck,
    Avi.

  • Java Applets not working with Firefox 5 properly

    Java Applets work sometime. But after sometime the Java icon at the bottom (near date & time) disappears. After this no matter what I do it does not work. Java Applets are used in this case to draw charts. The same charts come out properly in Internet Explorer. But I prefer using Firefox for its speed. What is the reason for this problem ?

    -> Tap ALT key or press F10 to show the Menu Bar
    -> go to Help Menu -> select "Restart with Add-ons Disabled"
    Firefox will close then it will open up with just basic Firefox. Now do this:
    -> Update ALL your Firefox Plug-ins https://www.mozilla.com/en-US/plugincheck/
    -> go to View Menu -> Toolbars -> unselect All Unwanted toolbars
    -> go to Tools Menu -> Options -> Content -> place Checkmarks on:
    1) Block Pop-up windows 2) Load images automatically 3) Enable JavaScript
    -> go to Tools Menu -> Options -> Privacy -> History section -> ''Firefox will: '''select "Remember History"'''''
    -> go to Tools Menu -> Options -> Security -> place Checkmarks on:
    1) Warn me when sites try to install add-ons 2) Block reported attack sites 3) Block reported web forgeries 4) Remember Passwords for sites
    -> Click OK on Options window
    -> click the Favicon (small drop down menu icon) on Firefox SearchBar (its position is on the Right side of the Address Bar) -> click "Manage Search Engines" -> select all Unwanted Search Engines and click Remove -> click OK
    -> go to Tools Menu -> Add-ons -> Extensions section -> REMOVE All Unwanted/Suspicious Extensions (Add-ons) -> Restart Firefox
    You can enable your Known & Trustworthy Add-ons later. Check and tell if its working.

  • Need help with Java applet, might need NetBeans URL

    I posted the below question. It was never answered, only I was told to post to the NetBeans help forum. Yet I don't see any such forum on this site. Can someone tell me where the NetBeans help forum is located (URL).
    Here is my original question:
    I have some Java source code from a book that I want to compile. The name of the file is HashTest.java. In order to compile and run this Java program I created a project in the NetBeans IDE named javaapplication16, and I created a class named HashTest. Once the project was created, I cut and pasted the below source code into my java file that was default created for HashTest.java.
    Now I can compile and build the project with no errors, but when I try and run it, I get a dialog box that says the following below (Ignore the [...])
    [..................Dialog Box......................................]
    Hash Test class wasn't found in JavaApplication16 project
    Select the main class:
    <No main classes found>
    [..................Dialog Box......................................]
    Does anyone know what the problem is here? Why won't the project run?
    // Here is the source code: *****************************************************************************************************
    import java.applet.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import java.util.*;
    public class HashTest extends Applet implements ItemListener
    // public static void main(String[] args) {
    // Hashtable to add tile images
    private Hashtable imageTable;
    // a Choice of the various tile images
    private Choice selections;
    // assume tiles will have the same width and height; this represents
    // both a tile's width and height
    private int imageSize;
    // filename description of our images
    private final String[] filenames = { "cement.gif", "dirt.gif", "grass.gif",
    "pebbles.gif", "stone.gif", "water.gif" };
    // initializes the Applet
    public void init()
    int n = filenames.length;
    // create a new Hashtable with n members
    imageTable = new Hashtable(n);
    // create the Choice
    selections = new Choice();
    // create a Panel to add our choice at the bottom of the window
    Panel p = new Panel();
    p.add(selections, BorderLayout.SOUTH);
    p.setBackground(Color.RED);
    // add the Choice to the applet and register the ItemListener
    setLayout(new BorderLayout());
    add(p, BorderLayout.SOUTH);
    selections.addItemListener(this);
    // allocate memory for the images and load 'em in
    for(int i = 0; i < n; i++)
    Image img = getImage(getCodeBase(), filenames);
    while(img.getWidth(this) < 0);
    // add the image to the Hashtable and the Choice
    imageTable.put(filenames[i], img);
    selections.add(filenames[i]);
    // set the imageSize field
    if(i == 0)
    imageSize = img.getWidth(this);
    } // init
    // tiles the currently selected tile image within the Applet
    public void paint(Graphics g)
    // cast the sent Graphics context to get a usable Graphics2D object
    Graphics2D g2d = (Graphics2D)g;
    // save the Applet's width and height
    int width = getSize().width;
    int height = getSize().height;
    // create an AffineTransform to place tile images
    AffineTransform at = new AffineTransform();
    // get the currently selected tile image
    Image currImage = (Image)imageTable.get(selections.getSelectedItem());
    // tile the image throughout the Applet
    int y = 0;
    while(y < height)
    int x = 0;
    while(x < width)
    at.setToTranslation(x, y);
    // draw the image
    g2d.drawImage(currImage, at, this);
    x += imageSize;
    y += imageSize;
    } // paint
    // called when the tile image Choice is changed
    public void itemStateChanged(ItemEvent e)
    // our drop box has changed-- redraw the scene
    repaint();
    } // HashTest

    BigDaddyLoveHandles wrote:
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    That wasn't attention-grabbing enough apparantly. Let's try it again.
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}

  • Java Applet painting broken in IE11 and Windows 8.1

    When running a Java applet in Internet Explorer 11 window on Windows 8.1, JRE fails to repaint the viewport correctly when the web browser window is resized or scrolled. (assuming the Java Applet has display dimensions larger than the window, necessitating the need to resize or scroll host IE window). Webpage is displaying the java applet using any of OBJECT or EMBED tags. 
    This JRE behavior prevents the user from interacting successfully with the Java Applet (typically input data fields or click buttons in applet) should user need to resize or scroll the window.
    This bug only occurs on IE11 on Windows 8.1 with JRE 7 and JRE 8 (include 8u31)
    This bug does not occur on  IE11 on Windows 7,  IE10 on Windows 7 / 8 ,  Firefox on Windows  7 / 8 / 8.1 ,  Google Chrome on Windows  7 / 8 / 8.1
    This bug has also been posted to the IE Feedback website since 2013 as we do not know if this is to be resolved by Oracle or Microsoft.
    With the upcoming removal of Java Plugin support in Google Chrome, and, with this JRE bug (or incompatibility?) in IE11 Windows 8.1, this leaves only Firefox as the only usable web browser for Java Applets on Windows 8.1.  Our customer base on Windows 8.1 is only using IE11 or Chrome.  

    I am seeing a minor issue with the timesheet grid after users are upgraded from IE8 to IE11.
    We are using Project Server 2010 with SP1 and Oct 2013 CU.
    When some users (using IE11) switches between filters or views in the Timesheet page, the grid shrinks making to content un readable.  The only way to get it back is to refresh the page. After a refresh, the grid returns to normal size, but the pane
    divider is too far to the left and always must be dragged to the right in order to see the task names in the left grid. 

  • Java applet 'notinited'

    I am receiving an error when my applet is loading
    Java applet notinited
    Using comments i have traced the error to:
    Graphics tempGraph;
    Image[] grid = new grid[someNumber];
    for(int d = 0; d<someNumber; d++)
           grid[d] = createImage(200,100);               
           //the following line is where the problem is...
           tempGraph = grid[d].getGraphics();
    }Any ideas?

    This is just a guess, because I can't see all your code...
    But did you override the method init() in your applet?

  • Java Applet (Masking/Scrollbar)

    hi ppl out there.. i've some difficulties in my project.. can u all help me?
    i need to create a java applet, with a scrollbar.. <-- this i know..
    but how to create a image overlapping an image? what i mean here is that i have a image (A) appearing now.. i need to have another image(B) to be on top of it.. den when i click/drag the scrollbar, the image(B) will move alittle, showing abit of image(A).. it is like masking type.. can some kind soul share with me the source code??

    i need to create a java applet, with a scrollbar.. <-- this i know..Why not use a JSlider?
    i have a image (A) appearing now.. i need to have another image(B) to be on top of it.. You can add a JPanel to your JApplet's content pane. You'll need to create your own class that extends JPanel. By creating your own class, you can override the paintComponent() method, which is where drawing on a component takes place. paintComponent() is called automatically when the component is first displayed, and when you call repaint() on the component. You can create the JPanel and add it to your JApplet inside init().
    Inside paintComponent(), you can draw the second image on top of the first image doing this:
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.drawImage(img1, 0, 0, this); //first image
         g.drawImage(img2, 0, 0, this); //second image
    }img1 and img2 must be objects of type Image. In a JApplet, you can create Image objects from a file name like this:
    URL pic1 = new URL(getCodeBase(), "yourPic.jpg"); //.jpg file is in same directory as applet's .class file
    Image img1 = getImage(pic1);
    but how to create a image overlapping an image?If you want to move the second image over 10 pixels so that the two images are overlapping, you can do this:
    g.drawImage(img2, 10, 0, this); //x coordinate was changed from 0 to 10
    den when i click/drag the scrollbar, the image(B) will move alittle, showing abit of image(A)..You can also add a JSlider to your JApplet. A JSlider will fire a ChangeEvent event when it is moved. You can register your JPanel to listen for that event. Once your JPanel is registered for that event, the JSlider will call a stateChanged() method inside your JPanel class, which you can define to perform the tasks you want.
    If you add a member variable to your JPanel class, like
    int img2x;  //x coordinate of 2nd imageYou can read that value inside the JPanel's paintComponent() method:
    g.drawImage(img2, img2x, 0, this); //x coordinate was changed from 0 to 10If you set img2x to 0 in the JPanel's constructor, then when your JPanel is first displayed, the second image will be on top of the first image. When the user moves the slider, the stateChanged() method that you define in your JPanel class will be called. Inside stateChanged(), you can get the value of the slider; and then set img2x to that value; and then call repaint() on your JPanel. Calling repaint() on your JPanel will cause paintComponent() to be called, which will read the new value for img2x, which will cause the second image to move to the new coordinates and reveal part of the first image.
    See here for more information on how to use a JSlider:
    http://java.sun.com/docs/books/tutorial/uiswing/components/slider.html

  • Easy way to convert javascript to a java applet?

    Hello all! I am relatively new to java and java programming and had a question about converting a JavaScript to a java applet or even a standalone application. I included the JavaScript code for a checkers game below and wanted to know what would be the easiest way to convert this code if at all possible?
    Thanks in advance,
    Bob
    <SCRIPT language=JavaScript>
    <!--
    version = 1.0;
    // -->
    </SCRIPT>
    <SCRIPT language=JavaScript1.1>
    <!--
    version = 1.1;
    // -->
    </SCRIPT>
    <SCRIPT language=JavaScript>
    <!--
    if (version==1.0)
    document.write("Your browser doesn't have JavaScript 1.1 capabilities. "
    + "This checkers game script only works on Netscape 3+ and MSIE 4+.");
    // -->
    </SCRIPT>
    <SCRIPT language=JavaScript1.1>
    <!--
    // Checkers Game
    // black.gif
    // gray.gif
    // you1.gif -- normal piece (player/red)
    // you2.gif -- highlighted piece
    // you1k.gif -- kinged normal piece
    // you2k.gif -- kinged highlighted piece
    // me1.gif -- normal piece (computer/black)
    // me2.gif -- highlighted piece
    // me1k.gif -- kinged normal piece
    // me2k.gif -- kinged highlighted piece
    function preload() {
    this.length = preload.arguments.length;
    for (var i = 0; i < this.length; i++) {
    this[i] = new Image();
    this.src = preload.arguments[i];
    var pics = new preload("black.gif","gray.gif",
    "you1.gif","you2.gif","you1k.gif","you2k.gif",
    "me1.gif","me2.gif","me1k.gif","me2k.gif");
    var black = -1; // computer is black
    var red = 1; // visitor is red
    var square_dim = 35;
    var piece_toggled = false;
    var my_turn = false;
    var double_jump = false;
    var comp_move = false;
    var game_is_over = false;
    var safe_from = safe_to = null;
    var toggler = null;
    var togglers = 0;
    function Board() {
    board = new Array();
    for (var i=0;i<8; i++) {
    board[i] = new Array();
    for (var j=0;j<8;j++)
    board[i][j] = Board.arguments[8*j+i];
    board[-2] = new Array(); // prevents errors
    board[-1] = new Array(); // prevents errors
    board[8] = new Array(); // prevents errors
    board[9] = new Array(); // prevents errors
    var board;
    Board(1,0,1,0,1,0,1,0,
    0,1,0,1,0,1,0,1,
    1,0,1,0,1,0,1,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,-1,0,-1,0,-1,0,-1,
    -1,0,-1,0,-1,0,-1,0,
    0,-1,0,-1,0,-1,0,-1);
    function message(str) {
    if (!game_is_over)
    document.disp.message.value = str;
    function moveable_space(i,j) {
    // calculates whether it is a gray (moveable)
    // or black (non-moveable) space
    return (((i%2)+j)%2 == 0);
    function Coord(x,y) {
    this.x = x;
    this.y = y;
    function coord(x,y) {
    c = new Coord(x,y);
    return c;
    document.write("<table border=0 cellspacing=0 cellpadding=0 width="+(square_dim*8+8)
    +"<tr><td><img src='black.gif' width="+(square_dim*8+8)
    +" height=4><br></td></tr>");
    for(var j=0;j<8;j++) {
    document.write("<tr><td><img src='black.gif' width=4 height="+square_dim+">");
    for(var i=0;i<8;i++) {
    if (moveable_space(i,j))
    document.write("<a href='javascript:clicked("+i+","+j+")'>");
    document.write("<img src='");
    if (board[i][j]==1) document.write("you1.gif");
    else if (board[i][j]==-1) document.write("me1.gif");
    else if (moveable_space(i,j)) document.write("gray.gif");
    else document.write("black.gif");
    document.write("' width="+square_dim+" height="+square_dim
    +" name='space"+i+""+j+"' border=0>");
    if (moveable_space(i,j)) document.write("</a>");
    document.write("<img src='black.gif' width=4 height="+square_dim+"></td></tr>");
    document.write("<tr><td><img src='black.gif' width="+(square_dim*8+8)
    +" height=4><br></td></tr></table><br>"
    +"<form name='disp'><textarea name='message' wrap=virtual rows=2 cols=40></textarea><br><input "
    +"type=button value=\"Start the Game Over\" onClick=\"location.href+=''\"></form>");
    function clicked(i,j) {
    if (my_turn) {
    if (integ(board[i][j])==1) toggle(i,j);
    else if (piece_toggled) move(selected,coord(i,j));
    else message("First click one of your red pieces, then click where you want to move it");
    } else {
    message("It's not your turn yet. Hang on a sec!");
    function toggle(x,y) {
    if (my_turn) {
    if (piece_toggled)
    draw(selected.x,selected.y,"you1"+((board[selected.x][selected.y]==1.1)?"k":"")+".gif");
    if (piece_toggled && (selected.x == x) && (selected.y == y)) {
    piece_toggled = false;
    if (double_jump) { my_turn = double_jump = false; computer(); }
    } else {
    piece_toggled = true;
    draw(x,y,"you2"+((board[x][y]==1.1)?"k":"")+".gif");
    selected = coord(x,y);
    } else {
    if ((piece_toggled) && (integ(board[selected_c.x][selected_c.y])==-1))
    draw(selected_c.x,selected_c.y,"me1"+((board[selected_c.x][selected_c.y]==-1.1)?"k":"")+".gif");
    if (piece_toggled && (selected_c.x == x) && (selected_c.y == y)) {
    piece_toggled = false;
    } else {
    piece_toggled = true;
    draw(x,y,"me2"+((board[x][y]==-1.1)?"k":"")+".gif");
    selected_c = coord(x,y);
    function draw(x,y,name) {
    document.images["space"+x+""+y].src = name;
    function integ(num) {
    if (num != null)
    return Math.round(num);
    else
    return null;
    function abs(num) {
    return Math.abs(num);
    function sign(num) {
    if (num < 0) return -1;
    else return 1;
    function concatenate(arr1,arr2) {
    // function tacks the second array onto the end of the first and returns result
    for(var i=0;i<arr2.length;i++)
    arr1[arr1.length+i] = arr2[i];
    return arr1;
    function legal_move(from,to) {
    if ((to.x < 0) || (to.y < 0) || (to.x > 7) || (to.y > 7)) return false;
    piece = board[from.x][from.y];
    distance = coord(to.x-from.x,to.y-from.y);
    if ((distance.x == 0) || (distance.y == 0)) {
    message("You may only move diagonally.");
    return false;
    if (abs(distance.x) != abs(distance.y)) {
    message("Invalid move.");
    return false;
    if (abs(distance.x) > 2) {
    message("Invalid move.");
    return false;
    if ((abs(distance.x) == 1) && double_jump) {
    return false;
    if ((board[to.x][to.y] != 0) || (piece == 0)) {
    return false;
    if ((abs(distance.x) == 2)
    && (integ(piece) != -integ(board[from.x+sign(distance.x)][from.y+sign(distance.y)]))) {
    return false;
    if ((integ(piece) == piece) && (sign(piece) != sign(distance.y))) {
    return false;
    return true;
    function move(from,to) {
    my_turn = true;
    if (legal_move(from,to)) {
    piece = board[from.x][from.y];
    distance = coord(to.x-from.x,to.y-from.y);
    if ((abs(distance.x) == 1) && (board[to.x][to.y] == 0)) {
    swap(from,to);
    } else if ((abs(distance.x) == 2)
    && (integ(piece) != integ(board[from.x+sign(distance.x)][from.y+sign(distance.y)]))) {
    double_jump = false;
    swap(from,to);
    remove(from.x+sign(distance.x),from.y+sign(distance.y));
    if ((legal_move(to,coord(to.x+2,to.y+2)))
    || (legal_move(to,coord(to.x+2,to.y-2)))
    || (legal_move(to,coord(to.x-2,to.y-2)))
    || (legal_move(to,coord(to.x-2,to.y+2)))) {
    double_jump = true;
    message("You may complete the double jump or click on your piece to stay still.");
    if ((board[to.x][to.y] == 1) && (to.y == 7)) king_me(to.x,to.y);
    selected = to;
    if (game_over() && !double_jump) {
    setTimeout("toggle("+to.x+","+to.y+");my_turn = double_jump = false;computer();",1000);
    return true;
    function king_me(x,y) {
    if (board[x][y] == 1) {
    board[x][y] = 1.1; // king you
    draw(x,y,"you2k.gif");
    } else if (board[x][y] == -1) {
    board[x][y] = -1.1; // king me
    draw(x,y,"me2k.gif");
    function swap(from,to) {
    if (my_turn || comp_move) {
    dummy_src = document.images["space"+to.x+""+to.y].src;
    document.images["space"+to.x+""+to.y].src = document.images["space"+from.x+""+from.y].src;
    document.images["space"+from.x+""+from.y].src = dummy_src;
    dummy_num = board[from.x][from.y];
    board[from.x][from.y] = board[to.x][to.y];
    board[to.x][to.y] = dummy_num;
    function remove(x,y) {
    if (my_turn || comp_move)
    draw(x,y,"gray.gif");
    board[x][y] = 0;
    function Result(val) {
    this.high = val;
    this.dir = new Array();
    function move_comp(from,to) {
    toggle(from.x,from.y);
    comp_move = true;
    swap(from,to);
    if (abs(from.x-to.x) == 2) {
    remove(from.x+sign(to.x-from.x),from.y+sign(to.y-from.y));
    if ((board[to.x][to.y] == -1) && (to.y == 0)) king_me(to.x,to.y);
    setTimeout("selected_c = coord("+to.x+","+to.y+");piece_toggled = true;",900);
    setTimeout("bak=my_turn;my_turn=false;toggle("+to.x+","+to.y+");my_turn=bak;",1000);
    if (game_over()) {
    setTimeout("comp_move = false;my_turn = true;togglers=0;",600);
    message("Ok. It's your turn. You may make your move.");
    return true;
    function game_over() { // make sure game is not over (return false if game is over)
    comp = you = false;
    for(var i=0;i<8;i++) {
    for(var j=0;j<8;j++) {
    if(integ(board[i][j]) == -1) comp = true;
    if(integ(board[i][j]) == 1) you = true;
    if (!comp) message("You beat me!");
    if (!you) message("Gotcha! Game over.");
    game_is_over = (!comp || !you)
    return (!game_is_over);
    // the higher the jump_priority, the more often the computer will take the jump over the safe move
    var jump_priority = 10;
    function computer() {
    // step one - prevent any jumps
    for(var j=0;j<8;j++) {
    for(var i=0;i<8;i++) {
    if (integ(board[i][j]) == 1) {
    if ((legal_move(coord(i,j),coord(i+2,j+2))) && (prevent(coord(i+2,j+2),coord(i+1,j+1)))) {
    return true;
    } if ((legal_move(coord(i,j),coord(i-2,j+2))) && (prevent(coord(i-2,j+2),coord(i-1,j+1)))) {
    return true;
    } if (board[i][j] == 1.1) {
    if ((legal_move(coord(i,j),coord(i-2,j-2))) && (prevent(coord(i-2,j-2),coord(i-1,j-1)))) {
    return true;
    } if ((legal_move(coord(i,j),coord(i+2,j-2))) && (prevent(coord(i+2,j-2),coord(i+1,j-1)))) {
    return true;
    // step two - if step one not taken, look for jumps
    for(var j=7;j>=0;j--) {
    for(var i=0;i<8;i++) {
    if (jump(i,j))
    return true;
    safe_from = null;
    // step three - if step two not taken, look for safe single space moves
    for(var j=0;j<8;j++) {
    for(var i=0;i<8;i++) {
    if (single(i,j))
    return true;
    // if no safe moves, just take whatever you can get
    if (safe_from != null) {
    move_comp(safe_from,safe_to);
    } else {
    message("You beat me!!");
    game_is_over = true;
    safe_from = safe_to = null;
    return false;
    function jump(i,j) {
    if (board[i][j] == -1.1) { 
    if (legal_move(coord(i,j),coord(i+2,j+2))) {
    move_comp(coord(i,j),coord(i+2,j+2));
    setTimeout("jump("+(i+2)+","+(j+2)+");",500);
    return true;
    } if (legal_move(coord(i,j),coord(i-2,j+2))) {
    move_comp(coord(i,j),coord(i-2,j+2));
    setTimeout("jump("+(i-2)+","+(j+2)+");",500);
    return true;
    } if (integ(board[i][j]) == -1) {
    if (legal_move(coord(i,j),coord(i-2,j-2))) {
    move_comp(coord(i,j),coord(i-2,j-2));
    setTimeout("jump("+(i-2)+","+(j-2)+");",500);
    return true;
    } if (legal_move(coord(i,j),coord(i+2,j-2))) {
    move_comp(coord(i,j),coord(i+2,j-2));
    setTimeout("jump("+(i+2)+","+(j-2)+");",500);
    return true;
    return false;
    function single(i,j) {
    if (board[i][j] == -1.1) {
    if (legal_move(coord(i,j),coord(i+1,j+1))) {
    safe_from = coord(i,j);
    safe_to = coord(i+1,j+1);
    if (wise(coord(i,j),coord(i+1,j+1))) {
    move_comp(coord(i,j),coord(i+1,j+1));
    return true;
    } if (legal_move(coord(i,j),coord(i-1,j+1))) {
    safe_from = coord(i,j);
    safe_to = coord(i-1,j+1);
    if (wise(coord(i,j),coord(i-1,j+1))) {
    move_comp(coord(i,j),coord(i-1,j+1));
    return true;
    } if (integ(board[i][j]) == -1) {
    if (legal_move(coord(i,j),coord(i+1,j-1))) {
    safe_from = coord(i,j);
    safe_to = coord(i+1,j-1);
    if (wise(coord(i,j),coord(i+1,j-1))) {
    move_comp(coord(i,j),coord(i+1,j-1));
    return true;
    } if (legal_move(coord(i,j),coord(i-1,j-1))) {
    safe_from = coord(i,j);
    safe_to = coord(i-1,j-1);
    if (wise(coord(i,j),coord(i-1,j-1))) {
    move_comp(coord(i,j),coord(i-1,j-1));
    return true;
    return false;
    function possibilities(x,y) {
    if (!jump(x,y))
    if (!single(x,y))
    return true;
    else
    return false;
    else
    return false;
    function prevent(end,s) {
    i = end.x;
    j = end.y;
    if (!possibilities(s.x,s.y))
    return true;
    else if ((integ(board[i-1][j+1])==-1) && (legal_move(coord(i-1,j+1),coord(i,j)))) {
    return move_comp(coord(i-1,j+1),coord(i,j));
    } else if ((integ(board[i+1][j+1])==-1) && (legal_move(coord(i+1,j+1),coord(i,j)))) {
    return move_comp(coord(i+1,j+1),coord(i,j));
    } else if ((board[i-1][j-1]==-1.1) && (legal_move(coord(i-1,j-1),coord(i,j)))) {
    return move_comp(coord(i-1,j-1),coord(i,j));
    } else if ((board[i+1][j-1]==-1.1) && (legal_move(coord(i+1,j-1),coord(i,j)))) {
    return move_comp(coord(i+1,j-1),coord(i,j));
    } else {
    return false;
    function wise(from,to) {
    i = to.x;
    j = to.y;
    n = (j>0);
    s = (j<7);
    e = (i<7);
    w = (i>0);
    if (n&&e) ne = board[i+1][j-1]; else ne = null;
    if (n&&w) nw = board[i-1][j-1]; else nw = null;
    if (s&&e) se = board[i+1][j+1]; else se = null;
    if (s&&w) sw = board[i-1][j+1]; else sw = null;
    eval(((j-from.y != 1)?"s":"n")+((i-from.x != 1)?"e":"w")+"=0;");
    if ((sw==0) && (integ(ne)==1)) return false;
    if ((se==0) && (integ(nw)==1)) return false;
    if ((nw==0) && (se==1.1)) return false;
    if ((ne==0) && (sw==1.1)) return false;
    return true;
    message("You may begin! Select a piece to move.");
    my_turn = true;
    // -->
    </SCRIPT>

    Well, you can get a free tutorial to Java at http://www.mindview.net/. It's the "Thinking In Java" book. You can download the whole book from that site, it's about a thousand pages. If you read that whole book, you'll know exactly where to start and probably how to finish it too.
    As a gimmie, think about it -- you'll have to remove all of the browser-detect code, since browser-detection is only done to determine which version of JavaScript is supported by the browser.

  • Need help with classes in Applets and drawing buildings.

    I'm trying to create an Applet that draws a starfield (I got that right) and then searches for any parameters in the Applet tag. The Applet then draws as many buldings as there are parameters in the Applet tag, and uses the number in the parameter as the height. I have it working OK, but it won't draw the buildings. Here is me code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    public class Skyline extends Applet {
    public void init() {
    setBackground(Color.black);
    public void paint(Graphics g) {
    Graphics2D pen = (Graphics2D) g;
    Random generator = new Random();
    Stars starField = new Stars();
    starField.drawStars(pen, getWidth(), getHeight());
    int n = 1;
    String param = null;
    while((param = getParameter("param" + n)) != null) {
    n++;
    int startX = 0;
    int startY = getHeight();
    int height = 0;
    int width = getWidth() / (n + 2);
    Building structure = new Building();
    structure.drawBuilding(pen, height, width, startX, startY, n);
    class Stars {
    public void drawStars(Graphics2D pen, int Width, int Height) {
    Random generator = new Random();
    int runs = 1;
    while (runs <= 1000) {
    int Xcord = generator.nextInt(Width - 3);
    int Ycord = generator.nextInt(Height - 3);
    Ellipse2D.Double star
    = new Ellipse2D.Double(Xcord, Ycord, 3, 3);
    pen.setColor(Color.white);
    pen.fill(star);
    runs++;
    class Building {
    public void drawBuilding(Graphics2D pen, int height, int width, int startX, int startY, int n) {
    Random generator = new Random();
    int n2 = 1;
    int runs = 1;
    String input = "";
    int red = generator.nextInt(100),
    green = generator.nextInt(100),
    blue = generator.nextInt(100);
    pen.setColor(new Color(red, green, blue));
    while (runs <= n) {
    input = getParameter("building" + n2);
    height = Integer.parseInt(input);
    height = startY - height;
    Rectangle building = new Rectangle(startX, startY, height, width);
    pen.fill(building);
    startY = startY + width;
    n2++;
    runs++;
    Can anyone help me?

    That didn't work, so I looked at the code again and found some errors. I decided to rewrite it, here is the updated code...
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    public class Skyline extends Applet {
    public void init() {
    setBackground(Color.black);
    public void paint(Graphics g) {
    Graphics2D pen = (Graphics2D) g;
    Random generator = new Random();
    Stars starField = new Stars();
    starField.drawStars(pen, getWidth(), getHeight());
    Building structure = new Building();
    structure.drawBuilding(pen);
    class Stars {
    public void drawStars(Graphics2D pen, int Width, int Height) {
    Random generator = new Random();
    int runs = 1;
    while (runs <= 1000) {
    int Xcord = generator.nextInt(Width - 3);
    int Ycord = generator.nextInt(Height - 3);
    Ellipse2D.Double star
    = new Ellipse2D.Double(Xcord, Ycord, 3, 3);
    pen.setColor(Color.white);
    pen.fill(star);
    runs++;
    class Building {
    public void drawBuilding(Graphics2D pen) {
    Random generator = new Random();
    int n = 1;
    int n2 = 1;
    int runs = 1;
    String input = "";
    String param = "";
    while ((param = getParameter("building" + n)) != null) {
    n++;
    int height = getHeight();
    int width = getWidth();
    int startX = 0;
    int startY = height;
    int red = generator.nextInt(100),
    green = generator.nextInt(100),
    blue = generator.nextInt(100);
    pen.setColor(new Color(red, green, blue));
    while (runs <= n) {
    height = getHeight();
    input = getParameter("building" + n2);
    height = Integer.parseInt(input);
    height = startY - height;
    Rectangle building = new Rectangle(startY, startX, height, width);
    pen.fill(building);
    startX = startX + width;
    n2++;
    runs++;
    I can get it to draw one large black building, but that's it.

  • Why is it unable to read URL through Java Applet ?

    I have tried to read an image with ImageIO.read(URL) in JApplet. But it failed to be initialized. Please refer to TEST.java. But if I read the image in MSDOS mode, it works. Please refer to DisplayImage.java. The only difference is Applet and MSDOS mode.
    I am using WindowsXP with j2sdk1.4.1_01 installed.
    //File one: TEST.java
    //Please run in Applet mode
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.net.*;
    public class TEST extends JApplet
         BufferedImage tempimg;
         public void init()
              try
                   tempimg = ImageIO.read(new URL("http", "www.footprint.org.hk", 80, "/newsphotos/N200301270_0.jpg"));
              catch(MalformedURLException murle){}
              catch(IOException ioe){}
              JFrame f = new JFrame("ImageDisplayer");
              f.setSize(new Dimension(550,350));
              f.setVisible(true);
    //End of TEST.java
    //File two: DisplayImage.java
    //Please run in MSDOS mode
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.net.*;
    public class DisplayImage extends JApplet
         ImagePanel imagePanel;
         public static void main(String[] args) throws MalformedURLException, IOException
              DisplayImage img = new DisplayImage();
              img.init();
         public void init()
              //Display Image
              try
                   imagePanel = new ImagePanel(ImageIO.read(new URL("http", "www.footprint.org.hk", 80, "/newsphotos/N200301270_0.jpg")));
              catch(MalformedURLException murle){}
              catch(IOException ioe){}
    JFrame f = new JFrame("ImageDisplayer");
              f.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              f.getContentPane().add(imagePanel, BorderLayout.CENTER);
              f.setSize(new Dimension(550,350));
              f.setVisible(true);
    class ImagePanel extends JPanel {
    Image image;
    public ImagePanel(Image image) {
    this.image = image;
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    //Draw image at its natural size first.
    g.drawImage(image, 0, 0, this); //85x62 image
    //End of DisplayImage.java

    The security model for applets does not allow them to read from a URL unless it is on the same host the applet was loaded from. If you must do this then you must sign your applet for it to work.

  • Newbie need help wtih Java Applet noinit error

    Hi, i am having problem with a making this java applet application run, i am new to java but i am sure that my coding is right, because this what i typed from my java class book. Don't know why when i try to run it is say at the bottom of the windows explorer, "applet class name "noinit"". The code is listed below maybe someone could help me figure this out. I used NetBean to compile it, also I have the latest version of java but could not find a applet that come with the newest version of java so I'm using the j2sdk1.4.2_11 applet, and have added it to my system environment path. Maybe that could be the problem if so where do i get the newest version of the applet, because without doing what i did i could run applets in the first place. My other sample applet sample (demo's) that come with Java runs fine without any problem. Only when i run mine i get the message, "applet class name noinit".
    HTML file:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Welcome Applet</title>
    </head>
    <!-- Used to load the Java .class file -->
    <applet code="WelcomeApplet.class" width="300" height="45">
    alt="Your browser understands the <;APPLET> tag but isn't running the applet, for some reason."
         Your browser is completely ignoring the <APPLET> tag!
    </applet>
    <body>
    </body>
    </html>Java code:
    /* Fig. 3.6: WelcomeApplet.java
    *  My first applet in Java
    * Created on May 2, 2006, 2:50 AM
    // Java packages
    package appletjavafig3_6;
    import java.awt.Graphics;   // import class Graphics
    import javax.swing.JApplet; // import class JApplet
    public class WelcomeApplet extends JApplet {
        public WelcomeApplet(){
        // 3rd method that is called by default
        // draw text on applets's background
        public void paint( Graphics g)
            // call superclass version of method paint
            super.paint(g);
            // draw a String at x-coordinate 25 and y coordinate 25
            g.drawString("Welcome to Java Programming!", 25,25);
        } // end method paint
    } // WelcomeApplet

    Hi,
    Your applet code in the html should be
    <applet code="appletjavafig3_6.WelcomeApplet" width="300" height="45">
    alt="Your browser understands the <;APPLET> tag but isn't running the applet, for some reason."
         Your browser is completely ignoring the <APPLET> tag!
    </applet>As the class is inside a package named appletjavafig3_6, put the class file inside a folder named appletjavafig3_6. Put the html file outside this folder and test it.

  • JavaScript calls method on Java Applet-- Problem

    Hi all,
    I have a problem as following:
    I have a method on JavaScript calling a method on Java Applet. A method on JavaScript repeatedly retrieves data form the server , let's say; every 100 ms and it calls the method on Java to draw a graph(I use thread to call repaint()). The problem is, if I leave the applet site(or the site has lost the focus), the stop() will be called and I can't recieve data from JavaScript anymore. If I go back to the site, the applet starts, but the graph doesn't show the figure, as it supposes to show.
    how can I tell the browser doesn't call the stop() or there is another way to solve this problem?
    Thanks for all answers. CU.
    A-Pex

    my own fault.. it's not the browser or the applet.. It's my computer.. it's too old for this applet..
    Does anyone know, how to optimize the applet with thread? thanks..

  • Java Applet painting outside it's borders?!

    Hello all, I have a java applet that is painting outside of it's bordors in Firefox and IE, only when scrolling does this occur. I have been searching around and found a bug which was submitted in 2006 for the same issue but cannot see any resolution or further issues. I imagine there must be a workaround as this would be quite a major issue if it was always the case. It only happens when scrolling and the applet is being repainted. Any ideas?
    Thanks
    Dori

    here we go!
    package main;
    import javax.swing.JApplet;
    public class Test extends JApplet
         private GamePanel gamePanel;
        public Test()
        public void init()
        public void start()
            //create a new GamePanel
             gamePanel = new GamePanel();
             //add the panel to the contentPane
             this.getContentPane().add(gamePanel);
        }//EOM
        public void stop()
             gamePanel.stopTimer();
        public void destroy()
            System.out.println("preparing for unloading...");
    }and
    package main;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.JPanel;
    public class GamePanel extends JPanel{
         private static final int PWIDTH = 400;
         private static final int PHEIGHT = 400;
         private StringBuffer buffer;
         private int clickCounter = 0;
         private static final int FONTSIZE = 100;
         //timer period in ms
         private static final int PERIOD = 100;
         //game length (seconds)
         private static final int GAME_LENGTH = 5;
         //for the timer
         private long startTime;
         //image for Double buffering
         private Image dbImage = null;
         //timer
         Timer t = null;
         private boolean debug = true;
         private boolean gameRunning = false;
         public GamePanel(){
              setBackground(Color.gray);
              setSize( new Dimension(PWIDTH, PHEIGHT));
              setFocusable(true); //to receive key events
             requestFocus();
             addMouseListener( new MouseAdapter() {
                public void mousePressed(MouseEvent e)
                { doMouseAction(); }
             setUpNewGame();
         }//EOC
         public void setUpNewGame(){
             //set gameRunning to true, affects click actions
             gameRunning = true;
             //set counter to 0
             clickCounter = 0;
            MyTimerTask task = new MyTimerTask();
            t = new Timer();
            t.scheduleAtFixedRate(task,0,PERIOD);
            //for the timer
            startTime = System.currentTimeMillis();
        }//EOM
          private void doMouseAction(){
             if(gameRunning == true){
                  incrementCounter();
             else if(gameRunning == false){
                  setUpNewGame();
         }//EOM
          public void stopTimer(){
               t.cancel();
              System.out.println("Timer stopped!");
          public void timesUp(){
             //stop the timer
             stopTimer();
             //set game running to false
             gameRunning = false;
             //show gameover message
             //overwrite dbimage with score
            Graphics dbg = dbImage.getGraphics();
             //clear the image
             dbg.setColor(Color.gray);
             dbg.fillRect(0, 0, getWidth(), getHeight());
             //write the score
             dbg.setColor(Color.white);
             dbg.drawString("Your score was "+clickCounter+" clicks in "+GAME_LENGTH+" secs", 10, 40);
             //draw this to screen
             repaint();
         public void paintComponent(Graphics g)
            super.paintComponent(g);
             g.drawImage(dbImage, 0, 0, null);
        //draw to dbImage
        public void renderImage(){
             //for debug only
            long startRenderTime = System.nanoTime();
             //this will be removed, on init it should take the attributes from the html
             //and create the dbimage only once with these params
            //out(""+dbImage);
             dbImage = createImage(getWidth(), getHeight());
             out(dbImage+","+getWidth()+","+getHeight());
             Graphics dbg = dbImage.getGraphics();
             //this code should be here
             dbg.setColor(Color.gray);
             dbg.fillRect(0,0, getWidth(), getHeight());
             dbg.setColor(Color.white);
            dbg.setFont(new Font("ARIAL BOLD",Font.PLAIN,FONTSIZE));
            dbg.drawString(""+clickCounter,(getWidth()/2),(getHeight()/2));
            //draw timer
            dbg.setFont(new Font("ARIAL",Font.PLAIN,15));
            //calc time
            long currentTime = System.currentTimeMillis() - startTime;
            //for display in secs
            float floatTime = (float)((int)(currentTime/100f))/10f;
            dbg.drawString(""+floatTime, 10, getHeight()-10);
            //dbg.dispose();//test
            if(false){ //test for game over here
                 //draw game over stuff here
            if(debug){
                 //in ms
                 long totalRenderTime = (System.nanoTime() - startRenderTime)/1000000L;
                 System.out.println("Total Render Time = "+totalRenderTime+" ms, allowed "+PERIOD+"ms");
        }//EOM
        public void incrementCounter(){
             clickCounter++;
         private class MyTimerTask extends TimerTask{     
             public void run(){
                  renderImage();
                  repaint();
                  if(System.currentTimeMillis()-startTime >= GAME_LENGTH*1000){
                       //stop the game
                       timesUp();
        }//End of inner class
          * Debugging method
          * @param out
         private void out(String out){
              System.out.println(out);
    }//End of class

  • Cannot initiate java applet

    I am trying to rework a Java Applet. It should work, but for some reason, when I put it into an html container I get this in the debug window:
    java.lang.NoClassDefFoundError: CroaxApplet (wrong name: Croax/CroaxApplet)
    This seems to have something to do with CroaxApplet.class being a part of the package "Croax," but I am unsure how to solve the problem. Anyone?
    Edited by: monocledsardine on Jan 12, 2008 11:42 AM

    Here's the code:
    package Croax;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.net.*;
    import javax.imageio.*;
    public class CroaxApplet extends Applet implements Runnable, KeyListener {
        final int roomWidth = 800;
        final int roomHeight = 600;
        Image dbimg;
        Graphics dbg;
        boolean keyLeft, keyRight, keyUp, keyDown=false;
        boolean keyPressLeft, keyPressRight, keyPressUp, keyPressDown=false;
        public void init(){
            addKeyListener(this);
        public void start(){
            Thread th = new Thread(this);
            th.start();
        public void destroy(){
        public void keyTyped(KeyEvent e){
        public void keyPressed(KeyEvent e){
            if (e.getKeyCode() == 37){
                keyLeft=true;
                keyPressLeft=true;
            if (e.getKeyCode() == 39){
                keyRight=true;
                keyPressRight=true;
            if (e.getKeyCode() == 38){
                keyUp=true;
                keyPressUp=true;
            if (e.getKeyCode() == 40){
                keyDown=true;
                keyPressDown=true;
        public void keyReleased(KeyEvent e){
            if (e.getKeyCode() == 37){
                keyLeft=false;
            if (e.getKeyCode() == 39){
                keyRight=false;
            if (e.getKeyCode() == 38){
                keyUp=false;
            if (e.getKeyCode() == 40){
                keyDown=false;
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true){
                repaint();
                try{
                    Thread.sleep(20);
                } catch (InterruptedException e){
                    e.printStackTrace();
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        public void update(Graphics g){
            if (dbimg == null){
                dbimg = createImage(this.getSize().width, this.getSize().height);
                dbg = dbimg.getGraphics();
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            dbg.setColor(getForeground());
            draw(dbg);
            paint(g);
        public void paint(Graphics g){
            g.drawImage(dbimg, 0, 0, this);
        public void draw(Graphics g){
    }

  • Java Applet Question

    I was wondering how I would go about saving the 'state' of a java applet. For instance if I created a drawing program, how would i create a feature so the user could save their drawing to work on later?

    Most probably it'll have to be persisted on your server. Sandboxing dictates that an applet can't have access to a local filesystem, and although this can be gotten around, ask yourself "would I like to install a piece of software from an unknown source that can access my hard drive through my web browser?". Personally, I wouldn't

Maybe you are looking for