简体   繁体   中英

Add to JList and select element?

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);
        }

    }

//}

}

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

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