It seems that my input boxes seem to come up twice, even though their not supposed too. Can’t seem to figure out why. Would be great if anyone could help 🙂
int x; //temperature input
int y; //temperature type
int z; //temperature convert
int c; //temperature celsius
int f; //temperature fahrenheit
public void init()
{
setSize(500, 500);
Container c = getContentPane();
c.setBackground(Color.BLUE);
}
public void paint (Graphics g)
{
super.paint(g);
g.setFont(new Font("Veranda", Font.PLAIN, 20));
g.setColor(Color.BLACK);
String number = JOptionPane.showInputDialog("What temperature would you like to convert? (input # of degrees)");
x = Integer.parseInt(number);
String number2 = JOptionPane.showInputDialog("What temperature type are you inputting? 1. Fahrenheit 2. Celsius");
y = Integer.parseInt(number2);
if (y==1)
{
c=(5/9)*(f-32);
g.drawString("Your temperature of" + x + "is" + y + "Celsius", 250, 100);
}//end if
if (y==2)
{
f=(9/5)*c+32;
g.drawString("Your temperature of" + x + "is" +y + "Fahrenheit", 250, 100);
}//end if
}//end paint
I understand this is an extremely basic program, but I’m more or less just trying to learn java by staring on basic stuff. So hopefully if I can understand how to get a simple program functioning, I can move on.
Don’t put in JOptionPane methods in a paint method unless you want to freeze your program to a crawl. The
paint(...)method should be for painting only. The paint method is responsible for drawing everything that the component holds, and if you break up its flow unnecessarily, your gui won’t render in a timely way, or may not render at all.You also don’t have control over when paint is called or even if it will be called. As you can see, it is not directly called by you (nor should it be), but rather is called by the JVM either in response to a suggestion in the code (by calling
repaint()) or due to request by the operating system, for instance if the OS finds a section of a window is “dirty”, it will do this. In fact you’re finding that it’s often called twice initially for these reasons. Put that code somewhere else, perhaps the in the init method.Also, this appears to possibly be a Swing application, not an AWT application, since you call
getContentPane()in your init method. If so, don’t draw directly in thepaint(...)method of a JApplet, but instead in thepaintComponent(...)method of a JPanel or other JComponent derivative that the JApplet holds. There are several reasons for this, but the main one is that the applet’s paint(…) method is responsible for many things that you don’t want to take the chance on messing with, including the painting of borders and child windows, and instead you should override a method that is responsible for painting a component only.