Help needed on a TicTacToe java program

I am very new to java and our teacher has given us a program
that i am having quite a bit of trouble with. I was wondering if anyone could help me out.
This is the program which i have bolded.
{You will write a Java class to play the TicTacToe game. This program will have at least two data members, one for the status of the board and one to keep track of whose turn it is. All data members must be private. You will create a user interface that allows client code to play the game.
The user interface must include:
�     Boolean xPlay(int num) which allows x to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
�     Boolean oPlay(int num) which allows o to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
�     Boolean isEmpty(int num) will check to see if the square labeled by num is empty.
�     Void display() which displays the current game status to the screen.
�     Char whoWon() which will return X, O, or C depending on the outcome of the game.
�     You must not allow the same player to play twice in a row. Should the client code attempt to, xPlay or oPlay should print an error and do nothing else.
�     Also calling whoWon when the game is not over should produce an error message and return a character other than X, O, or C.
�     Client code for the moment is up to you. Assume you have two human players that can enter the number of the square in which they want to play.
Verifying user input WILL be done by the client code.}

Hi,
This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at the Java Programming forum. The URL to this forum is:
http://forum.java.sun.com/forum.jspa?forumID=31
Cheers
Giri

Similar Messages

  • Help needed in running a  java program

    hi
    how to run a java program using another java program.
    i have tried a litte to run the notepad,mspaint applications sucessfully using the Runtime class,but how to specify a java program init . the program is given below
    public class cls
    public static void main(String args[])
      Runtime r=Runtime.getRuntime();
      Process p=null;
      try{
        p=r.exec("notepad" );}
        catch(Exception e) {
        System.out.println("error on execution");
    }to run another java program how to modify the exec() or any other way to do this.

    thank u
    its working without any error but it doesn't print any thing on the screen.
    the program is
    this program to be run by cls.java
                                             // hello.java
    import java.io.*;
    public class hello
    public static void main(String[] args)
        System.out.println("hello world");
      }cls.java is given below
                                                    //cls.java
    public class cls
    public static void main(String args[])
      Runtime r=Runtime.getRuntime();
      Process p=null;
      try{
        p=r.exec("java  hello" );}
        catch(Exception e) {
        System.out.println("error on execution");
    }

  • HELP NEeded in creating tis java program

    create a prompter appliation that prompts the user for two numbers. The first number is a minimum value, and the second is a maximum value. Prompter then prompts the user for a number between the minimum and maximum numbers entered. The user should be continuously prompted until a number within the range is entered. Be sure to include the minimum and maximum numbers in prompt.
    use boolean operator in while loop
    what do do??

    so can some 1 help me"Help" as in provide workable code? They might - you did all right in your last
    thread. Personally, though, I doubt you're much helped by this.
    Start by reading the description of what your code must do. Make sure you
    understand the description - perhaps by explaining it in your own words to someone
    else. If they don't understand then you don't understand: not in any sense
    that matters.
    Then proceed to write some code. The first sentence of the description you posted
    makes a good starting point. Write some code that compiles and does this.
    Make sure you understand what each line does before moving on.
    If you get stuck post some code and an actual question. If there is a compiler error,
    copy paste and post the actual error you can't understand and say which line it refers
    to. If your code compiles but has unwanted, unexpected or mysterious results,
    say what it does and what you were expecting, or wanting.
    Hope that helps.
    (My apologies if your native language is not English, but really. Use a
    dictionary - online or, better, in paper form. Eschew abbreviations. Read what you
    post aloud or, as above, to someone else who can tell you if it makes no sense.)

  • Need some help on a medium size Java program..

    I was given a medium size Java program which contains servlets that run on a web server..
    There are some documentations, but not very detailed.
    I'm just trying to following through the codes right now and are having some trouble..
    I'm trying to find out how the program actually begin and how all the other classes related to each other..
    Is there any tools or suggestions on what I should do/use??

    That is incredibly vague question but I will try to get you thinking about some things...
    The best thing to do first and foremost is in my opinion understand the application as a user first. If you have it packaged then deploy it to a web server, and try to simply install it. Look in the documentation to see if there is any other necessary software to run correctly on the server side, JRE version? Specific web server? Database server? Before you go any further make sure that you can figure out how to not only deploy it but establish it on a local test environment and then use it to some extent.
    If you did this then look for specific technologies, is it utilizing EJB's? Spring? Hibernate?, JSP, JSF, Servlets? Then go into more details, if servlets, servlet handler controller architecture? MVC design patterns? DAO objects?
    Try to conceptualize it from the top down.
    If you have done all this then post back.

  • I need to call a java program and pass parameters from C#

    I'm new to C# and was given a project to rewrite some of my old VB.net programs to C# to help me learn.  These VB programs call quite a few .bat files that have calls to java programs in them. I'm doing okay converting my VB code, but I've been
    stumped for days trying to figure out how to call java from C#. 
    Does anyone here know how to do this?  I really should've had this figured out by now and my back is to the wall.  Ugh :(
    This is the line from the .bat file that I need to convert to C#. 
    call jvbat production_r115.Automotive m:\data\MK115mn.100 m:\data\MK115mn.101 %6
    There is one parameters being passed, %6
    I would be forever grateful if someone can show me how to do this!

    Hi Joni,
    Do you mean call a bat file that it is a Java program from C#?  If so, there is an article talking about it.
    If that's not what you're trying to do, please be more specific about what you're trying to do.
    http://www.c-sharpcorner.com/UploadFile/maheswararao/CallingJavaProgramfromCS12062005233321PM/CallingJavaProgramfromCS.aspx
    Now the next issue is pass some parameters from C#.
    The above article tells using Process.Start() method to call java program. Also  in this class, you could  specify them all in the
    Arguments property:
    var p = new Process();
    p.StartInfo.Arguments = string.Format("{0} {1}", argument1, argument2);
    For more detailed information, please refer to
    C# Passing Multiple Arguments to BAT File
    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control
    these sites and has not tested any software or information found on these sites;
    Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information
    found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Help needed in understanding the Java code.

    Hi All,
    I have recently started learning the Java language. I came across this example and had a problem in understanding the output of the program. I could follow that if the continue statement is present in the below program the output is "Found 9 p's in the string" . But if the continue statement is removed I could not understand why the output would be "Found 35 p's in the string" .Is it because of the spaces and characters other than p... (eter ier icked a eck of ickled eers)
    Example-----------------------
    The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
    class ContinueDemo {
    public static void main(String[] args) {
    String searchMe
    = "peter piper picked a " +
    "peck of pickled peppers";
    int max = searchMe.length();
    int numPs = 0;
    for (int i = 0; i < max; i++) {
    // interested only in p's
    if (searchMe.charAt(i) != 'p')
    continue;
    // process p's
    numPs++;
    System.out.println("Found " +
    numPs + " p's in the string.");
    Here is the output of this program:
    Found 9 p's in the string.
    To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

    The answer is already in your example - "The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop."
    It unloads the current loop iteration when condition is matching. Loop is again starting from boolean expression inside loop declaration.
    Java Programming - java forum

  • Help needed in executing the java/jsp program from UCM .

    Hi ,
    I have a .jsp program running in my Jdeveloper which when executed pops a window to browse and select files and with few custom options .
    But i want to execute that Program from within UCM (create a new jsp page in UCM OR provide link ? i am not sure .... ) , could anyone help on how i can execute/run the program from UCM ?
    thanks in Advance
    Plaxman

    If your jsp makes use of jars you may want to look into using a WAR instead. You can check the WAR into content server and there is even a link on the administration page for JSP Web App Admin. Treating the JSP(s) and jar(s) as an entity may be a more successful path for you.
    You can find some jsp examples and ever a war example in this directory: <install root>\samples\JspServer
    And the briefest of help about that stuff here: [http://localhost/idc/help/wwhelp/wwhimpl/js/html/wwhelp.htm|http://localhost/idc/help/wwhelp/wwhimpl/js/html/wwhelp.htm]

  • Help Needed with Computer Science Java Project!

    Hi everyone, im in my final year at uni, im implementing a board game in java. I've started programming it, but have the main part yet to do, which is the actual game play. I need someone to look at my code and give me a few pointers, or even better do it for me, all this of course after you read the game description and the project specification. Whoever maybe able to help please send me your email, and i will send you all that i have, i.e. the project proposal, game description, project specification, and the java files. Anyones help will be much appreciated and rewarded, i have only 3 - 4 weeks to complete this project and need to get a first for it. Therefore i need help urgently! You can email me at [email protected], many thanks!
    Mace

    Hi everyone, im in my final year at uni, im
    implementing a board game in java. I've started
    programming it, but have the main part yet to do,
    which is the actual game play. So, you're in your final year, and yet you still think the correct approach is to just sit down and start writing code without first figuring out what the major pieces will be and how they'll fit together. You haven't learned much then.
    I need someone to look
    at my code and give me a few pointers, or even better
    do it for me, Ah, you're one of those vile, disgusting, lowlife shitbuckets who thinks it's okay to take credit for others' work and phuck over your classmates in the process.
    I mean this sincerely: I hope you die soon. Before you have the chance to breed.

  • Help needed creating a linked list program

    I have been trying to create a linked list program that takes in a word and its definition and adds the word to a link list followed by the definition. i.e. java - a simple platform-independent object-oriented programming language.
    the thing is that of course words must be added and removed from the list. so i am going to use the compareTo method. Basically there a 2 problems
    1: some syntax problem which is causing my add and remove method not to be seen from the WordList class
    2: Do I HAVE to use the iterator class to go thru the list? I understand how the iterator works but i see no need for it.
    I just need to be pointed in the right direction im a little lost.................
    your help would be greatly appreciated i've been working on this over a week i dont like linked list..........
    Here are my 4 classes of code........
    * Dictionary.java
    * Created on November 4, 2007, 10:53 PM
    * A class Dictionary that implements the other classes.
    * @author Denis
    import javax.swing.JOptionPane;
    /* testWordList.java
    * Created on November 10, 2007, 11:50 AM
    * @author Denis
    public class Dictionary {
        /** Creates a new instance of testWordList */
        public Dictionary() {
            boolean done=false;
    String in="";
    while(done!=true)
    in = JOptionPane.showInputDialog("Type 1 to add to Dictionary, 2 to remove from Dictionary, 3 to Print Dictionary, and 4 to Quit");
    int num = Integer.parseInt(in);
    switch (num){
    case 1:
    String toAdd = JOptionPane.showInputDialog("Please Key in the Word a dash and the definition.");
    add(toAdd);
    break;
    case 2:
    String toDelete = JOptionPane.showInputDialog("What would you like to remove?");
    remove(toDelete);
    break;
    case 3:
    for(Word e: list)
    System.out.println(e);
    break;
    case 4:
    System.out.println("Transaction complete.");
    done = true;
    break;
    default:
    done = true;
    break;
       }//end switch
      }//end while
    }//end Dictionary
    }//end main
    import java.util.Iterator;
    /* WordList.java
    * Created on November 4, 2007, 10:40 PM
    *A class WordList that creates and maintains a linked list of words and their meanings in lexicographical order.
    * @author Denis*/
    public class WordList{
        WordNode list;
        //Iterator<WordList> i = list.iterator();
        /*public void main(String [] args)
        while(i.hasNext())
        WordNode w = i.next();
        String s = w.word.getWord();
        void WordList() {
          list = null;
        void add(Word b)
            WordNode temp = new WordNode(b);
            WordNode current,previous = null;
            boolean found = false;
            try{
            if(list == null)
                list=temp;
            else{
                current = list;
                while(current != null && !found)
                    if(temp.object.getWord().compareTo(current.object.getWord())<0)
                        found = true;
                    else{
                    previous=current;
                    current=current.next;
                temp.next=current;
                if(previous==null)
                    list=temp;
                else
                    previous.next=temp;
                }//end else
            }//end try
            catch (NullPointerException e)
                System.out.println("Catch at line 46");
        }//end add
    /*WordNode.java
    * Created on November 4, 2007, 10:40 PM
    *A class WordNode that contains a Word object of information and a link field that will contain the address of the next WordNode.
    * @author Denis
    public class WordNode {
        Word object;//Word object of information
        WordNode next;//link field that will contain the address of the next WordNode.
        WordNode object2;
        public WordNode (WordNode wrd)
             object2 = wrd;
             next = null;
        WordNode(Word x)
            object = x;
            next = null;
        WordNode list = null;
        //WordNode list = new WordNode("z");
        Word getWord()
            return object;
        WordNode getNode()
            return next;
    import javax.swing.JOptionPane;
    /* Word.java
    * Created on November 4, 2007, 10:39 PM
    * A class Word that holds the name of a word and its meaning.
    * @author Denis
    public class Word {
        private String word = " ";
        /** Creates a new instance of Word with the definition*/
        public Word(String w) {
            word = w;
        String getWord(){
            return word;
    }

    zoemayne wrote:
    java:26: cannot find symbol
    symbol  : method add(java.lang.String)
    location: class Dictionary
    add(toAdd);this is in the dictionary class
    generic messageThat's because there is no add(...) method in your Dictionary class: the add(...) method is in your WordList class.
    To answer your next question "+how do I add things to my list then?+": Well, you need to create an instance of your WordList class and call the add(...) method on that instance.
    Here's an example of instantiating an object and invoking a method on that instance:
    Integer i = new Integer(6); // create an instance of Integer
    System.out.println(i.toString()); // call it's toString() method and display it on the "stdout"

  • Help needed in printing in java

    hello everyone, i m in grave need of a solution of printing a java page. I have a page designed in Java swings which contains mainly labels and textareas. And i need to print this page. The problem is that I have no clue how to go ahead. Cud neone arnd pls help me on this matter asap as this is very urgent. I shall be highly obliged to all the takers on this issue. Please email me at [email protected]
    Thanks and kind regards,
    Rahul.

    http://java.sun.com/docs/books/tutorial/2d/printing/index.html

  • Help needed in executing pl/sql programs

    hi all
    iam new to PL/SQL programming
    i have installed oracle 9i
    iam trying to practice some sample pl/sql programs
    i have opened oracle 9i and typed these commands
    sql>ed sum
    then a notepad opens where i type my pl/sql program and save it and then return back to oracle 9i and type this
    sql>@ sum
    then my pl/sql program gets executed.......but iam not getting any output
    its comig as procedure implemented succesfully
    is it compulsory to open notepad to execute pl/sql progams or we can direclty type the programs in oracle 9i
    please help in this matter ASAP
    Regards
    Suresh

    Yes, you can type the program directly at the SQL prompt, but editing will be a bit difficult.
    You should use some good editor that allows you to edit properly and then run like you did.
    You need to do:
    SQL> set serveroutput onbefore running your program to see dbms_output messages.

  • Help needed for Time Calc Java Script

    Hi,
    I am trying to create a timesheet in PDF and have hit a speed bump. Is there anyone there who could provide me with a script that calculated the difference between 2 times? (Field2 time)-(Feild 1 Time) = Duration.I am desperate and have tried everything.
    I proccess the payroll for a company and all of the 500 or so timesheets that I received each fortnight are paper copies and I am pulling my hair out. I need to use Adobe forms (We have Adobe Pro 9 and I am using the XML forms, not live cycle) as the serach engine that we use for emails cannot search on excel documents.
    I have no Java script experience and I am getting completely lost in the subject. Any help would be greatly appreciated.
    Thanks anyone who can help at all.
    -Sohnia

    hi friend here example for time calulation start and end time example..<br />just copy and paste then run it ur browser.<br /><br /><HTML><br /><script language="JavaScript"><br /><!--<br /><br />var h1 = 1;<br />var h2 = 2;<br />var days = 0;<br />var m1 = 1;<br />var m2 = 2;<br />var am1 = 1;<br />var am2 = 2;<br />function findtime(h1,h2,days,m1,m2,am1,am2)<br />{<br />var answer = "why";<br />var mdiff = 1;<br />var hdiff = 2;<br />pdays = parseInt(days);<br />ph1 = parseInt(h1);<br />ph2 = parseInt(h2);<br />pm1 = parseInt(m1);<br />pm2 = parseInt(m2);<br />if(am1 == 2 & ph1 < 12) ph1 = ph1 + 12;<br />if(am2 == 2 & ph2 < 12) ph2 = ph2 + 12;<br />if(am1 == 1 & ph1 == 12) ph1 = 24;<br />if(am2 == 1 & ph2 == 12) ph2 = 24;<br />if(am1 == 2 & am2 == 1 & ph2 < 24) ph2 = ph2 + 24;<br />if(am1 == am2 & ph1 > ph2) ph2 = ph2 + 24;<br />if(pm2 < pm1){<br />pm2 = pm2 + 60;<br />ph2 = ph2 - 1;<br />}<br />mdiff = pm2 - pm1;<br />hdiff = (ph2 - ph1) + (pdays * 24);<br />if(hdiff == 0) answer = mdiff + ' minutes';<br />else if(hdiff == 1) answer = '1 hour and ' + mdiff + ' minutes'<br />else answer = hdiff + ' hours and ' + mdiff + ' minutes'<br />return answer<br />}<br /><br />//--><br /></script><br /></HEAD><br /><br /><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><br /><BODY BGCOLOR=FFFFFF TEXT=000000 LINK=0000FF VLINK=800080><br /><br /><div align="center"><table width="950" border="0" cellpadding="0" bgcolor="#899194" cellspacing="0"><br /><br />  <br /><tr><td valign="middle" width="33%"><br /><br /><center><br /><form><br /><TD WIDTH=80%><br /><center><br /><TABLE ALIGN=MIDDLE BORDER=5 CELLPADDING=5><br /><TR BGCOLOR=#FFFFFF><br /><!--ROW 1--><br /><TD WIDTH=80%><br /><center><br /><TABLE ALIGN=MIDDLE BORDER=5 CELLPADDING=5><br /><TR BGCOLOR="#B6D4D2"><br /><!--ROW 1--><br /><td colspan=4><br /><center>Time Between Times Calculations - Multiple Days</center><br /><br /></td><br /></tr><br /><TR BGCOLOR="#B6D4D2"><br /><TD align="center" colspan=4><br />Required Data Entry<br /></td><br /></tr><br /><tr><br /><td align="center">Start / End</td><br /><td align="center">Hour</td><br /><td align="center">Minute</td><br /><td align="center">AM / PM</td><br /></tr><br /><br /><td align="center">Start time</td><br /><td align="center"><input type="text" name="hour1" size="5"></td><br /><td align="center"><input type="text" name="minute1" size="5"></td><br /><td align="center"><select name="period1"><br /><option value="1">AM<br /><option value="2">PM<br /></select><br /></td><br /></tr><br /><tr><br /><td colspan="3">    Add Complete Interim Days</td><td align="center"><input type="text" name="adays" size="5" value="0"></td><br /></tr><br /><tr><br /><td align="center">Start / End</td><br /><br /><td align="center">Hour</td><br /><td align="center">Minute</td><br /><td align="center">AM / PM</td><br /></tr><br /><td align="center">End time</td><br /><td align="center"><input type="text" name="hour2" size="5"></td><br /><td align="center"><input type="text" name="minute2" size="5"></td><br /><td align="center"><select name="period2"><br /><option value="1">AM<br /><option value="2">PM<br /></select><br /></td><br /></tr><br /><br /><tr><br /><td align="center" colspan=4 BGCOLOR="#B6D4D2"><br /><input type="button" value="Calculate" <br />onclick="h1=form.hour1.value;<br />h2=form.hour2.value;<br />m1=form.minute1.value;<br />m2=form.minute2.value;<br />days=form.adays.value;<br />am1=form.period1.options[period1.selectedIndex].value;<br />am2=form.period2.options[period2.selectedIndex].value;<br />if(h1 < 0 | h1 > 12) alert('Your start hour is not valid');<br />else if(h2 < 0 | h2 > 12) alert('Your end hour is not valid');<br />else if(m1 < 0 | m1 > 59) alert('Your start minute is not valid');<br />else if(m2 < 0 | m2 > 59) alert('Your end minute is not valid');<br />else form.answer.value=findtime(h1,h2,days,m1,m2,am1,am2);"><br />   <br /><input type="reset" value="Clear Values"><br /><br /></td><br /></tr><br /><TR BGCOLOR="#B6D4D2"><br /><TD align="center" colspan=4><br />Calculated Results<br /></td><br /></tr><br /><br /><tr><br /><td align="center" colspan="4"><br />Time Difference <input type="text" name="answer" size="40"><br /><tr><td>[email protected]</td></tr><br /></td><br /></tr><br /></table><br /></form><br /></td><br /></tr><br /></table><br /><br /></center><br /></td><br /></tr><br /></table><br /></center><br /><br /></TD><br /></TR><br /></TABLE><br /></BODY> <br /></HTML>

  • Who can help me :)--a problem with java program(reset problem in java )

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.The code like this,first one is shapes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }second one is drawpanel:
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    }If any kind people who can help me.
    many thanks to you!

    4 widgets???
    maybe this is what you mean.
    add this inside your actionPerformed method for the reset action
    squareButton.setSelected(true);
    colorComboBox.setSelectedIndex(0);
    if not be more clear in your post.

  • Help NEEDED!!! - Quiz Program

    Doing a Java project, writing a Quiz program basically got multiple screens and using a Buffered reader which loads a txt folder, at the moment it reads the questions and allows u to skip questions on all 4 buttons, i know need it to count up the correct answers and have a final score etc.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import javax.swing.*;
    public class Main extends JFrame implements ActionListener
         private JButton button, buttonAns1, buttonAns2, buttonAns3, buttonAns4;
         private JPanel panel, panelAns, panelAns1, panelAns2, panelAns3, panelAns4;
         private JLabel labelTitle, labelName, labelQ1;
         BufferedReader inFile;
         boolean start =true;
         String answer = null;
         int noOfQuestions = 0;
         Main myMain ;
         MusicQuiz myMusicQuiz;
         Levels myLevels;
         public Main()
              String name;
         name = JOptionPane.showInputDialog(null,"Please enter your Name!");     
              JOptionPane.showMessageDialog(null,"Welcome " + name);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              Container c= getContentPane();
              setSize(700,600);
              panel = new JPanel();
    panel.setLayout(new GridLayout(5,1));
    panel.setSize(600,400);
              c.add(panel);
              labelTitle = new JLabel("MTV's Quiz Star");
              labelTitle.setHorizontalAlignment(JLabel.CENTER);
              panel.add(labelTitle);
              labelTitle.setFont(new Font("Tahoma",Font.BOLD,48));
              labelTitle.setForeground(Color.orange);
              labelName = new JLabel("User: "+ name);
              labelName.setHorizontalAlignment(JLabel.CENTER);
              panel.add(labelName);
              labelName.setFont(new Font("Tahoma",Font.BOLD,14));
              labelName.setForeground(Color.darkGray);
              labelQ1 = new JLabel("");
              labelQ1.setHorizontalAlignment(JLabel.CENTER);
              panel.add(labelQ1);
              labelQ1.setFont(new Font("Tahoma",Font.BOLD,24));
              labelQ1.setForeground(Color.darkGray);
              panelAns = new JPanel();
              panelAns.setLayout(new GridLayout(2,2));
              panelAns.setSize(600,400);
              panel.add(panelAns);
              buttonAns1 = new JButton("");
              buttonAns1.addActionListener(this);
              buttonAns1.setForeground(Color.darkGray);
              panelAns.add(buttonAns1);
              buttonAns2 = new JButton("");
              buttonAns2.addActionListener(this);
              buttonAns2.setForeground(Color.darkGray);
              panelAns.add(buttonAns2);
              buttonAns3 = new JButton("");
              buttonAns3.addActionListener(this);
              buttonAns3.setForeground(Color.darkGray);
              panelAns.add(buttonAns3);
              buttonAns4 = new JButton("");
              buttonAns4.addActionListener(this);
              buttonAns4.setForeground(Color.darkGray);
              panelAns.add(buttonAns4);
              setSize(600,400);
              show();
              countQuestions();
              readQuestions();
         public static void main(String[] args)
                   Main myMain = new Main();
         public void countQuestions()
              try
                   String line;
                   inFile = new BufferedReader(new FileReader("Questions.txt"));
              try
                   while ((line = inFile.readLine()) != null)
                        noOfQuestions++;
                   inFile.close();
              catch(Exception e)
         catch (FileNotFoundException e)
              System.out.println("File - Questions.txt - File Not Found");
              private void readQuestions()
                   int number = (int)(Math.random() * noOfQuestions);
                   if(start == true)
                   start = false;
              try
                   inFile = new BufferedReader(new FileReader("Questions.txt"));
                   String line = null;
                   for(int loop =0;loop < number;loop++)
                        line= inFile.readLine();
                   StringTokenizer parts = new StringTokenizer(line,"|");
                   labelQ1.setText(parts.nextToken());
                   buttonAns1.setText(parts.nextToken());
                   buttonAns2.setText(parts.nextToken());
                   buttonAns3.setText(parts.nextToken());
                   buttonAns4.setText(parts.nextToken());
                   answer = parts.nextToken();
                   inFile.close();
              catch (Exception e)
              /* (non-Javadoc)
              * @see java.awt.event.ActionListeneractionPerformed(java.awt.event.ActionEvent)
              public void actionPerformed(ActionEvent arg0)
                   if (arg0.getSource()==myMusicQuiz)
                        if(myMusicQuiz==null)
                             myMusicQuiz= new MusicQuiz();
                        else show();
                   if (arg0.getSource()==myLevels)
                        if(myLevels==null)
                             myLevels= new Levels();
                        else show();
                   if(arg0.getSource() == buttonAns1)
                        readQuestions();
                   if(arg0.getSource() == buttonAns2)
                        readQuestions();
                   if(arg0.getSource() == buttonAns3)
                        readQuestions();
                   if(arg0.getSource() ==buttonAns4)
                        readQuestions();
    }

    In case you're wondering if someone is going to do it for you, I'd guess No. So if you're still sitting there on your hands you might want to do something about it instead.

  • Help needed on to write a program on connecting to data source

    I would to program a class that connect to data source without any manually configure.
    Is there other way that i could use intsead of using
    db = DriverManager.getConnection("jdbc:odbc:Driver={SQL Server};Server=MyServerName;Database=MyDataBase","","");
    My project requires me to use JDBC-ODBC Bridge on connecting to data source on client machine
    Is there any other way?

    Oh, oh,
    why???
    It's so simple to do a JDBC connection using the same connection params, which you use for your VB program's connnection.
    If your VB prog uses a system or user DSN configured via control panel, then use the same DSN in your Java prog.
    Dear karentan,
    you have just the same question now active in 4 or 5 different topics. And I and others have not been able to understand what really is your problem, I fear.
    Would you please do two things:
    1) Start a new topic (yes, another one!) and tell us there what exactly is your problem. What do you want to do?
    Not: is it possible ... but: I want ...
    2) Go to all the other topics you spreaded here and post the link of your new topic there, so that the poor people who try to answer your 5 (always the same) questions know that they can spare their time.
    Please, hold this forum useful!
    And let us come to the point that you are helped and we are glad!

Maybe you are looking for