有 Java 编程相关的问题?

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

在JavaSwingGUI中显示和操作ArrayList的数组

这是一个在Java中带有Arraylist的GUI。我试图在中央面板上以一种很好的方式显示ArrayList。如果能看到完整的列表就好了!我必须添加什么代码才能使当前数据进入JList并正确显示。另外,如何从GUI顶部的输入和添加按钮添加到ArrayList。关于什么代码可以达到这个目的有什么想法吗

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JScrollPane;
import java.util.ArrayList;
import java.util.Collections;

public class ArrayListGUI extends JPanel
{
// main method; runs application and sets up the JFrame
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("ArrayList");
        ArrayListGUI content = new ArrayListGUI();
        frame.setContentPane(content);
        frame.pack();
        frame.setResizable(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800,690);
        frame.setLocation(75,50);
        frame.setVisible(true);
    }

// declare variables
   private JList message;
   private Action messageAction;
   private JButton removeAll, printL, saveF, quitA; //west
   private JButton az, za, rev, random; // east
   private JTextField inputBox;
   private JButton addButton;
   private JTextField sizeBox; // bottom

//-------------------------------------------------------------------------------------------

    public ArrayListGUI()
        {

        ArrayList<String> wordlist = new ArrayList<String>();
        // wordlist ArrayList has been created, now we add words to that list...
        // (data set from the Word Association Test - Carl Jung)
        wordlist.add("Head");
        wordlist.add("Green");
        wordlist.add("Water");
        wordlist.add("To sing");
        wordlist.add("Dead");
        wordlist.add("Long");
        wordlist.add("Ship");
        wordlist.add("To pay");
        wordlist.add("Window");
        wordlist.add("Friendly");
        wordlist.add("To cook");
        wordlist.add("To ask");
        wordlist.add("Cold");
        wordlist.add("Stem");
        wordlist.add("To dance");
        wordlist.add("Village");
        wordlist.add("Lake");
        wordlist.add("Sick");
        wordlist.add("Pride");
        wordlist.add("To Cook"); // this item 20 in the word array
        wordlist.add("Ink");
        wordlist.add("Angry");
        wordlist.add("Needle");
        wordlist.add("To swim");
        wordlist.add("Voyage");
        wordlist.add("Blue");
        wordlist.add("Lamp");
        wordlist.add("To sin");
        wordlist.add("Bread");
        wordlist.add("Rich");
        wordlist.add("Tree");
        wordlist.add("To prick");
        wordlist.add("Pity");
        wordlist.add("Yellow");
        wordlist.add("Mountain");
        wordlist.add("To die");
        wordlist.add("Salt");
        wordlist.add("New");
        wordlist.add("Custom");
        wordlist.add("To pray"); // this item 40 in the word array
        wordlist.add("Money");
        wordlist.add("Foolish");
        wordlist.add("Pamphlet");
        wordlist.add("Despise");
        wordlist.add("Finger");
        wordlist.add("Expensive");
        wordlist.add("Bird");
        wordlist.add("To fall");
        wordlist.add("Book");
        wordlist.add("Unjust");
        wordlist.add("Frog");
        wordlist.add("To part");
        wordlist.add("Hunger");
        wordlist.add("White");
        wordlist.add("Child");
        wordlist.add("To take care");
        wordlist.add("Lead pencil");
        wordlist.add("Sad");
        wordlist.add("Plum");
        wordlist.add("To marry"); // this item 60 in the word array
        wordlist.add("House");
        wordlist.add("Dear");
        wordlist.add("Glass");
        wordlist.add("To quarrel");
        wordlist.add("Fur");
        wordlist.add("Big");
        wordlist.add("Carrot");
        wordlist.add("To paint");
        wordlist.add("Part");
        wordlist.add("Old");
        wordlist.add("Flower");
        wordlist.add("To beat");
        wordlist.add("Box");
        wordlist.add("Wild");
        wordlist.add("Family");
        wordlist.add("To wash");
        wordlist.add("Cow");
        wordlist.add("Friend");
        wordlist.add("Luck");
        wordlist.add("Lie"); // this item 80 in the word array
        wordlist.add("Deportment");
        wordlist.add("Narrow");
        wordlist.add("Brother");
        wordlist.add("To fear");
        wordlist.add("Stork");
        wordlist.add("False");
        wordlist.add("Anxiety");
        wordlist.add("To kiss");
        wordlist.add("Bride");
        wordlist.add("Pure");
        wordlist.add("Door");
        wordlist.add("To choose");
        wordlist.add("Hay");
        wordlist.add("Contented");
        wordlist.add("Ridicule");
        wordlist.add("To sleep");
        wordlist.add("Month");
        wordlist.add("Nice");
        wordlist.add("Woman");
        wordlist.add("To abuse"); // Phew! this item 100 in the word array
// Word list array is now populated with the basic data


//------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
// ArrayList actions outline, code/logic to mange the list. It is outputted to console for test purposes.
// next section outputs formatted list of words
        System.out.println("Contents of the ArrayList of words:");
        for(String str: wordlist)
        {
            System.out.println(str);
        }
// end output formatted list

// this section performs and displays the shuffle operation
        Collections.shuffle(wordlist);
        System.out.println("Results after shuffle operation:");
        for(String str: wordlist)
        {
            System.out.println(str);
        }
// end shuffle section

// prints an unformatted list of words in the ArrayList
        System.out.println(wordlist);

// this queries if the wordlist is populated.  Returns true if empty.  Returns false if populated
        System.out.println("Is ArrayList empty? "+ wordlist.isEmpty());

// finds and prints the index of a given word in the list, in this case 'ship'
        System.out.println("Index of Ship is "+ wordlist.indexOf("Ship"));


// finds the size of the ArrayList and prints to screen
        System.out.println("Size of the ArrayList is: "+ wordlist.size());

// end ArrayList actions design outline

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------


// create an introduction message
        String begin ="Welcome! \n\n Press OK to begin the ArrayList GUI demo";
        JOptionPane.showMessageDialog( null, begin );

// section for main MESSAGE

        JList <String> message = new JList<>(wordlist.toArray(new String[0]));
        //message.setOpaque(true);

        JScrollPane scrollPane = new JScrollPane(message);
        add(scrollPane, BorderLayout.CENTER);
//-----------------------------------------------------------------end message

// section for bottom panel
// call wordlist -- find if empty or not, display current size, and find index of sample word --
        sizeBox = new JTextField("  Is ArrayList empty? "+ wordlist.isEmpty() +
            "             Current size of list = "+ wordlist.size() +
            "              Index of the example word 'Ship' is "+ wordlist.indexOf("Ship"),
            JTextField.CENTER);
        sizeBox.setEditable(false);  // ensures that the list text cannot be edited in the panel
        sizeBox.setOpaque(true);
        sizeBox.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        sizeBox.setFont( new Font("Serif", Font.BOLD, 14) );

//------------------------------------------------------------------------------end bottom

// west panel
        ActionListener westListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                switch ( evt.getActionCommand() )
                {
                    case "Remove all items":
                    System.out.println("Remove all");// demonstrates actionlistener is working
                    break;

                    case "Print List":
                    System.out.println("Print List");
                    break;

                    case "Save to file":
                    System.out.println("Save file");
                    break;

                    case "Quit application":
                    System.out.println("Quit");
                    break;
                }
            }
        };

// create buttons for west panel
        ButtonGroup westGroup = new ButtonGroup();

        removeAll = new JButton("Remove all items");
        westGroup.add(removeAll);
        removeAll.addActionListener(westListener);

        printL = new JButton("Print List");
        westGroup.add(printL);
        printL.addActionListener(westListener);

        saveF = new JButton("Save to file");
        westGroup.add(saveF);
        saveF.addActionListener(westListener);

        quitA = new JButton("Quit application");
        westGroup.add(quitA);
        quitA.addActionListener(westListener);

// ----------------------------------------------------------- end west

// create input box
        inputBox = new JTextField("", JTextField.CENTER);
        inputBox.setEditable(true);  // ensures that the list text cannot be edited in the panel
        inputBox.setOpaque(true);
        inputBox.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        inputBox.setFont( new Font("Serif", Font.BOLD, 22) );
        inputBox.setForeground(Color.WHITE);
        inputBox.setBackground(Color.BLACK);
// create add button
        addButton = new JButton("Add to List");

//addButtonListener to take input from word add box and include in ArrayList
        addButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
             System.out.println("Add item to list");
             wordlist.add(inputBox.getText() + ", "); // append the input to the list
            }
        });
// ------------------------------------------------- end input box

// start east
        ActionListener eastListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent evt2)
            {
                switch ( evt2.getActionCommand() )
                {
                    case "A to Z":
                    System.out.println("A to Z");
                    break;

                    case "Z to A":
                    System.out.println("Z to A");
                    break;

                    case "Reverse order":
                    System.out.println("Reverse order");
                    break;

                    case "Random order":
                    System.out.println("Random order");
                    Collections.shuffle(wordlist);
                    break;
                }
            }
        };

// create EAST buttons
        ButtonGroup eastGroup = new ButtonGroup();

        az = new JButton("A to Z");
        eastGroup.add(az);
        az.addActionListener(eastListener);

        za = new JButton("Z to A");
        eastGroup.add(za);
        za.addActionListener(eastListener);

        rev = new JButton("Reverse order");
        eastGroup.add(rev);
        rev.addActionListener(eastListener);

        random = new JButton("Random order");
        eastGroup.add(random);
        random.addActionListener(eastListener);

// end east
//--------------------------------------------------------------------------------------------------------

 // arrange the GUI with 4 panels
 // the current ArrayList will be displayed in the center.


        setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
        JPanel left = new JPanel();
        JPanel right = new JPanel();
        JPanel center = new JPanel();
        JPanel top = new JPanel();
        JPanel bottom = new JPanel();

// create border layout and populate
        setLayout(new BorderLayout(5,5));
        add(left, BorderLayout.WEST);
        add(right, BorderLayout.EAST);
        add(center, BorderLayout.CENTER);
        add(bottom, BorderLayout.SOUTH);

// place series of grid layouts inside the border layout components
        left.setLayout(new GridLayout(4,1));
        right.setLayout(new GridLayout(4,1));

        center.setLayout(new BorderLayout(5,5));
        center.add(message,BorderLayout.CENTER);
        center.add(top,BorderLayout.NORTH);

        top.setLayout(new GridLayout(1,2,5,5));
        bottom.setLayout(new GridLayout(1,2,5,5));

// west panel
        left.add(removeAll);
        left.add(printL);
        left.add(saveF);
        left.add(quitA);

// east panel
         right.add(az);
         right.add(za);
         right.add(rev);
         right.add(random);

// top and bottom panel

        top.add(inputBox);
        top.add(addButton);
        bottom.add(sizeBox);

    } // constructor ends

} // THE END ArrayListGUI

共 (2) 个答案

  1. # 1 楼答案

    将您的项目放入JList,并将JList放入滚动条中

  2. # 2 楼答案

    您可以将ArrayList转换为一个数组,该数组将用于初始化JList

    public class Listing extends JFrame {
    
        public static void main(String[] args) {
    
            new Listing();
        }
    
        Listing() {
    
            final ArrayList<String> wordlist = new ArrayList<String>();
            wordlist.add("Head");
            wordlist.add("Green");
            wordlist.add("Water");
            wordlist.add("To sing");
            wordlist.add("Dead");
            wordlist.add("Long");
            wordlist.add("Ship");
            wordlist.add("To pay");
            wordlist.add("Window");
            wordlist.add("Friendly");
            wordlist.add("To cook");
    
            JList<String> displayList = new JList<>(wordlist.toArray(new String[0]));
            JScrollPane scrollPane = new JScrollPane(displayList);
    
            getContentPane().add(scrollPane);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    }