首页 > 解决方案 > JComboBox 不显示数组

问题描述

试图将一个数组传递给我的 JComboBox,但组合框显示为空。这是 GUI.java

package prototype;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultComboBoxModel;

import java.util.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Color;
import javax.swing.JComboBox;

import java.util.*;
import java.lang.Thread;
import java.awt.Insets;

import java.util.ArrayList;

public class GUI extends JFrame {
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        startUp();
        loadCarList();
        loadRegPlateArray();
    }
    
    public static void startUp()
    {
        try {
            File file = new File("Car.csv");
            if(!file.exists())
            {
                file.createNewFile();
                PrintWriter pw = new PrintWriter(file);
                pw.println("regPlate,price,make,model,fType,colour,mileage,prevOwners,mpg,0to60,bhp,maxSpeed,feature1,feature2,feature3,feature4,sold,boughtFor,profit");
                pw.close();
                System.out.println("Data loaded successfully!");
            }
            else
            {
                System.out.println("Data loaded successfully!");
            }
            } catch(IOException e) {
                e.printStackTrace();
            }
    }
    
    public static void loadCarList()
    {
        String currentLine = "";
        String[] linearray;
                
        try (BufferedReader br = new BufferedReader(new FileReader("Car.csv")))
        {
            while ((currentLine = br.readLine()) != null) 
            {
                linearray = currentLine.split(",");
                Car tempcar = new Car(
                                    linearray[0], Double.parseDouble(linearray[1]), linearray[2], linearray[3], linearray[4], linearray[5], Integer.parseInt(linearray[6]),
                                    Integer.parseInt(linearray[7]), Double.parseDouble(linearray[8]), Double.parseDouble(linearray[9]), Integer.parseInt(linearray[10]),
                                    Integer.parseInt(linearray[11]), linearray[12], linearray[13], linearray[14], linearray[15], Boolean.parseBoolean(linearray[16]),
                                    Double.parseDouble(linearray[17]), Double.parseDouble(linearray[18]));
                CarList.carArray.add(tempcar);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
            
    public static void loadRegPlateArray()
    {
        CarList cl = new CarList();
        
        for(int i = 0; i < CarList.carArray.size(); i++)
        {
            cl.regArray[i] = CarList.carArray.get(i).regPlate;
        }
    }

    /**
     * Create the frame.
     */
    public GUI() {
        CarList cl = new CarList();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(500, 200, 1000, 600);
        contentPane = new JPanel();
        contentPane.setBackground(Color.BLACK);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[]{0, 124, 123, 0, 0, 0, 0, 0, 0, 0, 0, 275, 189, 7, 0};
        gbl_contentPane.rowHeights = new int[]{0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 155, 0};
        gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        contentPane.setLayout(gbl_contentPane);
        
        JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(cl.regArray));
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.insets = new Insets(0, 0, 5, 5);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 1;
        gbc_comboBox.gridy = 2;
        contentPane.add(comboBox, gbc_comboBox);
    }
}

这是 Car.java

package prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.DataInputStream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.IOException;

public class Car {
    public String regPlate;
    public double price;
    public String make;
    public String model;
    public String fType;
    public String colour;
    public int mileage;
    public int prevOwners;
    public double mpg;
    public double noughttosixty;
    public int bhp;
    public int maxSpeed;
    public String feature1;
    public String feature2;
    public String feature3;
    public String feature4;
    public boolean sold;
    public double boughtFor;
    public double profit;
    
    public String[] regPlates;
    public String allRegPlates;
    
    Scanner input = new Scanner(System.in);
    public List<String[]> line = new ArrayList<String[]>();
    String lines = "";
    
    public String thisLine;
    
    public Car(String cregPlate, double cprice, String cmake, String cmodel, String cfType,
            String ccolour, int cmileage, int cprevOwners, double cmpg, double cnoughttosixty, int cbhp, int cmaxSpeed,
            String cfeature1, String cfeature2, String cfeature3, String cfeature4, boolean csold, double cboughtFor, double cprofit)
    {
        this.regPlate = cregPlate;
        this.price = cprice;
        this.make = cmake;
        this.model = cmodel;
        this.fType = cfType;
        this.colour = ccolour;
        this.mileage = cmileage;
        this.prevOwners = cprevOwners;
        this.mpg = cmpg;
        this.noughttosixty = cnoughttosixty;
        this.bhp = cbhp;
        this.maxSpeed = cmaxSpeed;
        this.feature1 = cfeature1;
        this.feature2 = cfeature2;
        this.feature3 = cfeature3;
        this.feature4 = cfeature4;
        this.sold = csold;
        this.boughtFor = cboughtFor;
        this.profit = cprofit;
    }
}

这是 CarList.java

package prototype;

import java.util.*;

import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import java.util.ArrayList;

public class CarList {
    static ArrayList<Car> carArray = new ArrayList<Car>();
    String[] regArray = new String[carArray.size()];
}

这是我的 CSV 文件。 汽车.csv

当我测试regArray并将其打印到 CLI 时,它应该显示一个数组列表。但是,当我将它发送到 时JComboBox,它不起作用。不知道我需要在这里做什么。

标签: javaarraysswinguser-interfacejcombobox

解决方案


startup()如果文件Car.csv不存在,方法创建一个空文件。当文件不存在时,您创建它并向其写入无效数据。我认为您应该删除该方法。

方法loadCarList()应该在调用类的构造函数之前调用GUI。这是该构造函数中的一行

comboBox.setModel(new DefaultComboBoxModel(cl.regArray));

执行此行时,cl.regArray它是空的,因为您还没有调用 method loadCarList()。但是还有另一个问题。在类的构造函数中,GUI您创建了一个新的类CarList实例,该实例与您在方法中创建的实例分开loadCarList(),因此即使您在调用类构造函数loadCarList()之前调用,您仍然是空的。为了将现有代码中的更改保持在最低限度,您应该从类构造函数中调用方法,并且还应该向该方法添加一个参数,以便它加载您在类构造函数中创建的实例的数组。但是方法还有另一个问题。当您创建类的实例时GUIComboBoxModelloadRegPlateArray()GUICarListGUIloadRegPlateArray()CarList,您将大小设置为regArray大小,carArray因此您需要在调用构造函数carArray之前进行初始化,因此方法必须是从方法调用的第一个方法。CarListloadCarList()main()

因此,总而言之,这里列出了需要进行的更改。请注意,这些更改只会确保您JComboBox将显示数据。

  1. Car.csv在运行应用程序之前,请确保文件存在并包含数据。
  2. 您的应用程序应该做的第一件事是从文件中加载数据Car.csv
  3. 加载数据后,调用类的构造函数GUI
  4. 在该构造函数中要做的第一件事是创建一个实例CarList并初始化regArray
  5. 创建并显示您的 GUI。

我唯一改变的课程是GUI。这是该类的代码以及我的更改。

public class GUI extends JFrame {
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        loadCarList();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void loadCarList() {
        String currentLine = "";
        String[] linearray;
        try (BufferedReader br = new BufferedReader(new FileReader("Car.csv"))) {
            while ((currentLine = br.readLine()) != null) {
                linearray = currentLine.split(",");
                Car tempcar = new Car(linearray[0],
                                      Double.parseDouble(linearray[1]),
                                      linearray[2],
                                      linearray[3],
                                      linearray[4],
                                      linearray[5],
                                      Integer.parseInt(linearray[6]),
                                      Integer.parseInt(linearray[7]),
                                      Double.parseDouble(linearray[8]),
                                      Double.parseDouble(linearray[9]),
                                      Integer.parseInt(linearray[10]),
                                      Integer.parseInt(linearray[11]),
                                      linearray[12],
                                      linearray[13],
                                      linearray[14],
                                      linearray[15],
                                      Boolean.parseBoolean(linearray[16]),
                                      Double.parseDouble(linearray[17]),
                                      Double.parseDouble(linearray[18]));
                CarList.carArray.add(tempcar);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void loadRegPlateArray(CarList cl) {
        for (int i = 0; i < CarList.carArray.size(); i++) {
            cl.regArray[i] = CarList.carArray.get(i).regPlate;
        }
    }

    /**
     * Create the frame.
     */
    public GUI() {
        CarList cl = new CarList();
        loadRegPlateArray(cl);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(500, 200, 1000, 600);
        contentPane = new JPanel();
        contentPane.setBackground(Color.BLACK);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[]{0, 124, 123, 0, 0, 0, 0, 0, 0, 0, 0, 275, 189, 7, 0};
        gbl_contentPane.rowHeights = new int[]{0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 155, 0};
        gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        contentPane.setLayout(gbl_contentPane);

        JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(cl.regArray));
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.insets = new Insets(0, 0, 5, 5);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 1;
        gbc_comboBox.gridy = 2;
        contentPane.add(comboBox, gbc_comboBox);
    }
}

推荐阅读