Search code examples
javaswingfile-iojcombobox

How To Create JComboBox With Info From External Files?


I am calling on the following code from another class, and the frame displays correctly, however my JComboBox just doesn't appear! I had a working version earlier, however It didn't recognize one of my variables inside of the same class!

  1. How can I create a variable string that applies to an entire class and not just a section of it.
  2. With the following code, what am I doing wrong as far as why my JComboBox won't display?

import java.io.File;
import java.util.Scanner;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ProjectList extends JFrame {
    private static final long serialVersionUID = 1l;
    String Path = new File("").getAbsolutePath();
    public Scanner x;

    public ProjectList() {
        super("My File");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setAlwaysOnTop(true);
        setUndecorated(true);
        setLocation(444, 327);
        setSize(400, 250);
        try {
            x = new Scanner(new File(Path + "/Name.txt"));
        } catch (Exception e) {
            System.out.println("Path Error: Path Does Not Exist!");
        }
    }

    public void readPJ1() {
        while (x.hasNext()) {
            String PJ1name = x.next();
        }
        String PJ1 = "";
        String PJ2 = "";
        String PJ3 = "";
        String PJ4 = "";
        String PJ5 = "";
        String PJ6 = "";
        String PJ7 = "";
        String PJ8 = "";
        String PJ9 = "";
        String PJ10 = "";
        String PJ11 = "";
        String PJ12 = "";
        String PJ13 = "";
        String PJ14 = "";
        String PJ15 = "";
        String PJ16 = "";
        String PJ17 = "";
        String PJ18 = "";
        String PJ19 = "";
        String PJ20 = "";
        JPanel p1 = new JPanel();
        String[] ho = { "jo", "ho", "joe" };
        JComboBox cb = new JComboBox(ho);
        add(p1);
    }
}

Solution

    1. You can create a field ( member variable ) which is accessible inside the class
    2. You need to add the JComboBox to the JPanel :

      JPanel p1 = new JPanel(); String[] ho = { "jo", "ho", "joe" }; JComboBox cb = new JComboBox(ho); // add the JComboBox to the JPanel: p1.add(cb); // then add the JPanel to this JFrame: add(p1);