0

I need to have a box with a jlist and two buttons. One button will close the box and the other will bring up a text box the user can fill in to add an element to the jlist.

What I have so far:

import java.awt.FlowLayout;

import javax.swing.*;
public class Main {
public static void main(String[] args)
{
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame box = new JFrame("Course List");
    box.setSize(600,300);
    box.setLayout(new FlowLayout());
    box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    box.setVisible(true);       
    DefaultListModel listModel = new DefaultListModel();        
    JList list = new JList(listModel);
    list.setSelectedIndex(1);
    box.add(new JScrollPane(list));
    box.pack();     
    JButton button1 = new JButton("Add Course");        
    box.add(button1);
    HandlerClass handler = new HandlerClass();
    button1.addActionListener(handler); 
}
}




import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;


class HandlerClass implements ActionListener{   
        public void actionPerformed(ActionEvent e) {            
        String input;
        input = JOptionPane.showInputDialog(null, "Enter in course name");




    }       
}

My issue is I don't know how to pass "ListModel" or if that's even possible so that I can do something like listModel.addElement(input) and add the text from the text to the jlist.

EDIT:

So I don't know if this is the way it is supposed to be done but I just created an infinite loop in my main and some setters and getters in the handlerclass. It works but my not be the correct way to do it.

1 Answer 1

0

Generally speaking, don't (pass the list model), instead, use a JDialog or JOptionPane to collect the required details from the user and when they are closed, retrieve the details you need from them.

Take a look at How to make dialogs for more details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.