简体   繁体   中英

Java - Why i can't see my list in JFrame?

I can't see my list under the MenuBar, it should show me a list (playing cards) What i should do ?

图片

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

public class Joc extends JFrame{

    JMenuBar mb = new JMenuBar();
    JMenu m1 = new JMenu("Optiuni");
    JMenuItem mi1 = new JMenuItem("Amesteca");
    JMenuItem mi2 = new JMenuItem ("Inchide");

    DefaultListModel<Card> model = new DefaultListModel<Card>();
    JList<Card> list = new JList<Card>();
    JScrollPane jsp = new JScrollPane(list);

    Deck d = new Deck ();

    public Joc() {
        super("Joc");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setJMenuBar(mb);

        add(jsp);

        mb.add(m1);
        m1.add(mi1);
        m1.add(mi2);

        ArrayList<Card> carti = d.getCards();
        for (Card c: carti) {
            model.addElement(c);
        }

        mi1.addActionListener (
            new ActionListener() {
                    public void actionPerformed (ActionEvent ev) {
                        d.amesteca();
                        ArrayList<Card> carti = d.getCards();
                        model.clear();
                            for (Card c: carti) {
                                    model.addElement(c);
                        }
                   }
            }
        ); 

        mi2.addActionListener (
            new ActionListener() {
                    public void actionPerformed (ActionEvent ev) {
                        System.exit(0);
                   }
            }
        ); 


        setSize(500,500);
        setVisible(true);

    }

    public static void main (String [] args) {
        new Joc();
    }

}

Can anyone help me with this problem ? I'm new to java and coding , i just play around with the code... but i want results

I don't see where you add the model to the list, so the JList has an empty model with nothing to display

Create the JList using the model:

DefaultListModel<Card> model = new DefaultListModel<Card>();
//JList<Card> list = new JList<Card>();
JList<Card> list = new JList<Card>(model);

Also, you should be using:

list.setVisibleRowCount(...);

This will allow the JList to determine its own preferred size and you can use frame.pack() instead of frame.setSize(...).

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