How to make a scrollable JList to add details got from a JOptionPane

Haxed picture Haxed · Jul 8, 2010 · Viewed 23.3k times · Source

I want to repeatedly take input from the user(probably using a button) via a JOptionPane(already done) and store the details in something(how about a dynamic object array) and display this information as a list in a scrollable JList.


MY CODE


import java.awt.GridLayout;
import javax.swing.*;

class Flight {



public static void main(String[] args) {

    //Panel
    JPanel panel = new JPanel(new GridLayout(7, 2,20, 20));

    //Add textfields here
    JTextField txtflightno = new JTextField(8);
    JTextField txtmechanicalstatus = new JTextField(8);
    JTextField txtmedicalstatus = new JTextField(8);
    JTextField txtfuellevel = new JTextField(8);
    JTextField txtweathercondition = new JTextField(8);
    JTextField txtfrequency = new JTextField(8);
    JTextField txtflightpath = new JTextField(8);






    //Add labels here
    JLabel lblflightno = new JLabel("Flight No : ");
    JLabel lblmechanicalstatus = new JLabel("Mechanical Status:");
    JLabel lblmedicalstatus = new JLabel("Medical Status:");
    JLabel lblfuellevel = new JLabel("Fuel Level:");
    JLabel lblweathercondition = new JLabel("Weather Condition:");
    JLabel lblfrequency = new JLabel("Frequency:");
    JLabel lblflightpath = new JLabel("Flight Path:");





    //Adding flightno to panel
    panel.add(lblflightno);
    panel.add(txtflightno);

    //Adding mechanicalstatus to the panel
    panel.add(lblmechanicalstatus);
    panel.add(txtmechanicalstatus);

    //Adding medicalstatus to the panel
    panel.add(lblmedicalstatus);
    panel.add(txtmedicalstatus);

    //Adding fuellevel to the panel
    panel.add(lblfuellevel);
    panel.add(txtfuellevel);

    //Adding weathercondition to the panel
    panel.add(lblweathercondition);
    panel.add(txtweathercondition);

    //Adding frequency to the panel
    panel.add(lblfrequency);
    panel.add(txtfrequency);

    //Adding flightpath to the panel
    panel.add(lblflightpath);
    panel.add(txtflightpath);


    panel.setBounds(0, 0, 800, 600);




   int result = JOptionPane.showConfirmDialog(null, panel, "Flight Details",
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION) {

    }
}
}

How must I do the storing of the plane details ? How must I implement a scrollable JList ? Any suggestions.

Many Thanks

Answer

trashgod picture trashgod · Jul 8, 2010

As discussed in How to Use Lists, JList uses a list model as the source of data it displays. Just add your data to a DefaultListModel, and use it to construct your list.

DefaultListModel dlm = new DefaultListModel();
// add data
JList list = new JList(dlm);
panel.add(new JScrollPane(list));