Nikhil Bansode
Nikhil Bansode

Reputation: 43

Java JFrame issue with dialog box

When I run the program I'm facing some problem with JFrame Buffer, I don't know what the problem exactly is. When I run the program, it displays some dialog box part on the top left corner of the buffer.

Here is output of my program:

https://i.sstatic.net/SpVSD.jpg

And following is the code

Thank you.

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class Main extends JPanel 
{
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        int[] x1 = new int[10];
        int[] y1 = new int[10];
        int i,n;
        Polygon p=new Polygon();
        n = Integer.parseInt(JOptionPane.showInputDialog("Enter no. of co-ordinates of polygon: "));
        System.out.println(" no. of co-ordinates of polygon are :"+n);

        for(i=0;i<n;i++) 
        {  
            x1[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter x co-ordinates of polygon: "));
            y1[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter y co-ordinates of polygon: "));
        }
        for(i=0;i<n-1;i++)
        {
            g.drawLine(x1[i],y1[i],x1[i+1],y1[i+1]);
        }
        g.drawLine(x1[n-1],y1[n-1],x1[0],y1[0]);
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setTitle("Polygon");
        frame.setSize(500,500);
        Container contentPane = frame.getContentPane();
        contentPane.add(new Main());
        frame.setVisible(true);
    }
}

Upvotes: 0

Views: 61

Answers (2)

SHAMBANNA
SHAMBANNA

Reputation: 312

The paintComponent( ... ) method is called whenever 'something' (the AWT EDT thread) thinks the component needs to be repainted. That method is called often and often at moments you didn't expect it to be called. So, don't show a JOptionPane in the body of that method.

  • So it is better to call from main method only as camickr said.

Upvotes: 1

camickr
camickr

Reputation: 324088

Never display an JOptionPane from a painting method. Painting methods are for painting only, they are not for getting user input.

Instead you need to do the following:

  1. The JOptionPane should be displayed from the main method to gather the x/y parameters.

  2. Modify your Main() class to have a method like addPoint(int x, int y).

  3. The above method will then save the x/y values to an ArrayList object in your class. I would store Point objects in this list.

  4. The painting method will then iterate through the List and then paint each line.

Upvotes: 3

Related Questions