• 0

[JAVA] how do i make this stop looping?


Question

hey neowinians,

i'm trying to write this code to put a name given by the user into a rectangle, but the input dialog box keeps popping up infinitely, can you guys please help me out?

thanks in advance.

here's the code:

import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JOptionPane;

public class NameInRectangle extends Applet
{
    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        final int HUGE_SIZE = 28;
        Font hugeFont = new Font("Serif", Font.BOLD, HUGE_SIZE);
        g2.setFont(hugeFont);
        String input = JOptionPane.showInputDialog("Enter your name ");
   	 String name = input;
   	 FontRenderContext context = g2.getFontRenderContext();
   	 Rectangle2D bounds = hugeFont.getStringBounds(name, context);
   	 double yMessageAscent = -bounds.getY();
   	 double yMessageDescent = bounds.getHeight() + bounds.getY();
   	 double yMessageHeight = bounds.getHeight();
   	 double xMessageWidth = bounds.getWidth();
   	 double xLeft = (getWidth() - xMessageWidth)/2;
   	 double yTop = (getHeight() - yMessageHeight)/2;
   	 double yBase = yTop + yMessageAscent;
   	 g2.drawString(name, (float)xLeft, (float)yBase);
   	 g2.draw(new Rectangle2D.Double(xLeft, yTop, xMessageWidth, yMessageHeight));
   	 g2.draw(new Line2D.Double(xLeft, yBase, xLeft + xMessageWidth, yBase));
    }
}

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

that wouldn't be the best method... because the paint method if i'm correct is continuously invoked in some form. You can overcome this in some way like checking if a instance variable which contain the name of the input is null if it's not then don't show an input dialog.

Link to comment
Share on other sites

  • 0
that wouldn't be the best method... because the paint method if i'm correct is continuously invoked in some form. You can overcome this in some way like checking if a instance variable which contain the name of the input is null if it's not then don't show an input dialog.

584750220[/snapback]

Yeah, paint is called every refresh. It's probably best not to ask the user for input in the paint method. Ask it when it starts up and store the input in a global variable and then paint that in.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.