添加到 JList 并选择元素?

发布于 2024-12-27 18:31:40 字数 7245 浏览 0 评论 0原文

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

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

这是处理不同按钮的动作侦听器的一部分。在这里我想使用 model.add("Name"); bot 我在 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 中的元素?我应该使用类的实现 ActionListener 还是 FrameHandler 对象?谢谢!

编辑:我无法解决的主要问题是 JList 位于构造函数内部,并且当我使用 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);
        }

    }

//}

}

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

    }

//}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

翻身的咸鱼 2025-01-03 18:31:40

你很幸运我心情很好。这是一个非常基本的示例,与您提供的代码相匹配。在文本字段中输入内容,点击 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
  }
}

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文