添加到JList并选择元素?

时间:2012-01-17 20:22:00

标签: java swing jlist actionlistener

我需要一些帮助才能将元素添加到JList以及如何选择元素whith事件。

这是我的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));

这是我处理不同按钮的actionlistener的一部分。它在这里我想使用model.add(“Name”);机器人我在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);
}
}
}

然后我会预先帮助我如何选择JList中的元素?我应该对类或FrameHandler对象使用实现ActionListener吗?谢谢!

编辑:我无法解决的主要问题是JList在construcor中,当我使用model.add(“name”)时;它在构造函数中工作,但是当我想在构造函数外添加一些东西时,它不起作用?我已多次阅读本教程,但无法找到任何帮助。

编辑2:完整代码。可能有些超出范围的问题?

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 个答案:

答案 0 :(得分:1)

你很幸运我心情很好。这是一个非常基本的示例,与您提供的代码相匹配。在文本字段中键入内容,按Enter按钮并观察列表填充。

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

修改

根据您的完整代码,您必须在列表中添加GUI4EX类中的字段,类似于buttonNewCustomer字段

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

这将确保您可以访问model方法中的actionPerformed。但是,如果你无法弄清楚这个基本的东西,你不应该创建GUI,而是阅读基本的Java语法和OO原则