简体   繁体   中英

Java HTML - Change Color of Applet by Click

Hey guys I have a problem. Im currently studying IT and we started to program with Java. So our task was to program a HTLM site with a Java Applet that switches Back- and Foregroundcolor of a Textboxthing on click. So here is the code and im absolutly not sure what is wrong:

Java-file:

import java.applet.*; //Applet
import java.awt.*; // Graphics, Color
public class HalloWeltPlus extends Applet
{
  Color vordergrundfarbe = Color.white; 
  Color hintergrundfarbe = Color.black;
public void paint( Graphics g)
{
  setForeground ( vordergrundfarbe);
  setBackground ( hintergrundfarbe); 
  g.drawString("Hello World...",50,50); // Bildschirmausschrift erzeugen
}
public void setColor()
{
  setForeground (hintergrundfarbe);
  setBackground (vordergrundfarbe);
  repaint( 100L);
}
}

HTML-File:

<html>
<!-- Diese Seite bindet das HalloWelt - Applet ein. -->
 <head>
  <title>
    HalloWeltPlus
   </title>
 </head>
  <body>
   <!-- Applet -->
  <applet
    code=HalloWeltPlus.class name=A width=170 height=100>
   </applet>
   <a onClick="document.A.setColor()"></a>
 <p>
  </body>
 </html>

So when I click the Box nothing happens - pls help me :)

You cannot communicate with DOM elements by name attribute alone. Add id="A" to your applet, and add some words inside the A tag to make everything work.

document.A <== this refers to one element with id="A"

Update: There's a bug in your Java. repaint() just schedules a call to your paint function, but tells the system to get ready the graphics "g" object on your behalf.

You set the background and foreground colors in setColor(), but then you call repaint(), the system gets a graphics object and calls YOUR paint method, then you reset the foreground and background colors.

You should add an init method to set the foreground only once.

//only called on time by applet system
public void init() {
  setForeground ( vordergrundfarbe);
  setBackground ( hintergrundfarbe); 
}
//called everytime you call repaint()
public void paint( Graphics g)
{
  g.drawString("Hello World...",50,50); // Bildschirmausschrift erzeugen
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM