简体   繁体   English

Java HTML-通过单击更改小程序的颜色

[英]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. 我目前正在研究IT,我们开始使用Java进行编程。 So our task was to program a HTLM site with a Java Applet that switches Back- and Foregroundcolor of a Textboxthing on click. 因此,我们的任务是使用Java Applet对HTLM网站进行编程,该Java Applet在单击时切换Textboxthing的Back-ground和Foregroundcolor。 So here is the code and im absolutly not sure what is wrong: 所以这是代码,我绝对不确定出什么问题了:

Java-file: Java文件:

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文件:

<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. 您不能仅通过name属性与DOM元素进行通信。 Add id="A" to your applet, and add some words inside the A tag to make everything work. 在您的applet中添加id =“ A”,并在A标签内添加一些单词,以使所有内容正常运行。

document.A <== this refers to one element with id="A" document.A <==这是指id =“ A”的一个元素

Update: There's a bug in your Java. 更新:Java中存在一个错误。 repaint() just schedules a call to your paint function, but tells the system to get ready the graphics "g" object on your behalf. repaint()只是调度对您的paint函数的调用,但是告诉系统为您准备图形“ g”对象。

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. 您可以在setColor()中设置背景色和前景色,但随后调用repaint(),系统将获取图形对象并调用您的paint方法,然后重置前景色和背景色。

You should add an init method to set the foreground only once. 您应该添加一个init方法来仅设置一次前台。

//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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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