Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7172065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T15:32:23+00:00 2026-05-28T15:32:23+00:00

I need some help to be able to add element to a JList and

  • 0

I need some help to be able to add element to a JList and how to select element whith event.

This is my JList:

DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));

This is part of my actionlistener that handle different buttons. It’s here I want to use model.add(“Name”); bot I get a red underline in Eclipse!?

public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number); 

if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement(name);
}
}
}

Then I would preciate some help how I should select the element inside the JList? Should I use implements ActionListener to the class or a FrameHandler object? Thanks!

EDIT: My main problem that I can’t solve is that the JList is inside the construcor and when I use model.add(“name”); inside the constructor it works, but it’s not working when I want to add something outside the constructor? I have read the tutorial several times, but can’t find any help for this.

EDIT 2: The completet code. Probably some out of scope problem?

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

public class GUI4EX extends JFrame implements ActionListener{

private JButton buttonNewCustomer, buttonTerminate, buttonAddNewName, buttonAddNewSavingsAccount, buttonAddNewCreditAccount;
private JLabel textLabelName, textLabelPersonalNumber, textLabelNewName;
private JTextField textInputName, textInputPersonalNumber, textInputNewName;
private JPanel panelNewCustomer, panelQuit, panelNewAccount, panelChangeName, panelSelectCustomer;

private boolean statusButtonNewCustomer = true;
private boolean statusButton2 = true;
private boolean statusButtonAddNewName = true;

private String title = "Bank ";

// Create a customHandler object
CustomHandler customHandler = new CustomHandler();

// Main method to start program
public static void main(String[] args){
    GUI4EX frame = new GUI4EX();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(3);
}

// Cunstructor
public GUI4EX(){
    // Create window
    setTitle(title);
    setSize(450,500);
    setLocation(400,100);
    setResizable(false);

    // Set layout to boxlayout
    Container container = getContentPane( );
    setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));

    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    JScrollPane listScroller = new JScrollPane(list);
    listScroller.setPreferredSize(new Dimension(430, 80));


    model.addElement("test");
    model.addElement("test");
    model.addElement("test");
    model.addElement("test");
    model.addElement("test");
    model.addElement("test");

    // Create jpanels
    panelNewCustomer = new JPanel();
    panelQuit = new JPanel();
    panelNewAccount = new JPanel();
    panelChangeName = new JPanel();
    panelSelectCustomer = new JPanel();

    // Create and add components - buttons
    buttonNewCustomer = new JButton("OK");
    buttonTerminate = new JButton("Avsluta");
    buttonAddNewName = new JButton("OK");
    buttonAddNewSavingsAccount = new JButton("Sparkonto");
    buttonAddNewCreditAccount = new JButton("Kreditkonto");

    // Create and add components - labels
    textLabelName = new JLabel("Namn");
    textLabelPersonalNumber = new JLabel("Personnummer");
    textLabelNewName = new JLabel("Nytt namn");
    //add(textLabel1);

    // Create and add components - textfields
    textInputName = new JTextField("");
    textInputPersonalNumber = new JTextField("");
    textInputName.setColumns(10);
    textInputPersonalNumber.setColumns(10);
    textInputNewName = new JTextField();
    textInputNewName.setColumns(20);

    // Add components to panel new customer
    panelNewCustomer.add(textLabelName);
    panelNewCustomer.add(textInputName);
    panelNewCustomer.add(textLabelPersonalNumber);
    panelNewCustomer.add(textInputPersonalNumber);
    panelNewCustomer.add(buttonNewCustomer);

    // Add components to panel to select customer
    panelSelectCustomer.add(listScroller);

    // Add components to panel new name
    panelChangeName.add(textLabelNewName);
    panelChangeName.add(textInputNewName);
    panelChangeName.add(buttonAddNewName);

    // Add components to panel new accounts
    panelNewAccount.add(buttonAddNewSavingsAccount);
    panelNewAccount.add(buttonAddNewCreditAccount);

    // Add components to panel quit
    panelQuit.add(buttonTerminate);

    // Set borders to jpanels
    panelNewCustomer.setBorder(BorderFactory.createTitledBorder("Skapa ny kund"));
    panelChangeName.setBorder(BorderFactory.createTitledBorder("Ändra namn"));
    panelNewAccount.setBorder(BorderFactory.createTitledBorder("Skapa nytt konto"));
    panelQuit.setBorder(BorderFactory.createTitledBorder("Avsluta programmet"));
    panelSelectCustomer.setBorder(BorderFactory.createTitledBorder("Välj kund"));

    // Add panels to window
    add(panelNewCustomer);
    add(panelSelectCustomer);
    add(panelChangeName);
    add(panelNewAccount);
    add(panelQuit);

    // Listener
    // FrameHandler handler = new FrameHandler();

    // Add listener to components
    //button1.addActionListener(handler);
    buttonNewCustomer.addActionListener(this);
    buttonAddNewName.addActionListener(this);
    buttonAddNewSavingsAccount.addActionListener(this);
    buttonAddNewCreditAccount.addActionListener(this);
    buttonTerminate.addActionListener(this);
}


//private class FrameHandler implements ActionListener{

    public void actionPerformed(ActionEvent event){
        // New customer
        if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
        {
            String name = textInputName.getText();
            String number = textInputPersonalNumber.getText();
            boolean checkCustomerExist = customHandler.findCustomer(name, number); // Check if customer exist

            if(!checkCustomerExist) // If not true add new customer
            {
                customHandler.addCustomer(name, number); // Call method to add name
                setTitle(title + "Kund: " + name); // Set new title
                model.addElement("name");
            }
        }

        // Change name
        if(event.getSource() == buttonAddNewName && statusButtonAddNewName)
        {
            String newName = textInputNewName.getText();
            customHandler.changeName(newName); // call method to change name
            setTitle(title + "Kund: " + newName);
        }

        // Create new savings account
        if(event.getSource() == buttonAddNewSavingsAccount)
        {
            customHandler.CreateNewSavingsAccount();    
        }

        // Create new credit account
        if(event.getSource() == buttonAddNewCreditAccount)
        {
            customHandler.CreateNewCreditAccount();
        }

        // Terminate program
        if(event.getSource()==buttonTerminate && statusButton2)
        {
            System.exit(3);
        }

    }

//}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T15:32:24+00:00Added an answer on May 28, 2026 at 3:32 pm

    You are lucky I am in a good mood. Here a very basic example, matching the code you provided. Type something in the textfield, hit the enter button and watch the list get populated.

    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JTextField;
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class AddToJListDemo {
    
      private static JFrame createGUI(){
        JFrame frame = new JFrame(  );
    
        final DefaultListModel model = new DefaultListModel();
        JList list = new JList( model );
    
        final JTextField input = new JTextField( 10 );
        input.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent aActionEvent ) {
            String text = input.getText();
            if ( text.length() > 0 ) {
              model.addElement( text );
              input.setText( "" );
            }
          }
        } );
    
        frame.add( list, BorderLayout.CENTER );
        frame.add( input, BorderLayout.SOUTH );
    
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        return frame;
      }
    
      public static void main( String[] args ) {
        EventQueue.invokeLater( new Runnable() {
          public void run() {
            JFrame frame = createGUI();
            frame.setSize( 200,200 );
            frame.setVisible( true );
          }
        } );
      }
    }
    

    Edit

    Based on your full code, you must make the list a field in your GUI4EX class, similar to for example the buttonNewCustomer field

    public class GUI4EX extends JFrame implements ActionListener{
      //... all other field
      DefaultListModel model;
    
      //constructor
      public GUI4EX(){
        //all other code
        //DefaultListModel model = new DefaultListModel(); instantiate the field instead
        model = new DefaultListModel();
        JList list = new JList(model);
        //rest of your code
      }
    }
    

    This will make sure you can access the model in the actionPerformed method. But if you cannot figure out something this basic, you should not be creating GUIs but reading up on basic Java syntax and OO principles

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Need some help to solve this. I have a gridview and inside the gridview
Need some help with this problem in implementing with XSLT, I had already implemented
Need some help gathering thoughts on this issue. Our team is moving ahead with
Need some help assigning a mouseover event to display some icons that start out
Need some help about with Memcache. I have created a class and want to
Need some help, please. I have a line of horizontal thumbnails loaded as ONE
Need some help from javascript gurus. I have one page where http://www.google.com/finance/converter is embedded
I need some help from the shell-script gurus out there. I have a .txt
I need some help regarding algorithm for randomness. So Problem is. There are 50
I need some help calculating Pi. I am trying to write a python program

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.