Answer» I am creating an Applet using java. The applet is supposed to get user input to make a rectangle. The user will enter in the height and width, and then click the draw BUTTON to have the rectangle drawn. My code compiles and runs fine, but I am just having some problems with some of the minor details. I am supposed to restrict the maximum and MINIMUM SIZE of the applet such that the user cannot enter a negative number or zero for the min, and limit the max so that the rectangle will be properly displayed in the applet. I'm thinking that this part would be IF statements, but I'm just unsure of how to goabouts in writing the IF statement. Also, I would like to have an image set as my background, but I just can't seem to get it to work right. Here is my code
Code: [SELECT]
import java.applet.*; import java.awt.*; import java.awt.event.*; import java.text.*; import java.awt.Graphics;
public class rectangle extends Applet implements ActionListener { //declare VARIABLES Image background; //declare an Image object int height, width;
//construct components Label heightLabel = new Label("Enter the height of your rectangle: "); TextField heightField = new TextField(10); Label widthLabel = new Label ("Enter the width of your recntagle: "); TextField widthField = new TextField(10); Button drawButton = new Button("Draw Rectangle"); Label outputLabel = new Label("Click the Draw Rectangle button to see your rectangle."); public void init() { setMaximumSize(new Dimension(700,700)); setMinimumSize(new Dimension(500,500)); setForeground(Color.green); add(heightLabel); add(heightField); add(widthLabel); add(widthField); add(drawButton); drawButton.addActionListener(this); add(outputLabel); setBackground(Color.red); background = getImage(getCodeBase(), "santa.jpg");
} public void actionPerformed(ActionEvent e) { height = Integer.parseInt(heightField.getText()); width = Integer.parseInt(widthField.getText()); repaint(); } public void paint(Graphics g) { g.setColor(Color.green); g.drawRect(125,100,width,height); g.fillRect(125,100,width,height); g.drawImage(0,0,background);
} }
|