从HashMap填充JList

时间:2018-06-08 21:28:17

标签: java swing hashmap hashtable jlist

我正在构建一个applet来更改jPanel的颜色,但是我很难让我的值显示在JList窗口中。 我知道有些人不喜欢NetBeans,但我们需要使用它。

这是我现在的代码

MainWindow.java

package ColorChanger;

import ColorMap.ColorMap;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;

/**
 *
 * @author 
 */
public class MainWindow extends javax.swing.JFrame {    

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
        pGUI();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbl_Title = new javax.swing.JLabel();
        lbl_instruct = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jl_HT = ShowList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbl_Title.setText("Color Changer");

        lbl_instruct.setText("Select A Color:");

        jl_HT.setModel(new DefaultListModel());
        jl_HT.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jl_HT);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_instruct, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lbl_Title))
                .addContainerGap(168, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbl_Title)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_instruct, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(108, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void pGUI() {
        JFrame mainFrame = new JFrame("Select a color to change background");
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowsClosing(WindowEvent windowevent) {
                System.exit(0);
            }
        });

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
        set Hashtable from ColorMap Package.

         */
 /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new MainWindow().setVisible(true);
        });
    }

    public JList ShowList() {
        JList jListO = null;
        JList jList = new JList();
        Hashtable ht = new Hashtable();
        ht.putAll(ColorMap.hColorMap);
        JList jlist = new JList(new Vector(ht.keySet()));
        DefaultListModel dlm = (DefaultListModel)jlist.getModel();
        Enumeration e = dlm.elements();
        while (e.hasMoreElements()) {
            jListO = (JList) e.nextElement();
        }
        return jListO;
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JList<JList> jl_HT;
    private javax.swing.JLabel lbl_Title;
    private javax.swing.JLabel lbl_instruct;
    // End of variables declaration                   

}

这是构建HashMap的ColorMap包。 ColorMap.java

    package ColorMap;

import java.awt.Color;
import java.util.HashMap;

/**
 *
 * @author 
 */
public class ColorMap {
    /*
    Creating the HashMap of Colors
    */
    public static HashMap<String, Color> hColorMap = new HashMap<>();
/*
    Populating the HashMap with the index and colors
    */
    public ColorMap() {
        hColorMap.put("Black", Color.BLACK);
        hColorMap.put("Blue", Color.BLUE);
        hColorMap.put("Cyan", Color.CYAN);
        hColorMap.put("Dark Gray", Color.DARK_GRAY);
        hColorMap.put("Gray", Color.GRAY);
        hColorMap.put("Green", Color.GREEN);
        hColorMap.put("Light Gray", Color.LIGHT_GRAY);
        hColorMap.put("Magenta", Color.MAGENTA);
        hColorMap.put("Orange", Color.ORANGE);
        hColorMap.put("Pink", Color.PINK);
        hColorMap.put("Red", Color.RED);
        hColorMap.put("White", Color.WHITE);
        hColorMap.put("Yellow", Color.YELLOW);
    }

    private String getName(Color color) {
        return color.getClass().getName();
    }

    public HashMap<String, Color> getColor() {
        return hColorMap;
    }

}

我遇到的问题是从HashMap中获取名称以显示在JList中

0 个答案:

没有答案