test
test

Reputation: 18200

Java JList not appearing

On every JList I've made... I've had to CLICK on it before ANY of the JList would show up. It was like... invisible but still there... UNTIL I clicked on it...

I have tried list.setVisible(true) and such... but no luck. :\ Help? Yes, I tried the Javadoc, Google, AND SO Search. >_< I have never encountered a problem like this.

Code:

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import javax.swing.JList;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import java.util.*;

public class inventory extends JApplet implements MouseListener {

public static String newline;
public static JList list;
int gold = 123;

    public void init() {



ArrayList<String> arr = new ArrayList<String>();
arr.add("Hatchet");
arr.add("Sword");
arr.add("Shield");
arr.add(gold + " Gold");
System.out.println("You have " + arr.size() + " items in your inventory.");
showInventory(arr);



        list = new JList(arr.toArray());

        add(list);

        list.addMouseListener(this);

        list.setVisible(true);

    }

public static void showInventory (ArrayList<String> theList) {
for (int i = 0; i < theList.size(); i++) {
System.out.println(theList.get(i));
}
}


    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
        Object index = list.getSelectedValue();
       System.out.println("You have selected: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }




    public void paint(Graphics g) {

    }
}

Upvotes: 1

Views: 1556

Answers (3)

Rabindra Barik
Rabindra Barik

Reputation: 11

You can add this.setVisible(true); line at the end of the init() method like

list.addMouseListener(this);

list.setVisible(true);
this.setVisible(true);

Upvotes: 1

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

Or if you want to override the paint method, replace it with:

public void paint(Graphics g) {
   super.paint(g);
   // your code
}

Upvotes: 2

Luis Miguel Serrano
Luis Miguel Serrano

Reputation: 5099

You have to erase this part from your code:

public void paint(Graphics g) {

}

Basicly your problem was that you were overwriting the paint method with an empty method. That is why your list was not displaying properly at start.

Upvotes: 1

Related Questions