我正在研究我的第一个java项目,我感到很困惑。这将打开一个对话框以获取0-255之间的数字,检查它是否为整数并且它在范围内,然后使用int为图形小程序的背景制作灰色阴影。我做它应该做的一切!但它并没有绘制小程序。程序在最后一次调用JOptionPane后终止。
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);
}
}
}
我无法弄清楚'public void paint(Graphics g)'有什么问题,但它不会导致任何事情发生。我会欢迎任何人纠正,我确信我犯了一个可笑的错误,因为我对这种语言不太满意......
答案 0 :(得分:4)
这不是applet程序 - 是的,它扩展了JApplet,但没有init
方法,而是你有一个main
方法 - 一个不会在applet中调用的方法程序。在做其他任何事情之前,请先通过JApplet Tutorial。
其他建议:
init()
覆盖。paintComponent(...)
方法。paint(...)
方法中设置背景颜色或更改GUI的状态。paintComponent(...)
方法覆盖中调用super.paintComponent(...)
方法,这通常是您方法的第一个方法调用。paintComponent(...)
方法覆盖,您将需要一个主方法,您将把您的组件放入JFrame作为顶级窗口。运气!