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.

Similar Messages

  • Cant figure out whats wrong with my applet, help pls??

    this applet checks a string against one in a database then if passwords match, a new url is opened. the applet loads in webpage with no problems. it just doesnt seem to work. have granted full access to code base in policy file.
    heres the code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.applet.*;
    import java.sql.*;
    import java.net.*;
    public class LoginApplet extends Applet implements ActionListener
        Panel top;
        Panel bottom;
        TextField nameField;
        TextField passField;
        Label userNameLabel;
        Label passwordLabel;
        Button loginButton;
        public void init()
            setSize(230,200);
            setBackground(Color.white);
            // Create panels, labels, and text fields
            top                = new Panel(new FlowLayout(FlowLayout.LEFT));
            bottom                = new Panel(new FlowLayout(FlowLayout.LEFT));
            nameField           = new TextField(15);
            passField           = new TextField(15);
            userNameLabel      = new Label("User Name:", Label.LEFT);
            passwordLabel      = new Label("Password:   ", Label.LEFT);
            loginButton          = new Button("Login:");
            loginButton.addActionListener(this);
            // Mask the input so that people looking over your shoulder
            // won't be able to see the password
            passField.setEchoChar('*');
            // Add items to their panels
            top.add(userNameLabel);
            top.add(nameField);
            top.add(passwordLabel);
            top.add(passField);
            bottom.add(loginButton);
            // Set the applet layout
            setLayout(new GridLayout(3,3));
            // Add the panels to the applet (skip this
            // part and you won't see the panels on screen)
            add(top);
            add(bottom);
        public void actionPerformed(ActionEvent e)
                   String name      = nameField.getText();
                   String pass      = passField.getText();
                   try
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        // set this to a MS Access DB
                        String filename = "e:/iain/College/Y4/SWP/Program/website/database/loginDetails.mdb";
                        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
                        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
                        // now we can get the connection from the DriverManager
                        Connection con = DriverManager.getConnection( database ,"","");
                        Statement s = con.createStatement();
                        s.execute(" SELECT [password] FROM logindetails WHERE [username] = '" + name + "' "); // select the data from the table
                        ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
                        if (rs != null) // if rs == null, then there is no ResultSet to view
                             while ( rs.next() ) // this will step through our data row-by-row
                                  String passtmp = "";
                                  passtmp = passtmp + rs.getString(1);
                                  if(passtmp.equals(pass))
                                       String url = "E:/iain/College/Y4/SWP/Program/website";
                                       Runtime rt = Runtime.getRuntime();
                                       String[] callAndArgs = {"\"C:\\Program Files\\Internet Explorer\\iexplore.exe\"", url };
                                       try
                                            Process child = rt.exec(callAndArgs);
                                            nameField.setText("");
                                            passField.setText("");
                                       catch (Exception eee)
                                            eee.printStackTrace(System.err);
                                  else
                                       System.out.println("Invalid Password " +name);
                                  s.close(); // close the Statement to let the database know we're done with it
                                 con.close(); // close the Connection to let the database know we're done with it
                   catch (Exception ee)
                        System.out.println("Error: " + ee);
    }

    this is the initial error, when applet is run:
    java.security.policy: error adding Entry:
    java.net.MalformedURLException: unknown
    unknown protocol: eI don't know where that's from that code, but e isn't a protocol. If it's a file, you should append "file:///" to the full path.
    then when trying to read from db:
    Error: java.security.AccessControlException: access
    denied (java.lang.RuntimePer
    mission accessClassInPackage.sun.jdbc.odbc)
    didnt think of running it through applet viewer.
    the whole thing will be running on the same server
    using IIS over a LANYou don't connect to a local file system thru an applet without a signed applet. Period.

  • 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());

  • Desperately need applet help....im a beginner

    I'm currently trying to write an applet that takes in text from a textfield and then displays it in the applet window when the return key is pressed, updating the text whenever new text is entered. I'm trying to get two letters of the alphabet to be a certain colour when the text appears. I've tried to get the string from the input into a character array and seem to have done this, but i can't get them to display in the applet window let alone specify colours for certain characters. If anyone could help it would be very much appreciated. Here is the code i have so far:
    import java.util.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class ali extends Applet implements ActionListener
    String name;
    TextField input;
    char myArray[];
    public void init()
    input = new TextField(20);
    add(input);
    input.addActionListener(this);
    public void actionPerformed ( ActionEvent e )
    name = e.getActionCommand();
    repaint();
    // i think this is right for getting the characters into the array:
    myArray = new char[name.length()];
    for (int i=0; i< myArray.length; i++)
    myArray[i] = name.charAt(i);
    public void paint(Graphics g )
    //cant get them back out...
    }

    Here is something that will get you started -- as far as outputting in colors, I'll leave it up to you:
    ali.html
    ======
    <applet code="ali" codebase="." width=400 height=400></applet>
    ali.java
    ======
    import java.util.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class ali extends Applet implements ActionListener {
       String name;
       String out="";
       TextField input;
       char myArray[];
       public void init() {
          input = new TextField(20);
          add(input);
          input.addActionListener(this);
          setVisible(true);
       public void actionPerformed (ActionEvent e ) {
          repaint();
       public void paint(Graphics g ) {
          g.drawString(input.getText(),40,40);
    }V.V.

  • Multiple applets help

    I am very new to java and I have written several stand alone applets but when I try to call the different applets from a main they fail to load or end up in a new instance loop. Sorry if the verbage is incorrect. Here is an example of what I am trying to accomplish
    public class MainLayout extends Applet implements ActionListener,MouseListener {
    menuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    SwingUtilities.invokeLater(new Runnable() {
    public void run()
    new anotherApplet(); //not working
    createAndShowFrame(); // works and creates an empty frame.
    public static void createAndShowFrame() {
    JFrame myFrame = new JFrame("My JFrame");
    myFrame.setSize(250, 250);
    myFrame.setLocation(300,200);
    myFrame.getContentPane().add(BorderLayout.CENTER, new JTextArea(10, 40));
    myFrame.show();
    Like I said "MainLayout" runs no problem but I am unable to load "anotherApplet". However if I run anotherApplet seperately it executes correctly. Any help would be greatly appreciated.

    Applet containers usually invoke a number of lifecycle methods on their applets, such as init, start, stop, destroy, etc. and provide an AppletContext. If your applets rely on any of these methods, then your attempt to execute them from a main should invoke those methods and potentially provide a context.

  • Java applet help

    iam trying to put the checkboxes in different line
    so all the checkbox is alligned
    what the syntax to do that??
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class Computers extends Applet implements ActionListener
         //declare varibles
         double totalCost;
         //contruct Label and Checkboxes
         Label companyName = new Label ("REASONABLE COMPUTER CORPORATION");
         Label system = new Label ("Basic Computer System cost: $575");
         Label choice = new Label ("Select the peripheral devices you want add");
         CheckboxGroup selectGroup = new CheckboxGroup();
              Checkbox printers = new Checkbox("Printer $150",false,selectGroup);
              Checkbox monitors = new Checkbox("Monitor $300",false,selectGroup);
              Checkbox modems = new Checkbox("Modems $100",false,selectGroup);
              Checkbox speaker = new Checkbox("Speaker $20",false,selectGroup);
              Checkbox microphone = new Checkbox("MircoPhone $15",false,selectGroup);
              Checkbox external = new Checkbox ("250G external hard driver $200",false,selectGroup);
         Button calc = new Button("Calculate");
         Label output = new Label("Click Calculate to see your final price");
         //init method for adding the stuff
         public void init()
              setBackground(Color.green);
              setForeground(Color.black);
              add(companyName);
              add(system);
              add(choice);
              add(printers);
              add(monitors);
              add(modems);
              add(speaker);
              add(microphone);
              add(external);
              add(calc);
              calc.addActionListener(this);
              add(output);
         public void actionPerformed(ActionEvent e)
              totalCost = 575 + getCode();
              output(totalCost);
         public double getCode()
              double dollars = 0;
              if (printers.getState()) dollars += 150;
              else if (monitors.getState()) dollars += 300;
              else if (modems.getState()) dollars += 100;
              else if (speaker.getState()) dollars += 20;
              else if (microphone.getState()) dollars += 15;
              else if (external.getState()) dollars += 200;
                return dollars;
         public void output(double totalCost)
              output.setText("Your Final cost is: " + totalCost + ".");
    }

    hiddendragon wrote:
    iam trying to put the checkboxes in different line
    so all the checkbox is alligned
    what the syntax to do that??There's no "syntax" involved. Instead you have to read up on and study the various layout managers. You could for instance use a BoxLayout to stack information on top of each other, and put your checkboxes in their own panel that uses flowlayout. There's many many ways to arrange this, and the best is the one that works for you. Start here .

  • I'm using Windows 8.1 and the browser won't load any web page. I downloaded the latest one from the website. Any help would be great. All other browsers work.

    I'm using Windows 8.1 and the browser won't load any web page. I downloaded the latest one from the website. Any help would be great. All other browsers work.

    Hi curtismoxam,
    Please try these troubleshooting steps: [[Fix problems connecting to websites after updating Firefox]]

  • Images won't open in my gmail or websites can anybody help me? this happend when i updated to the newest version of Firefox

    Question
    Images won't open in my gmail or websites can anybody help me? This happen when I updated to the newest version of Firefox

    If images are missing then check that you aren't blocking images from some domains.
    See:
    * http://kb.mozillazine.org/Images_or_animations_do_not_load
    * Check the permissions for the domain in the current tab in Tools > Page Info > Permissions
    * Check that images are enabled: Tools > Options > Content: [X] Load images automatically
    * Check the exceptions in Tools > Options > Content: Load Images > Exceptions
    * Check the "Tools > Page Info > Media" tab for blocked images (scroll through all the images)
    There are also extensions (Tools > Add-ons > Extensions) that can block images.
    * [[Troubleshooting extensions and themes]]

  • I have several folders setup in my Safari.  However, when I try to add a website to them, it never appears.  When I add a folder and add a website to it, the website appears.  Help?

    I have several folders setup in my Safari.  However, when I try to add a website to them, it never appears.  When I add a folder and add a website to it, the website appears.  Help?

    I thank you for the response.  Apple does some assinine things sometimes and this is one of them.  Ask the planet the difference between a movie and a home video and with the exception of Apple, you'd get 100% consenus on the what difference is.  A home video is something that I shoot, like my kids birthday party.  A movie is something I urchased either via download or a DVD that I ripped.  Unbelievable!   The fact that Apple has chosen not to distinguish based upon which folder I tell it is Movies and which folder is Home Videos is really hard to fathom - sounds like something Windows would do. I find it funny that in my iTunes movies sub-section of the movies section, the movie icons have a cloud icon in upper right corner to distinguish it as bought from Apple iTunes versus no cloud icon for movies that I have ripped - so the distintion was already made and clearly visible.  Now - everything just defaults to "home videos" if I try to import a new ripped DVD - why even bother to have this distinction on the iTunes bar?  WOW!
    As for your direction, I do not understand what you are telling me - what Media Kind and what Options tab are you referring to?  I see no Options tab in iTunes.  Right licking on the movie icon does not yield media kind or options as well.  Gping to the source file does not yield these options either.
    Thanks again for your help.
    Clay

  • White screen on my ipod touch not resolve yet althought i follow the instruction on apple website!!help!!

    white screen on my ipod touch not resolve yet althought i follow the instruction on apple website!!help!!am i really need to pay for repair it,but i 'm still got warranty

    Make an appointment at the Genius Bar of an Apple store.  If The can't fix it and the iPod is within the warranty period, Apple should give a a refurbished iPod.

  • 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 );     
              );

  • 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.

  • 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!

  • Applet help required

    I have created an applet that displays a date but i cannot get this applet to work in my website, What am I doing wrong?
    this the code
    package DisplayTheDate;
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    import java.applet.Applet;
    public class getthis extends Applet {
    public void init() {
    String theDate;
    Date getdate = new Date();
    theDate = getdate+".";
    setLayout(new BorderLayout());
    Panel t = new Panel();
    t.setLayout(new GridLayout(1,1));
    t.add(new Label(theDate));
    add("Center", t);
    public static void main(String args[]){
    Frame f = new Frame("display Date");
    getthis ce = new getthis();
    ce.init();
    f.add("Center", ce);
    f.pack();
    f.show();
    in the website
    <html>
    <title>
    This is the date class
    </title>
    <body>
    <center>
    <applet code="C:\JBuilder3\myprojects\untitled10\getthis.class">
    </applet></center>
    </body>
    </html>
    please help!

    I dont understand what you are saying, I have followed
    the example to a T but with no luck!If you had followed it to a T it would be working already ;) You must have made a silly mistake somewhere. Try again.
    By the way, not only is the code attribute wrong in your html, you are also missing the required width and height attributes that specify the size of the applet on screen.

Maybe you are looking for