【发布时间】:2018-10-20 22:07:01
【问题描述】:
我为我的 java 小程序编写了一个绘制方法,这允许我的 drawString 将颜色更改为用户在三个文本字段(R、G、B)中输入的任何内容。我的默认字体颜色是黑色,但是我试图将其更改为绿色但不能,因为要更改字体颜色,我必须编写 g.setColor(mixColor)。那么有谁知道当我运行我的小程序而不是黑色时如何使字体颜色以绿色开始。
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class text2 extends Applet implements ActionListener
{
Font textFont;
TextField T1;
TextField T2;
TextField T3;
int redColor, greenColor, blueColor;
String as, ag, ab;
Button bttn;
Button bttn2;
public void init() {
// This routine is called by the system to initialize
// the applet. It sets up the font and initial colors
// the applet. It adds a button to the applet for
// changing the message color.
setBackground(Color.lightGray);
// The applet is filled with the background color before
// the paint method is called. The button and the message
// in this applet will appear on a light gray background.
redColor=0;
greenColor=0;
blueColor=0;
textFont = new Font("Serif",Font.BOLD,24);
T1 = new TextField("",12);
T2 = new TextField("",12);
T3 = new TextField("",12);
add(T1);
add(T2);
add(T3);
bttn = new Button("Change Colour");
bttn2 = new Button("Reset");
// Create a new button. "ChangeColour" is the text
// displayed on the button.
bttn.addActionListener(this);
bttn2.addActionListener(this);
// Set up bttn to send an "action event" to this applet
// when the user clicks the button
add(bttn);
add(bttn2);
// Add the button to the applet, so that it
// will appear on the screen.
}
public void paint(Graphics g) {
// This routine is called by the system whenever the content
// of the applet needs to be drawn or redrawn. It displays
// my name and reg number in the proper colour and font.
this.bttn2.setLocation(600, 600);
Color mixColor = new Color(redColor, greenColor,blueColor);
g.setColor(mixColor);
g.setFont(textFont); // Set the font.
g.drawString("Welcome to my applet by: Joshua", 330, 300);
}
public void actionPerformed(ActionEvent e) {
// This routine is called by the system when the user clicks
// on the button. The response is to change the colorNum
// which determines the color of the message, and to call
// repaint() to see that the applet is redrawn with the
// new color.
if (e.getSource() == bttn2) {
T1.setText(null);
T2.setText(null);
T3.setText(null);
}
if (e.getSource() == bttn)
{
as=T1.getText();
ag=T2.getText();
ab=T3.getText();
as=as.trim();
ag=ag.trim();
ab=ab.trim();
redColor= Integer.parseInt(as);
greenColor= Integer.parseInt(ag);
blueColor= Integer.parseInt(ab);
repaint(); // Tell system that this applet needs to be redrawn
}
}
}
【问题讨论】:
-
编辑您的问题以显示 redColor、greenColor 和 blueColor 是如何声明和初始化的。
-
我现在将添加我的整个代码
-
您在
init方法中将 redColor、greenColor 和 blueColor 初始化为零。这意味着您的绘画方法有效地执行黑色的new Color(0, 0, 0)。您可能希望在系统上的任何简单绘图程序中使用颜色选择器,以便查看各种红色、绿色和蓝色的结果。 -
对不起,我是 java 的初学者,所以基本上如果我希望在运行我的小程序时字体颜色最初显示为绿色,我是否要更改 rgb 值
-
ohhhh我已经搞定了,我刚刚把初始的绿色值改成了255,非常感谢