有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将arraylist或array放入构造函数中的JList?

我的想法是用JavaSwing制作一个应用程序,它包含一个登录窗口,然后是一种公司选择器。但是我需要从json url导入公司列表和ID,这就是我所做的,但是如何将构造函数中的数组推送到JList中呢

这是我的主要方法

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);
    }
}

这是我的登录窗口

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");
            }

        }});



}

}

这是公司选择窗口

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();
}

我试着用JSONarray做一个ArrayList甚至是普通数组,然后把它推到JList(因为我认为这样做是正确的)。我知道这里的一切都有点乱。我看了一些教程,读了一些文章,但我做不到。对不起,我的英语不好,如果我的问题是愚蠢的,对不起:)。谢谢


共 (2) 个答案

  1. # 1 楼答案

    尝试使用DefaultListModel而不是ArrayList:

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

    然后将其传递给JList构造函数

  2. # 2 楼答案

    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);
    }
    

    使构造函数接受字符串项的数组,然后调用传递数组的方法

    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());
    }
    

    或者,您可以让构造函数接受arraylist,然后可以按照上述方法将列表添加到数据中