I’m working on my first java project, and I’ve been confounded. This opens a dialog box to get a number from 0-255, checks that it is an integer and that it is in range, then uses the int to make a shade of gray for the background of a graphic applet. I have it doing everything it’s supposed to! But it doesn’t draw the applet. The program is terminated after the last time JOptionPane is called.
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import java.awt.Graphics;
import java.awt.Color;
@SuppressWarnings("serial")
public class DrawingShapes extends JApplet
{
private Shade shade = new Shade();
private void getColor()
{
int rgb = 0;
boolean useful = false;
String number = JOptionPane.showInputDialog("Make this easy for me.\n"
+ "Type an integer between 0 and 255");
{
try
{
rgb = Integer.parseInt(number);
if (rgb > 0 && rgb < 255)
{
useful = true;
shade.setColor(rgb);
}
else
{
useful = false;
number = JOptionPane.showInputDialog( null, "\"" + number + "\""
+ " is not between 0 and 255!\n"
+ "Lrn2 be doin' it right!" );
}
}
catch (NumberFormatException nfe)
{
number = JOptionPane.showInputDialog(null, "\"" + number + "\""
+ " is not an integer!\n"
+ "Lrn2 be doin' it right!");
}
}
if (useful)
{
JOptionPane.showMessageDialog(null, rgb + " will be the shade of gray.");
//WHEN this message is closed, the program seems to quit.
//System.exit(0);
}
}
public static void main(String[] args)
{
new DrawingShapes().getColor();
}
public class Shade
{
private int color;
public void setColor(int col)
{
color = col;
System.out.println("color: " + color);
System.out.println("col: " + col); //IT prints these lines....
}
public void paint (Graphics g) //Everything after this is sadly ignored.
{
int size = 500;
setSize(size, size);
int rgb = color;
Color gray = new Color(rgb,rgb,rgb);
setBackground(gray);
System.out.println(rgb + " This should be the third time");
g.drawOval(0, 0, size, size);
}
}
}
I cannot figure out what is wrong with ‘public void paint (Graphics g)’, but it doesn’t cause anything to happen. I’ll welcome correction from anyone, I’m sure I’ve made a laughable mistake because I’m not quite comfortable with the language…
This isn’t an applet program — yes, it extends JApplet, but there’s no
initmethod and instead you have amainmethod — a method that will not be called in an applet program. Please go through the JApplet Tutorial first before doing anything else.Other suggestions:
init()override.paintComponent(...)method of a JPanel that is shown in the JApplet.paint(...)orpaintComponent(...)method.super.paintComponent(...)method inside of yourpaintComponent(...)method override, and often this is the first method call of your method.init()method override, you will need a main method, and you’ll put your components into a JFrame as your top-level Window.Luck!