Mark Miw
Mark Miw

Reputation: 9

JPanel not being added to JFrame

When I try to add the panel into my frame, I get no results (hence I've tried making the panel's background to be red). Also, whenever I call on my linkedList in my Vertex class, I get an error saying: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. My main issue right now is with the panel.

Draw Panel class

@SuppressWarnings("serial")
public class DrawPanel extends JPanel {
Project4Test test = new Project4Test();
Graph graph;
Vertex v;

public DrawPanel() {
    setBackground(Color.red);
    setPreferredSize(new Dimension(500,500));

}

public void paintComponent(Graphics page) {
    Graphics2D page2 = (Graphics2D) page;
    page2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    page2.setColor(Color.black);

    Iterator iterator = test.hashEdge.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry dualEntry = (Map.Entry)iterator.next();
        Edge e = (Edge) dualEntry.getValue();
        drawEdge(page2, e.vertex1, e.vertex2);
    }

    ListIterator<Vertex> listIterator = v.linkedList.listIterator();
    while(listIterator.hasNext()) {
    drawEdge(page2, v, listIterator.next());
    }
}

public void drawEdge(Graphics2D page2, Vertex vertex1, Vertex vertex2) {
    //x1, y1, x2, y2
    page2.setColor(Color.black);
    page2.draw(new Line2D.Double(vertex1.latitude, vertex1.longitude, vertex2.latitude, vertex2.longitude));
}
}

Test Class

@SuppressWarnings("serial")
public class Project4Test {
static int numVertices = 0;
static Map<String, Vertex> hashVertex = new HashMap<String, Vertex>();
static Map<String, Edge> hashEdge = new HashMap<String, Edge>();

//Map with String intersectionID as the key, and Vertexes as the value
@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) {
    JFrame frame = new JFrame("Map");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);
    DrawPanel drawpanel = new DrawPanel();
    frame.setSize(660, 630);
    frame.add(drawpanel);

    //frame.setExtendedState(Frame.MAXIMIZED_BOTH);



    File inFile = new File(args[0]);
    //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
    //DrawPanel drawpanel;
    //frame.setVisible(true);


    try {
        Scanner scan = new Scanner(inFile);
        Graph newGraph = new Graph(0, false);

        while(scan.hasNext()) {
            String temp = scan.nextLine();
            String[] info = temp.split("\\t", 4);
            String interRoad = info[0];

            //If it is an intersection
            if(info[0].equalsIgnoreCase("i")) {
                String vertexID = info[1];
                double x = Double.parseDouble(info[2]);
                double y = Double.parseDouble(info[3]);
                //System.out.println(interRoad + " " + vertexID + " " + x + " " + y);
                //Insert to vertex here
                Vertex tempVertex = new Vertex(vertexID, numVertices, x , y);
                hashVertex.put(vertexID, tempVertex);
                numVertices++;
            }//end of intersection

            //Update graph to have the number of vertices
            newGraph = new Graph(numVertices, false);

            //If it is a road
            if(info[0].equalsIgnoreCase("r")) {
                String roadID = info[1];
                String vertexID1 = info[2];
                String vertexID2 = info[3];

                Vertex vertex1 = hashVertex.get(vertexID1);
                Vertex vertex2 = hashVertex.get(vertexID2);
                //System.out.println(interRoad + " " + roadID + " " + vertexID1 + " " + vertexID2);
                Edge newEdge = new Edge(roadID, vertex1, vertex2);
                hashEdge.put(roadID, newEdge);

                //Essentially saying linkedList(v1).add(v2) because if it's a road, it's inherently connected
                vertex1.linkedList.add(vertex2);
                vertex2.linkedList.add(vertex1);
                //drawpanel = new DrawPanel(newGraph);
                frame.add(drawpanel);
            }
        }//end of while loop
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

//      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true); 
} //end of main


}

Upvotes: 0

Views: 71

Answers (2)

camickr
camickr

Reputation: 324118

public class DrawPanel extends JPanel 
{
    Project4Test test = new Project4Test();

The whole structure of your code is wrong. You should not have code that creates the Project4Test class.

The DrawPanel class should only do one thing which is do the custom painting of your panel.

In order to do the painting you need data. So the DrawPanel class needs methods like: setHashVertex(...) and setHashEdge(...). I'm sure you can think of better methods. But the main point in the logic that reads in your data must invoke a method of the DrawPanel class to add the data directly to the DrawPanel class. You should not rely on static variables from the Project4Test class to access the data. The data must be defined in the DrawPanel class.

The Project4Test class should only be used to create the GUI and load the data into the DrawPanel. It should NOT be used to contain the data used in the custom painting. Any time you use static variables must to access data in another class you really should look at your design.

Fix the entire structure of the code first before even worrying about the NPE.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

First and foremost, be sure to call your JPanel's own paintComponent method by calling the super's method in your override as this will allow the JPanel to draw its background color and do any other housekeeping graphics. In other words, change this:

public void paintComponent(Graphics page) {
    Graphics2D page2 = (Graphics2D) page;

to this:

@Override  // don't forget this
protected void paintComponent(Graphics page) {  // method should be protected
    super.paintComponent(page);  // ****** key to add this and call it first
    Graphics2D page2 = (Graphics2D) page;

As for your NullPointerException, you will want to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, something the exception's stacktrace will tell you, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.

Upvotes: 2

Related Questions