简体   繁体   中英

How to put arraylist or array to JList in constructor?

My idea is to make an app in Java swing, which contains of a login window and then a kind of company chooser. But I need to import the company list and ID's from the json url, which is what I did, but how can I push the array in constructor into a JList ?

This is my main method

import java.awt.EventQueue;

public class Main {
    public static void main(String[] args) {        
        LoginWindow loginWindow = new LoginWindow();
        loginWindow.setVisible(true);
        loginWindow.setSize(500, 400);
        //loginWindow.setDefaultCloseOperation(Exit);
    }
}

Here's my login window.

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

public class LoginWindow extends JFrame {

private JLabel item1;
private JLabel item2;
private JTextField login;
private JPasswordField password;
private JButton loginButton;
private JPanel loginPanel;


GridBagConstraints gbc = new GridBagConstraints();

public static void main(String[] args) {

}

LoginWindow(){
    super("MyApp");
    setLayout(new GridBagLayout());
    gbc.insets = new Insets(5, 5, 5, 5);
    item1 = new JLabel("Login");
    gbc.gridx = 0;
    gbc.gridy = 1;
    add(item1, gbc);

    item2 = new JLabel("Password");
    gbc.gridx = 0;
    gbc.gridy = 2;
    add(item2, gbc);

    login = new JTextField(15);
    gbc.gridx = 2;
    gbc.gridy = 1;
    add(login, gbc);

    password = new JPasswordField(15);
    gbc.gridx = 2;
    gbc.gridy = 2;
    add(password, gbc);

    loginButton = new JButton("Login");     
    gbc.gridx = 2;
    gbc.gridy = 3;
    add(loginButton, gbc);

    loginButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if("admin".equals(password.getText()) && 
"admin".equals(login.getText())){
                dispose();
                CompanySelectionWindow frame = new CompanySelectionWindow();
                frame.setVisible(true);
                frame.setSize(500, 300);
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            }
            else{
        JOptionPane.showMessageDialog(null, "Wrong password or login");
            }

        }});



}

}

and here's CompanySelectionWindow

import javax.swing.*;
import org.json.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;


public class CompanySelectionWindow extends JFrame {

private JLabel label;
private JList list;
//private JList<JSONArray> list = new JList<>();
DefaultListModel<companyInfo> model = new DefaultListModel<>();
GridBagConstraints gbc = new GridBagConstraints();


public CompanySelectionWindow() {
    super("Company Selection Window");
    //model.addElement(element);
    setLayout(new GridBagLayout());
    gbc.insets = new Insets(5, 5, 5, 5);
    label = new JLabel("Choose company:");
    gbc.gridx = 3;
    gbc.gridy = 3;
    add(label);
    **list = new JList(what and how put something here?);**
}

public static void main(String[] args) {
    String jsonString = callURL("xxx");
    System.out.println("\n\njsonString: " + jsonString);
    ArrayList<JSONObject> array = new ArrayList<>();
    //String str = "{id:\"123\",name:\"myName\"}   {id:\"456\",name:\"yetanotherName\"}{id:\"456\",name:\"anotherName\"}";
    String[] strs = jsonString.split("(?<=\\})(?=\\{)");
    for (String s : strs) {
        System.out.println(s);          
    }
    try {

        JSONArray jsonArray = new JSONArray(jsonString);

        int count = jsonArray.length(); // get totalCount of all jsonObjects
        for(int i=0 ; i< count; i++){   // iterate through jsonArray 
            JSONObject jsonObject = jsonArray.getJSONObject(i);  // get jsonObject @ i position 
            array.add(i, jsonObject);
            System.out.println("jsonObject " + i + ": " + jsonObject);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }


}

public String[] pullArray(String[] a){
    return a;
}

public static String callURL(String myURL) {
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;

    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(),
                    Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }

        }
    in.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception while calling URL:"+ myURL, e);
    } 

    return sb.toString();
}

I tried to make an ArrayList and even normal array out of JSONarray and push it to JList (cause I think it'll be the right way to do it). I know everything here is a bit messy. I watched several tutorials and read some articles here and there, but i can't do it. Sorry for my bad English and sorry if my question is stupid :). Thanks

Try using a DefaultListModel instead of an ArrayList:

DefaultListModel<JSONObject> array = new DefaultListModel<>();

then pass it into the JList constructor.

public CompanySelectionWindow(String []ar) {
    super("Company Selection Window");
    //model.addElement(element);
    setLayout(new GridBagLayout());
    gbc.insets = new Insets(5, 5, 5, 5);
    label = new JLabel("Choose company:");
    gbc.gridx = 3;
    gbc.gridy = 3;
    add(label);
    jList1.setListData(ar);
}

make your constructor to accept a array of your string items then call the method passing an array

public CompanySelectionWindow(ArrayList<String> listdata) {
    super("Company Selection Window");
    //model.addElement(element);
    setLayout(new GridBagLayout());
    gbc.insets = new Insets(5, 5, 5, 5);
    label = new JLabel("Choose company:");
    gbc.gridx = 3;
    gbc.gridy = 3;
    add(label);
    jList1.setListData(listdata.toArray());
}

or you can make the constructor to accept arraylist then you can follow the above approach to add list to data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM