Reputation: 11
I want to use drawString() once a button is pushed to draw the answer on my applet but I can't figure it out. I have try many ways to do and my program compiles but won't drawString() when the button is pushed please help.
import java.applet.Applet;
import java.awt.event.*;
import java.awt.Graphics.*;
import java.awt.*;
public class FortuneTellerApplet extends Applet {
Image image;
Button getFortune = new Button("Get Your Fortune");
Button tryAgain = new Button("Clear And Try Again");
TextField input = new TextField("Enter Question Here", 30);
public void init() {
image = getImage(getDocumentBase(), "webimages/crystalball.jpg");
getFortune.setBackground(Color.black);
getFortune.setForeground(Color.orange);
tryAgain.setBackground(Color.black);
tryAgain.setForeground(Color.orange);
input.setBackground(Color.black);
input.setForeground(Color.orange);
setLayout(new FlowLayout());
setBackground(Color.green);
add(getFortune);
add(tryAgain);
add(input);
MyHandler handler = new MyHandler();
getFortune.addActionListener(handler);
tryAgain.addActionListener(handler);
}
public void paint(Graphics g) {
g.drawImage(image, 12, 34, this);
}
public class MyHandler extends Button implements ActionListener {
public void actionPerformed(ActionEvent ev) {
if (ev.getSource()==getFortune) {
// >>>>>>>>> I want be able to use drawString() here <<<<<<<
} else if (ev.getSource()==tryAgain) {
input.setText("");
input.requestFocus();
}
}
}
}
Upvotes: 1
Views: 2659
Reputation: 324207
Do you need to do custom painting?
Just use a Label
that initially defaults to an empty string. Then when the you want to display the answer you invoke the setText() method on the label to display the text.
Why are you using AWT? I would learn Swing. I don't use AWT but I would guess that if you are going to do custom painting, then you should have a super.paint()
at the start of your painting method. I know this is important for Swing.
Upvotes: 3
Reputation: 3961
Use a boolean value in paint method, like this:
// Add this to the top
boolean stringVisible = false;
// Change paint method accordingly
public void paint(Graphics g) {
g.drawImage(image, 12, 34, this);
if( stringVisible )
{
// draw string
}
}
Set the boolean value to true when button is pressed, it must be false initially.
Upvotes: 2