JOptionPane in applet - Help!

Beginning to write a program and narrowed down the problem. When I ask for an input for the number of sticks to take away, the popup keeps coming back! How do I make the program accept the first input and stop?
Thanks!
import java.util.*;
import java.applet.Applet;
import javax.swing.JOptionPane;
import java.awt.*;
public class jaeglenim2 extends Applet
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
g2.drawString("The Game of Nim", 100,30);
Random generator = new Random();
boolean smart = true;
boolean firstPlayer = true;
int totalNumber = 10 + generator.nextInt(100);
g2.drawString("Total number of sticks left: " + totalNumber,300,50);
if (firstPlayer == true)
g2.drawString("You go first.", 0,60);
String input = JOptionPane.showInputDialog("Choose the number of sticks to take away.");
int number = Integer.parseInt(input);
g2.drawString("You take " + number, 0,80);
totalNumber = totalNumber - number;
g2.drawString("Total number of sticks left: " + totalNumber, 300, 80);
else
g2.drawString("Computer goes first.",0,60);
System.exit(0)

You shouldn't ask for input in the paint method, that method should restrict its actions to graphics.

Similar Messages

  • Simple button applet help

    ok, i'm working on a project involving buttons, and i finished it and it compiles fine, but when i run the applet (using textpad), nothign shows up.
    i decided to make a new applet of only the frame and buttons, and i got the same problem. here is the simple one.
    import java.util.*;
    import java.applet.Applet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class framek extends JApplet
         public static final int WIDTH = 600;
         public static final int HEIGHT = 300;
         public void framek()
              JFrame myWindow = new JFrame();
              myWindow.setSize(WIDTH, HEIGHT);
         Container contentPane = myWindow.getContentPane();
              contentPane.setBackground(Color.blue);
              contentPane.setLayout(new BorderLayout());
              JPanel button = new JPanel();
              button.setLayout(new FlowLayout());
              JButton convert = new JButton("Translate");
              button.add(convert);
              JButton delete = new JButton("Delete");
              button.add(delete);
              contentPane.add(button, BorderLayout.SOUTH);
    i might have made some mistakes in the shortening of my project (such as variables that arent used) but i just need help with getting the buttons and background things to show. I used very similar programs in a textbook and on the web to check and they worked fine on textpad, and this doesnt. its probably a very simple thing that i forgot but i cant find it yet, as i am fairly new to swing.
    any help is appreciated thanks

    /*  <applet code="HelloApplet" width="600" height="300"></applet>
    *  use: >appletviewer HelloApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class HelloApplet extends JApplet
        public static final int WIDTH = 600;
        public static final int HEIGHT = 300;
        public void init()
            Container contentPane = getContentPane();
            contentPane.setBackground(Color.blue);
            contentPane.setLayout(new BorderLayout());
            JPanel button = new JPanel();
            button.setLayout(new FlowLayout());
            JButton convert = new JButton("Translate");
            button.add(convert);
            JButton delete = new JButton("Delete");
            button.add(delete);
            contentPane.add(button, BorderLayout.SOUTH);
        /** this is a convenience method */
        public static void main(String[] args)
            JApplet applet = new HelloApplet();
            JFrame myWindow = new JFrame();
            myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myWindow.add(applet);
            myWindow.setSize(WIDTH, HEIGHT);
            myWindow.setLocation(200,200);
            applet.init();
            myWindow.setVisible(true);
    }

  • Using my new GUI component in an applet :Help!!!

    I am seeking help for the following
    Define class MyColorChooser as a new component so it can be reused in other applications or applets. We want to use the new GUI component as part of an applet that displays the current Color value.
    The following is the code of MyColorChooser class
    * a) We define a class called MyColorChooser that provides three JSlider
    * objects and three JTextField objects. Each JSlider represents the values
    * from 0 to 255 for the red, green and blue parts of a color.
    * We use wred, green and blue values as the arguments to the Color contructeur
    * to create a new Color object.
    * We display the current value of each JSlider in the corresponding JTextField.
    * When the user changes the value of the JSlider, the JTextField(s) should be changed
    * accordingly as weel as the current color.
    * b)Define class MyColorChooser so it can be reused in other applications or applets.
    * Use your new GUI component as part of an applet that displays the current
    * Color value.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class MyChooserColor extends JFrame{
         private int red, green, blue;  // color shade for red, green and blue
         private static Color myColor;  // color resultant from red, green and blue shades
         private JSlider mySlider [];      
         private JTextField textField [];
    // Panels for sliders, textfields and button components
         private JPanel mySliderPanel, textFieldPanel, buttonPanel;
    // sublcass objet of JPanel for drawing purposes
         private CustomPanel myPanel;
         private JButton okButton, exitButton;
         public MyChooserColor ()     
              super( "HOME MADE COLOR COMPONENT; composition of RGB values " );
    //       setting properties of the mySlider array and registering the events
              mySlider = new JSlider [3];
              ChangeHandler handler = new ChangeHandler();
              for (int i = 0; i < mySlider.length; i++)
              {     mySlider[i] = new JSlider( SwingConstants.HORIZONTAL,
                               0, 255, 255 );
                   mySlider.setMajorTickSpacing( 10 );
                   mySlider[i].setPaintTicks( true );
    //      register events for mySlider[i]
                   mySlider[i].addChangeListener( handler);                     
    //      setting properties of the textField array           
              textField = new JTextField [3];          
              for (int i = 0; i < textField.length; i++)
              {     textField[i] = new JTextField("100.00%", 5 );
                   textField[i].setEditable(false);
                   textField[i].setBackground(Color.white);
    // initial Background color of each slider and foreground for each textfield
    // accordingly to its current color shade
              mySlider[0].setBackground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );
              textField[0].setForeground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );           
              mySlider[1].setBackground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              textField[1].setForeground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              mySlider[2].setBackground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
              textField[2].setForeground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
    // initialize myColor to white
              myColor = Color.WHITE;
    // instanciate myPanel for drawing purposes          
              myPanel = new CustomPanel();
              myPanel.setBackground(myColor);
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
    //      instanciate exitButton with its inanymous class
    //      to handle its related events           
              exitButton = new JButton("Exit");
              exitButton.setToolTipText("Exit the application");
              exitButton.setMnemonic('x');
              exitButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed (ActionEvent e)
                             {     System.exit( 0 );     
    // define the contentPane
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
    //     panel as container for sliders
              mySliderPanel = new JPanel(new BorderLayout());
    //      panel as container for textFields           
              textFieldPanel = new JPanel(new FlowLayout());
    //      panel as container for Jbuttons components           
              buttonPanel = new JPanel ();
              buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
    //add the Jbutton components to buttonPanel           
              buttonPanel.add(okButton);
              buttonPanel.add(exitButton);
    //     add the mySlider components to mySliderPanel
              mySliderPanel.add(mySlider[0], BorderLayout.NORTH);
              mySliderPanel.add(mySlider[1], BorderLayout.CENTER);
              mySliderPanel.add(mySlider[2], BorderLayout.SOUTH);
    //add the textField components to textFieldPanel     
              for (int i = 0; i < textField.length; i++){
                   textFieldPanel.add(textField[i]);
    // add the panels to the container c          
              c.add( mySliderPanel, BorderLayout.NORTH );
              c.add( buttonPanel, BorderLayout.WEST);
              c.add( textFieldPanel, BorderLayout.SOUTH);
              c.add( myPanel, BorderLayout.CENTER );
              setSize(500, 300);          
              show();               
    //     inner class for mySlider events handling
         private class ChangeHandler implements ChangeListener {          
              public void stateChanged( ChangeEvent e )
    // start by collecting the current color shade
    // for red , forgreen and for blue               
                   setRedColor(mySlider[0].getValue());
                   setGreenColor(mySlider[1].getValue());
                   setBlueColor(mySlider[2].getValue());
    //The textcolor in myPanel (subclass of JPanel for drawing purposes)
                   myPanel.setMyTextColor( ( 255 - getRedColor() ),
                             ( 255 - getGreenColor() ), ( 255 - getBlueColor() ) );
    //call to repaint() occurs here
                   myPanel.setThumbSlider1( getRedColor() );
                   myPanel.setThumbSlider2( getGreenColor() );
                   myPanel.setThumbSlider3( getBlueColor() );
    // display color value in the textFields (%)
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   for (int i = 0; i < textField.length; i++){
                        textField[i].setText("" + twoDigits.format(
                                  100.0* mySlider[i].getValue()/255) + " %") ;
    // seting the textcolor for each textField
    // and the background color for each slider               
                   textField[0].setForeground(
                             new Color ( getRedColor(), 0, 0 ) );
                   mySlider[0].setBackground(
                             new Color ( getRedColor(), 0, 0) );
                   textField[1].setForeground(
                             new Color ( 0, getGreenColor() , 0 ) );
                   mySlider[1].setBackground(
                             new Color ( 0, getGreenColor(), 0) );
                   textField[2].setForeground(
                             new Color ( 0, 0, getBlueColor() ) );
                   mySlider[2].setBackground(
                             new Color ( 0, 0, getBlueColor() ) );
    // color of myPanel background
                   myColor = new Color (getRedColor(),
                             getGreenColor(), getBlueColor());
                   myPanel.setBackground(myColor);               
    // set methods to set the basic color shade
         private void setRedColor (int r){
              red = ( (r >= 0 && r <= 255) ? r : 255 );
         private void setGreenColor (int g){
              green = ( (g >= 0 && g <= 255) ? g : 255 );
         private void setBlueColor (int b){
              blue = ( (b >= 0 && b <= 255) ? b : 255 );
    // get methods (return the basic color shade)
         private int getRedColor (){
              return red ;
         private int getGreenColor (){
              return green;
         private int getBlueColor (){
              return blue;
         public static Color getMyColor (){
              return myColor;
    // main method                
         public static void main (String args []){
              MyChooserColor app = new MyChooserColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {     System.exit( 0 );
    // inner class CustomPanel for drawing purposes
         private class CustomPanel extends JPanel {
              private int thumbSlider1 = 255;
              private int thumbSlider2 = 255;
              private int thumbSlider3 = 255;
              private Color myTextColor;
              public void paintComponent( Graphics g )
                   super.paintComponent( g );
                   g.setColor(myTextColor);
                   g.setFont( new Font( "Serif", Font.TRUETYPE_FONT, 12 ) );
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   g.drawString( "The RGB values of the current color are : "
                             + "( "     + thumbSlider1 + " , " + thumbSlider2 + " , "
                             + thumbSlider3 + " )", 10, 40);
                   g.drawString( "The current background color is composed by " +
                             "the folllowing RGB colors " , 10, 60);
                   g.drawString( "Percentage of RED from slider1 : "
                        + twoDigits.format(thumbSlider1*100.0/255), 10, 80 );
                   g.drawString( "Percentage of GREEN from slider2 : "
                        + twoDigits.format(thumbSlider2*100.0/255), 10, 100 );
                   g.drawString( "Percentage of BLUE from slider3 : "
                        + twoDigits.format(thumbSlider3*100.0/255), 10, 120 );
    // call to repaint occurs here     
              public void setThumbSlider1(int th){
                   thumbSlider1 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider2(int th){
                   thumbSlider2 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider3(int th){
                   thumbSlider3 = (th >= 0 ? th: 255 );
                   repaint();
              public void setMyTextColor(int r, int g, int b){
                   myTextColor = new Color(r, g, b);
                   repaint();
    //The following method is used by layout managers
              public Dimension getPreferredSize()
              {     return new Dimension( 150, 100 );
    The following is the code of application that tests the component
    //Application used to demonstrating
    // the homemade GUI MyChooserColor component
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowMyColor extends JFrame {
         private JButton changeColor;
         private Color color = Color.lightGray;
         private Container c;
         MyChooserColor colorComponent;
         public ShowMyColor()
         {     super( "Using MyChooserColor" );
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              changeColor = new JButton( "Change Color" );
              changeColor.addActionListener(
                        new ActionListener() {
                             public void actionPerformed( ActionEvent e )
                             {     colorComponent = new MyChooserColor ();
                                  colorComponent.show();
                                  color = MyChooserColor.getMyColor();
                                  if ( color == null )
                                       color = Color.lightGray;
                                  c.setBackground( color );
                                  c.repaint();
              c.add( changeColor );
              setSize( 400, 130 );
              show();
         public static void main( String args[] )
         {     ShowMyColor app = new ShowMyColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {  System.exit( 0 );

    Yes, I want help for the missing code to add in actionPerformed method below. As a result, when you confirm the selected color (clicking the OK button), it will be transferred to a variable color of class ShowMyColor.
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
              );

  • JOptionPane and Applet problem

    Hi folks,
    I have an applet, I want to display a pop up dialog whenever the user
    does something. SO i used JOptionPane:
    int userIn=JOptionPane.showInternalConfirmDialog(this,"Do you wish to generate xml for each ics/ids files pair in this data set?", "information",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
    //repaint();
    The dialog just doesn't show up, I tried repaint(), tried JApplet, nothing works, what am I missing? I'm pretty sure the above code gets called.
    thanks

    A. Are you sure this code is executing?
    B. Are you sure you aren't getting an error, possibly something like
    java.lang.RuntimeException: JOptionPane: parentComponent does not have a valid parent
    at javax.swing.JOptionPane.createInternalFrame(JOptionPane.java:1161)
    at javax.swing.JOptionPane.showInternalOptionDialog(JOptionPane.java:1025)
    at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:967)
    at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:931)

  • JOptionPane and Applets

    How do I get rid of the "Applet window" status bar on the message boxes using JOptionPane, when I use the same in an applet?

    sign your applet.

  • Certificates in lieu of Oracle connection Manager for our Applets -- Help!!

    I support an application named IDEA out of New York. The IDEA application is an INTRANET application for use within our company Firewall.
    Currently, the IDEA application's front end resides on a Windows 2000 Server running IIS 5 and JRun 3.0. The back-end runs on Oracle 8.1.7 database on a UNIX Database Hosting Utility (DHU). Our applets communicate with the back-end database using Oracle Connection Manager that is installed on the Web Host.
    We are trying to migrate to the DWeb environment (Linux cluster). The linux cluster is running Apache Tomcat. We have been told that installing Oracle connection manager is not a viable solution (our company does not support it). Because of this our applets cannot communicate with our database. Below is a brief description of this limitation and also the work-around.
    ====================================================================================================================================================
    Connecting to the Database through the Applet
    The most common task of an applet using the JDBC driver is to connect to and query a database. Because of applet security restrictions, unless particular steps are taken an applet can open TCP/IP sockets only to the host from which it was downloaded (this is the host on which the Web server is running). This means that without these steps, your applet can connect only to a database that is running on the same host as the Web server.
    If your database and Web server are running on the same host, then there is no issue and no special steps are required. You can connect to the database as you would from an application.
    As with connecting from an application, there are two ways in which you can specify the connection information to the driver. You can provide it in the form of host:port:sid or in the form of a TNS keyword-value syntax.
    For example, if the database to which you want to connect resides on host prodHost, at port 1521, and SID ORCL, and you want to connect with user name scott with password tiger, then use either of the two following connect strings:
    using host:port:sid syntax:
    String connString="jdbc:oracle:thin:@prodHost:1521:ORCL";
    conn = DriverManager.getConnection(connString, "scott", "tiger");
    using TNS keyword-value syntax:
    String connString = "jdbc:oracle:thin:@(description=(address_list=
    (address=(protocol=tcp)(port=1521)(host=prodHost)))
    (connect_data=(sid=ORCL)))";
    conn = DriverManager.getConnection(connString, "scott", "tiger");
    If you use the TNS keyword-value pair to specify the connection information to the JDBC Thin driver, then you must declare the protocol as TCP.
    However, a Web server and an Oracle database server both require many resources; you seldom find both servers running on the same machine. Usually, your applet connects to a database on a host other than the one on which the Web server runs. There are two possible ways in which you can work around the security restriction:
    You can connect to the database by using the Oracle8 Connection Manager.
    or:
    You can use a signed applet to connect to the database directly.
    These options are discussed in the next section, "Connecting to a Database on a Different Host Than the Web Server".
    Connecting to a Database on a Different Host Than the Web Server
    If you are connecting to a database on a host other than the one on which the Web server is running, then you must overcome applet security restrictions. You can do this by using either the Oracle8 Connection Manager or signed applets. ====================================================================================================================================================
    It was suggested that we implement signed applets (it is our only alternative at this time). This is where, hopefully, you can help me. We are unfamiliar with using certificates and signing applets. We need to obtain certificates that will allow our applets to connect to our oracle database on the DHU. What kind of certificates do we use? Are their coding examples of how to use these certificates? We have a CA within our company but they cannot tell us what kind of certificates we need. How many certificates do we need? Do we install any certificates on the backend database server? Any information would be greatly appreciated. We are basically trying to get our applet to work outside the sandbox by establishing a connection to the database server.Thanks in advance for your time.

    or:
    You can use a signed applet to connect to the database directly.
    These options are discussed in the next section, "Connecting to a Database on a Different Host Than the Web Server".
    If you want to connect to the database from the applet there is a third option.
    Since this is an intranet application you have control over the desktops using this
    application. In our company the jre ignores signed applets (as it should) because
    it gives control to the user to run potentially harmfull applets from the Internet.
    The way to dish out special privileges to applets is the policy, put a policy file on
    you intranet and have the jre use it by specifying its URL in the java.security.
    Here is some more info about security configuration of the jre:
    http://forum.java.sun.com/thread.jspa?threadID=646161&tstart=45
    reply 3
    We use Oracle jinitiator to run Oracle forms but I am not involved in that project
    and do not know a lot about it. It does perform quite good though.

  • Login Applet Help

    Hello
    I am trying to write a applet that allows me to login to a particular page on my site. I am new to java and have looked some books on the subject. I thought I would be able to manage it myself but I cant for the life of me do it.
    Here is the code I have written:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    <applet code="pass" width=300 height=80>
    </applet>
    public class pass extends Applet implements ActionListener{
         Label lbl1;
         Button btn1;
         TextField txa1;
         public void init(){
              lbl1= new Label("Please enter your password!");
              btn1= new Button("ok");
              txa1= new TextField("",20);
              add(txa1);
              add(btn1);
              add(lbl1);
              btn1.addActionListener(this);
         public void actionPerformed(ActionEvent ae){
              if(txa1 == 'will'){
              lbl1.setText("Password Accepted");
              //**GOTO A CORRECT URL
              else{
              lbl1.setText("Password Incorrect");
              //**GOTO REJECT URL
    How can I get it to check the password entered? Also how the hell do get it to go to a URL???
    Any help would be appreciated.
    Regards
    Jimmy

    (1) Use the getText() method of TextField to get the data typed into the TextField. Returns a String
    (2) Use the equals() method of class String to compare the String returned by the above with the password
    (3) Use the Applet method getAppletContext() to return a reference to the browser.
    (4) Use the AppletContext method showDocument() to redirect the browser to a new page.
    public void actionPerformed(ActionEvent ae)
    if(txa1.getText().equals("will"))
        lbl1.setText("Password Accepted");
        try
            URL url = new URL("http://www.thePageIwantToView.com");
            getAppletContext.showDocument(url);
        catch (MalformedUrlException muex)
           System.out.println(muex.toString());

  • Website in applet help-actionListener

    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MainIndex extends Applet implements MouseListener {
         Image header;
         Image home;
         Image halo;
         Image java;
         public void init() {
              header = getImage(getCodeBase(), "header.png");
              home = getImage(getCodeBase(), "on.png");
              halo = getImage(getCodeBase(), "off.png");
              java = getImage(getCodeBase(), "off.png");
              addMouseListener(halo);
         public void mouseClicked(MouseEvent e) {
         public void paint(Graphics g) {
              g.drawImage(header, 1, 1, this);
              g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
              g.drawRect(0, 101, getSize().width - 1, getSize().height - 1);
              g.drawImage(home, 370, 77, this);
              g.drawImage(halo, 447, 77, this);
              g.drawImage(java, 524, 77, this);
              g.drawString("Ben Sprinkle's Website", 4, 75);
              String body = "I am Ben Sprinkle and this is where I share my interests with other people.";
              g.drawString(body, 4, 115);
              showStatus("Ben Sprinkle's Website");
         public void rePaintHaloTab(Graphics g) {
         public void rePaintJavaTab(Graphics g) {
         public void stop() {
    }Is it possible to add action listeners to my image? I need help.

    Yes, I know, but I acctually did think that you were joking...
    Read the API for JButton, JLabel, JApplet and also read up on http://java.sun.com/docs/books/tutorial/uiswing/components/button.html
    JButton for instance have a constructor that takes an Icon as parameter.

  • Card Applet Help

    Hello,
    I have a quick question, hopefully easy enough....
    In designing a card game applet.....I want the cards to show up on the screen very similar to the Windows Hearts card game.
    I understand how to get the cards at the top and bottom of the screen, but not how to get them to align on the left and right as in what you see when playing the Windows Hearts game.
    Here is the code that I have.....Just a rough draft....
    //import Java classes
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CardApplet extends JApplet implements ActionListener
         //GUI Components
         private JButton cardStatus = new JButton ("Next Players Turn");
         private JButton addTalon = new JButton ("Add Talon");
         private JButton getTrick = new JButton ("Get Trick");
         private BorderLayout layout;
         private JPanel buttonPanel;
         private int player = 0;
         private boolean faceUp = true;
         Deck deck;
         Hand hand1;
         Hand hand2;
         Hand hand3;
         Trick trick;
         private static int trump = 0;
         private static Card talon[];
         private int next = 0;
         public void init()
              layout = new BorderLayout();
              buttonPanel = new JPanel();;
              buttonPanel.setLayout(new FlowLayout());
              //register listeners
              cardStatus.addActionListener(this);
              addTalon.addActionListener(this);
              getTrick.addActionListener(this);
              //add to applet
              Container container = getContentPane();
              container.setLayout(layout);
              container.add(buttonPanel, BorderLayout.NORTH);
              buttonPanel.add(cardStatus);
              buttonPanel.add(addTalon);
              buttonPanel.add(getTrick);
              setVisible(true);
              deck = new Deck();
              deck.shuffleDeck();
              hand1 = new Hand(faceUp,0);
              hand2 = new Hand(false,1);
              hand3 = new Hand(false,2);
              talon = new Card[2];
              createTalon();
              trick = new Trick();
              setSize(550,500);
         }// end of init()
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == cardStatus)
                   cardStatus.setText("Hide Next Hand");
                   if (player == 0) {
                      hand1.turnHandDown();
                      hand2.turnHandDown();
                      hand3.turnHandUp();
                   else if (player == 1) {
                      hand2.turnHandDown();
                      hand3.turnHandDown();
                      hand1.turnHandUp();
                   else if (player == 2) {
                      hand3.turnHandDown();
                      hand1.turnHandDown();
                      hand2.turnHandUp();
                   player = (player + 1) % 3;
             }//if
             if (e.getSource() == addTalon)
                addTalonToHand();
             if (e.getSource() == getTrick)
                getTrick();
              repaint();
         }//end of actionPerformed()
         public void paint(Graphics g)
              super.paint(g);
              Card oneCard;
              g.drawString("Hand1 = " + hand1.getCardsInHand() + " Cards", 10,10);
              g.drawString("Hand2 = " + hand2.getCardsInHand() + " Cards", 10,25);
              g.drawString("Hand3 = " + hand3.getCardsInHand() + " Cards", 10,40);
              int h = 25;
              int v = 50;
              int z = 50;
              for (int k = 0; k < hand1.getCardsInHand() ;k++)
                   h +=25;
                   z +=10;
                   g.drawString(" " + k,10, z);
                      //oneCard = hand.showCards();
                      oneCard = hand1.dealCard(k);
                      oneCard.toImage().paintIcon(this,g,h,v);
              h = 20;
              v = 150;
              for (int k = 0; k < (hand2.getCardsInHand());k++)
                   h +=25;
                   oneCard = hand2.dealCard(k);
                   oneCard.toImage().paintIcon(this,g,h,v);
              h = 20;
              v = 250;
              for (int m = 0; m < (hand3.getCardsInHand());m++)
                   h +=25;
                   oneCard = hand3.dealCard(m);
                   oneCard.toImage().paintIcon(this,g,h,v);
              h=50;
              v = 350;
              for (int n = 0; n < 2; n++)
                   h += 25;
                   oneCard = displayTalon();
                   oneCard.toImage().paintIcon(this,g,h,v);
              h=150;
              v = 350;
              for (int b=0; b < 3; b++)
                   h += 25;
                   oneCard = trick.getCardsInTrick(b);
                   oneCard.toImage().paintIcon(this,g,h,v);
         }//end of paint()
         public void createTalon()
            for (int i = 0; i < 2 ; i++)
                talon[i] = Deck.dealOneCard(false);
        public Card displayTalon()
              Card nextCard = talon[next];
              next = (next + 1) % 2;
         return nextCard;
         public static int getTrump()
              return trump;
         public void addTalonToHand()
              hand1.addCards(talon[0]);
              hand1.addCards(talon[1]);
              talon[0] = hand1.dealCard(0);
              talon[1] = hand1.dealCard(1);
              talon[0].turnCardDown();
              talon[1].turnCardDown();
              hand1.removeCard(0);
              hand1.removeCard(0);
              hand1.sortHand();
              repaint();
         public void getTrick()
              trick.addCardToTrick(hand1.dealCard(5), 0);
              trick.addCardToTrick(hand2.dealCard(5), 1);
              trick.addCardToTrick(hand3.dealCard(5), 2);
              hand1.removeCard(5);
              hand2.removeCard(5);
              hand3.removeCard(5);
    }----Not sure this is how I'm supossed to post the code on here or not.....this is just the applet code....
    Any help would be greatly appreciated!

    ok, actually u don't really need to hassle with rotation if all u're drawing is an empty rectangle, but of course if u have other shapes drawn inside of it, it would be easier to create a function rotate and apply some mathematical transformation formulae on the coordinates of all the shapes.

  • Cost Estimating Applet HELP PLEASE!!!!!!!!!

    i need to develop an applet that calculates the choices that the user makes and the numeric input in the textfield...i have done a basic applet with a panel and 3 comboboxes that i need and the textfield. my problem is how to take the value that the user inputs from the textfield in order to calculate it with the other choices. in the begginng when i had the only the combo boxes was working fine..when i added the textfield something in the code smells..i provide anyone who wants to help with the code..thanx everyone for their time...
    * Course Work Assignment - Applet Programming *
    * Programmed by Christos Lappas *
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import javax.swing.JApplet;
    import javax.swing.JComboBox;
    import javax.swing.JFormattedTextField;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.TitledBorder;
    * This is the main class that implements the "Pricer" applet.
    public class Pricer extends JApplet {
    // The standar colours available
    private String[] colours = {"None","Red","White","Black"};
    // Bonus colour available only for Cars and Boats
    private String bonusColour = "Any other color";
    // The standar items available
    private String[] items = {"None","<50 tiles","100>50 tiles","100=<"};
    // The base prices of these items
    private double[] prices = {0,1.1,1.0,0.8};
    // The sizes available
    private String[] sizes = {"None","small","normal","large"};
    // Initialize the combo-boxes
    private JComboBox item = new JComboBox(items);
    private JComboBox size = new JComboBox(sizes);
    private JComboBox colour = new JComboBox(colours);
    private int cols = 5;
    private int tiles;
    private JTextField notiles = new JTextField(cols);
    // Initialize the price
    private JLabel price = new JLabel("Please select a combination");
    // Initialize the current values
    private int curTeam = 0;
    private int curItem = 0;
    private int curColour = 0;
    private int curSize = 0;
    * The constructor method. Leaves everything to the init method.
    public Pricer()
    // do nothing
    * Initialize the components and add them to the applet.
    public void init()
    // Set applet size and layout
    this.setSize(new Dimension(400,250));
    this.getContentPane().setLayout(new BorderLayout());
    // Initialize the title
    JLabel title = new JLabel("Tiles-U-Like Inc.");
    title.setHorizontalAlignment(SwingConstants.CENTER);
    title.setFont(new java.awt.Font("Comic Sans MS", 2, 16));
    title.setMaximumSize(new Dimension(400,50));
    title.setMinimumSize(new Dimension(400,50));
    title.setPreferredSize(new Dimension(400,50));
    // Initialize the price
    price.setHorizontalAlignment(SwingConstants.CENTER);
    price.setFont(new java.awt.Font("Comic Sans MS", 2, 14));
    price.setMaximumSize(new Dimension(400,50));
    price.setMinimumSize(new Dimension(400,50));
    price.setPreferredSize(new Dimension(400,50));
    // Initialize the optionPanel that will hold the combo-boxes
    JPanel optionPanel = new JPanel();
    TitledBorder border = new TitledBorder("Choose a combination to display it's value");
    border.setTitleJustification(TitledBorder.CENTER);
    optionPanel.setBorder(border);
    optionPanel.setMaximumSize(new Dimension(594, 450));
    optionPanel.setMinimumSize(new Dimension(394, 350));
    optionPanel.setPreferredSize(new Dimension(400, 400));
    // Create the Anonymous Class that will handle the item's actions
    item.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e1) {
    int itemIndex = item.getSelectedIndex();
    if (itemIndex!=curItem) // If the selection was changed
    curItem = itemIndex;
    int team = ((itemIndex==1) || (itemIndex==5))?1:0;
    if ((team != curTeam) && (itemIndex>0)) // If team changed
    curTeam = team;
    setColours(team); // Fix the colours
    // Finally, calculate and display the price
    // for the new combination
    displayPrice();
    // Create the Anonymous Class that will handle the size's actions
    size.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e2) {
    int sizeIndex = size.getSelectedIndex();
    // If the selection was changed, calculate and display
    // the price for the new combination
    if (sizeIndex!=curSize)
    curSize = sizeIndex;
    displayPrice();
    // Create the Anonymous Class that will handle the colour's actions
    colour.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e2) {
    int colourIndex = colour.getSelectedIndex();
    // If the selection was changed, calculate and display
    // the price for the new combination
    if (colourIndex!=curColour)
    curColour = colourIndex;
    displayPrice();
    //Class to handle tiles actions
    notiles.addActionListener(new java.awt.event.ActionListener(){
                   public void actionPerformed(ActionEvent e3) {
    // Add the combo-boxes to the optionPanel
    optionPanel.add(item);
    optionPanel.add(size);
    optionPanel.add(colour);
    optionPanel.add(notiles);
    // Add the components to the applet
    this.getContentPane().add(title, "North");
    this.getContentPane().add(optionPanel, "Center");
    this.getContentPane().add(price, "South");
    // This method determines the available colours
    // depending on the curent team
    private void setColours(int team)
    if (team==1) colour.addItem(bonusColour);
    else colour.removeItem(bonusColour);
    // This method calculates and displays the price
    private void displayPrice()
    // If an invalid combination was selected,
    // display the appropriate message
    if ((curItem==0) || (curSize==0) || (curColour==0)|| (tiles==0))
    price.setFont(new java.awt.Font("Comic Sans MS", 2, 14));
    price.setText("Please select a valid combination");
    else // valid combination
    // Determine the base price, as well as the
    // colour and size bias
    double base = prices[curItem];
    double colAdd=0, sizeAdd=0;
    switch (curColour)
    case 1: colAdd=1.25; break; // Red or Green
    case 2: colAdd=1.0; break; // White
    case 3: colAdd=1.50; break; // Black
    case 4: colAdd=3.50; break; // Any other
    switch (curSize)
    case 1: sizeAdd=-6.75; break; // Small
    case 2: sizeAdd=4.25; break; // Normal
    case 3: sizeAdd=3.50; break; // Large
    // Determine the total price
    double totalPrice = Math.round(base + (base*colAdd) + (base*sizeAdd)+ (base*tiles));
    // Set the font and print the result (rounded)
    price.setFont(new java.awt.Font("Comic Sans MS", 1, 18));
    price.setText(Math.round(totalPrice)+" pounds");
    }

    ok then..i want the applet to take the options from
    the comboboxes and the number from the
    textfield..multiplying them all together and display
    the total price..originally the problem was stated
    as: An applet is required that allows a potential
    customer to obtain an estimate of the cost associated
    with tiling a supplied square area of floor with
    tiles of a specified size and colour.
    ...that is all for now..i can provide even more
    detailed description..thanx..I don't need a more detailed of your homework, I need a more detailed description of your problem.

  • JOptionPane and JList HELP!!!

    Hi there,
    I want to be able to use a JOptionPane and add these elements to my JList component. I know how to add elements to it through the source code but am not able to get a user to inout values into this JList. 've got my JOptionPane running by using the following code:
    public void actionPerformed(ActionEvent ae) {
           if(ae.getActionCommand().equals("New Player")){
                s1 = JOptionPane.showInputDialog("Enter player: ");
                list.append(s1);
           repaint();
      }I want the values taken from this Prompt and be shown in my JList. I tried doing:
    list.addElement(s1);
    list.append(s1);
    I tried looking at the Java API website but didn't find it helpful at all of what I'm trying to do.

    I keep getting an error on the line where it says:
    list.add(s1);And even when I try:
    list.addElement(s1);Still same error. Is it a different way of doing it?
    Thanks for any response

  • JOptionPane glitches - need help!

    Hi,
    I am building a java application that is full-screen. It is not set to always be on top. What happens is that the user is supposed to drag one of the green shapes onto the board. If they drag the shape and let go slowly, the JOptionPane shows up correctly. If they drag the shape and let go fast while they are dragging it, it causes problems with the display of the JOptionPane dialog. Below are some screen-shots of the problem:
    [http://www.thedigitallion.com/temp/ex1.jpg]
    [http://www.thedigitallion.com/temp/ex2.jpg]
    The JOptionPane shows up on mouse button release because that is how I test for when they stop dragging it. It seems like it still animates the shape after the joptionpane comes up and that is why it doesn't refresh the screen afterward. Here is a code snippet:
    [http://www.thedigitallion.com/temp/code.txt]
    Any help would be greatly appreciated!!!
    Ryan

    Point A
    JOptionPane.showInputDialog(....);
    Point BA modal dialog serves two purposes. One is that it dosen't allow you to get to Point B until the dialog is closed. You are using this property in your code to get input and then handle the input only after the dialog is closed. The second purpose of a modal dialog is to cut off functionality to the parent frame. If I try to click on the parent frame then Windows will make a "beep" sound and the dialog's window decorations will flash. I have to handle the dialog before I can start working with the frame again.
    This would seemingly pose a problem though if the modal dialog is shown on the EDT (short for Event Dispatch Thread). The EDT is the thread that handle's all your GUI events (painting, key input, mouse input, focus changes, component resizes ... bascially anything and everything that extends java.awt.AWTEvent ). It's a simple matter of fact that if you hold up the EDT, then the GUI becomes unresponsive - to everything - until the EDT is ... no longer held up.
    As I mentioned, because one of the purpose of a modal dialog is to keep the thread that made the dialog visible from continuing on (until the dialog is closed) then it would be in theory very bad to call JOptionPane.showXXX on the EDT as this would deadlock the program. Fortunately though, the java developers were kind enough to forsee this problem and implemented it so that a new temporary thread is created to handle the GUI stuff if a modal dialog is shown on the EDT.
    The bad news is that we can't really mimick this functionality on our own.
    Would I have to manually go through all of my components on the screen disabling them whenever I want to show a dialog if I did it this way or can I just block input to anything below the layer that the dialog in on?It could be as easy as making a component visible (like the glass pane) or as easy as calling a single method (when your content pane is wrapped within a JXLayer). You may not even need this functionality.
    I'm simply stating that the hard part is to design your code so that Point B no longer directly comes after showing the input prompt.
    Point A
    JOptionPane.showInputDialog(....);
    Point BThis can only be achieved by placing the input handling stuff (Point B) in a seperate method. One which is called by the component receiving input in a layer above the content pane.
    The JXLayer and the glass pane thing were simply to cut off functionality to the parent frame (the second purpose of a modal dialog).

  • Simple java applet help needed

    hi, im having trouble with an applet im developing for a project.
    i have developed an applet with asks the user for simple information( name,address and phone) through textfields, i wish for the applet to store this information in an array when an add button below the textfeilds is pressed.
    client array[];
    array=new client[];//needs to be an infinate array!
    I have created the client class with all the set and get methods plus constructors needed but i dont know how to take the text typed into the textfields by the user and store them in the array.
    i also need to save this info to a file and be able to load it back into the applet.
    Could some please help! Thank you for your time.

    Better maybe redefine the idea using an data structure :
    public class client{
    private char name[];
    private char address[];
    private int phone;
    public class vector_clients{
    private client vect[];
    // methods for vect[]
    What is your opinion about ???

  • EEM - Applet Help Appreciated

    I am using the following applet to modify entries in two ACLs from a mobile device. Please see applet below with output from a test run:
    3    applet    user    none                Off   Sun Mar 28 22:42:59 2010  rite1
    policyname {rite1} sync {yes}
    maxrun 60.000
    action 1.0 puts "Set HostA:"
    action 1.1 gets hosta
    action 1.2 puts "Set HostB:"
    action 1.3 gets hostb
    action 1.4 cli command "enable"
    action 1.5 cli command "config t"
    action 1.6 cli command "ip access-list extended rite1_incoming"
    action 1.7 cli command "no 10"
    action 1.8 cli command "no 20"
    action 1.9 cli command "10 permit ip host $hosta host $hostb"
    action 2.0 cli command "20 permit ip host $hostb host $hosta"
    action 2.1 cli command "ip access-list extended rite1_outgoing"
    action 2.2 cli command "no 10"
    action 2.3 cli command "no 20"
    action 2.4 cli command "10 permit ip host $hosta host $hostb"
    action 2.5 cli command "20 permit ip host $hostb host $hosta"
    action 2.6 cli command "end"
    action 2.7 cli command "show ip access-list | s rite1"
    action 2.8 puts "$_cli_result"
    action 2.9 puts ""
    action 3.1 puts "-------------------------------------"
    action 3.2 puts ""
    action 3.3 puts "Use following packet_capture commands:"
    action 3.4 puts " ritesh - show packet_capture"
    action 3.5 puts " ritecl - clear packet_capture"
    action 3.6 puts " ritestr - start packet_capture"
    action 3.7 puts " ritestp - stop packet_capture"
    action 3.8 puts ""
    action 3.9 puts "-------------------------------------"
    alias exec rite1 event manager run rite1
    Router#rite1
    Set HostA:
    172.20.1.1
    Set HostB:
    20.1.1.1
    Extended IP access list rite1_incoming
        10 permit ip host 172.20.1.1 host 20.1.1.1
        20 permit ip host 20.1.1.1 host 172.20.1.1
    Extended IP access list rite1_outgoing
        10 permit ip host 172.20.1.1 host 20.1.1.1
        20 permit ip host 20.1.1.1 host 172.20.1.1
    Use following packet_capture commands:
    ritesh - show packet_capture
    ritecl - clear packet_capture
    ritestr - start packet_capture
    ritestp - stop packet_capture
    I use this for packet capturing with RITE on remote sites that do not warrant consistent samples. We get alerted when a specific top-talker is showing unusual high volumes of traffic and our techs are able to run the following script on the fly from mobile devices. The high-volume converstaion gets captured and we have another script that exports those onboard captures to centralized servers. The whole operation runs pretty great. The problem is that for some reason it eats a TON of process usage.
    117852: Mar 28 23:03:54.197 DST: %SYS-1-CPURISINGTHRESHOLD: Threshold: Total CPU Utilization(Total/Intr): 72%/1%, Top 3 processes(Pid/Util):  199/71%, 49/0%, 81/0%
    117865: Mar 28 23:04:09.128 DST: %SYS-1-CPUFALLINGTHRESHOLD: Threshold: Total CPU Utilization(Total/Intr) 1%/0%.
    I"m assuming that process # 199 is dynamically created for this specific applet when it runs, as it does not seem to run on the routers at other times:
    Router#show process cpu
    ....output omitted....
    198           0           3          0  0.00%  0.00%  0.00%   0 EEM ED RPC
    201       14371       99291        144  0.00%  0.00%  0.00%   0 DHCPD Receive
    ....output omitted....
    For some reason, while the router is interacting with the user, waiting for input from the "action x.x get" commands, the processer is through the roof. Any ideas on how I could run this similar operation without taking up so much process overhead? I want to say that I could probably limit the resource usage of those specific processes maybe with ERM, but I'm currently not very familiar with ERM. Thanks for everyone's help.

    Joe,
    Thanks so much for converting our applet into a tcl script. It works great everywhere that we have deployed it. We did run into one issue deploying on a 3745 Router with 12.4(15)T9. When the policy was triggered, we received the following error:
    error reading "stdin": Unknown error 134217728
        while executing
    "gets stdin"
        invoked from within
    "$slave eval $Contents"
        (procedure "eval_script" line 7)
        invoked from within
    "eval_script slave $scriptname"
        invoked from within
    "if {$security_level == 1} {       #untrusted script
         interp create -safe slave
         interp share {} stdin slave
         interp share {} stdout slave
        (file "tmpsys:/lib/tcl/base.tcl" line 50)
    Tcl policy execute failed: error reading "stdin": Unknown error 134217728
    Tcl policy execute failed: error reading "stdin": Unknown error 134217728
    I also pulled the specific script that it's referencing the error from:
    # base.tcl - Safe base script forinvoking safe-tcl on FM policies.
    # August 2002, Jason Pfeifer
    # Copyright (c) 2002, 2004-2006 bycisco Systems, Inc.
    # All rights reserved.
    # Current security levels:
    # 0 - trusted script, safe mode not enabled
    # 1 - untrusted script, safe modeenabled
    ####################   Procedures  ##################
    proc TraceVariable { fromInterp fromVartoInterp toVar } {
        set value [ interp eval $fromInterpset ::$fromVar]
        interp eval $toInterp [list set::$toVar $value]
    proc eval_script { slave scriptname } {
        # Open script and evaluate it in slave
        set F [open $scriptname]
        set Contents [read $F]
        close $F
        $slave eval $Contents
    ####################  End of Procedures  ##################
    # main
    # Process argv input:
    set scriptname [lindex $argv 0]
    set security_level [lindex $argv 1]
    if {$security_level != 0 && $security_level != 1} {
        set security_level 1
    #Set Security level specific parameters
    set errorInfo ""
    set FM_TCLLIBDIR [info library]
    if {$security_level == 1} {      #untrusted script
         interp create -safe slave
         interp share {} stdin slave
         interp share {} stdout slave
         interp share {} stderr slave
         lappend global_vars auto_path
         lappend global_vars auto_oldpath
         lappend global_vars tcl_library
         foreach entry [info vars] {
             if [array exists $entry] {
                 continue
             if {[lsearch -exact$global_vars $entry] >= 0} {
                 continue;
             TraceVariable {} $entry slave$entry
         # uncomment to debug safe.tcl
         #::safe::setLogCmd puts stderr
         ::safe::interpInit slave
         # Hidden commands that are exposed to slave to ease restrictions.
         interp alias slave exit {} exit
         interp expose slave fconfigure
         interp expose slave socket
         eval_script slave $scriptname
         close stdin
         close stdout
         close stderr
         ::safe::interpDelete slave
    } else {                          #trusted script
         interp create slave
         interp share {} stdin slave
         interp share {} stdout slave
         interp share {} stderr slave
         foreach entry [info vars] {
             if [array exists $entry] {
                 continue
             TraceVariable {} $entry slave$entry
         if {[catch {::interp eval slave\
                 {source [file join$FM_TCLLIBDIR init.tcl]}} msg]} {
             error "can't sourceinit.tcl into slave ($msg)"
         eval_script slave $scriptname
         interp delete slave
    What ended up happening is the script stayed stuck in pending(no 'scheduler' commands in this early version of eem) and we eventually had to reboot the router(we waited until a regularly scheduled maintenance window, so it worked out fine). Since receiving this error, we haven't tried to run this particular script on this particular router. All other devices that we have deployed this on, including other 3745's running 12.4(15)T, have worked great. If anyone has some idea as to exactly what happened and what adjustments we need to perform to correct the problem, we would greatly appreciate it.
    Thanks again for everyone's help.

  • Java applet help for mountain lion update on macbook pro

    Hey, I upgraded to the new mountain lion update yesterday and since then when opening java applets, it won't allow me to do anything with them such as entering usernames and passwords. It was working fine yesterday before I did the update but now I can't seem to get it to work. I've reinstalled Java and it says it's all installed correctly. I was wondering if anyone else is having/had the same problem and knows what to do?
    Thanks in advance

    Hi Leonie! I was running into the same problem on my Macbook Air with ML but I just found a soultion that worked for me.
    I downloaded and installed Java 7 from oracle's website.  And then in the java prefences referenced before, changed the Java 7 build to be my default. 
    All my applets work great now for me.
    Hope this helps!

Maybe you are looking for

  • Albums created on mac not showing on iphone or ipad

    I created an album on my mac photo app.  How do I get this album to appear on my iphone and ipad? Upload to my photo stream and icloud photo library are active on all of my devices.

  • Oracle XE not starting up

    Hi Community, I have installed Oracle XE on top of RH FC4 running on my VM. When I start XE I get the following error: [root@vm ~]# /etc/init.d/oracle-xe start Starting Oracle Net Listener. Starting Oracle Database 10g Express Edition Instance. Faile

  • Support for o/r in Oracle 8i tools

    Support for object types in the Oracle 8i administration tools seems to be limited. For example, I can't select an object type for a table column in DBAStudio. However, I can define types and tables using types through SQLPlus. What fails is to refer

  • Hi guru's I am new to the xi,please  explain me documentation in xi part.

    1) I have done file to idoc scenario. in this what is the documentation part in xi .     where we have to wtite in xi.?

  • How do you restore email?

    I had to get a new hard disk. I had backed up my computer with time machine on a separate hard drive. I have restored the apps but how do I restore my email messages?