gpt4 book ai didi

java - 如何通过 JOptionPane 修改/添加字符串到 JList

转载 作者:行者123 更新时间:2023-12-02 04:06:03 26 4
gpt4 key购买 nike

我需要帮助通过 JOptionPane 将字符串添加到 JList,这是迄今为止我的代码:

import javax.swing.JPanel; 
import java.awt.Dimension;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.ArrayList;

/**
* Write a description of class Front_Menu here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Front_Menu
{
//Fields
private JFrame frame;
private JButton button1;
private JList list;
private JScrollPane listScroller;
private JPanel panel1;
private String title;

/**
* Construct the GUI
*/

public void go()
{
frame = new JFrame("Flashcard Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Dimension frameSize = new Dimension(400, 300);
frame.getContentPane().setPreferredSize(frameSize);
frame.getContentPane().setBackground(Color.WHITE);

button1 = new JButton("New Set");
button1.addActionListener(new ButtonListener());
frame.getContentPane().add(BorderLayout.SOUTH, button1);

String[] titleArray ={"Biology Set", title};
list = new JList(titleArray);

listScroller = new JScrollPane(list);
frame.getContentPane().add(BorderLayout.CENTER, listScroller);

frame.pack();
frame.setVisible(true);
}

/**
* Main Method
*/

public static void main(String[] args)
{
Front_Menu front_menu = new Front_Menu();
front_menu.go();
}

/**
* Inner class for the Button Listener
*/

private class ButtonListener implements ActionListener
{
/**
* Override the actionPerformed Method
*/

public void actionPerformed(ActionEvent event)
{
title = JOptionPane.showInputDialog(
null,
"What is the title of your new set? "
);
}
}
}

因此,在这个程序中,我有一个 JList,我想通过 JOptionPane 添加另一个字符串来修改它。它可以编译,但是当我单击按钮时它不会显示。

提前致谢!

最佳答案

运行代码后,您的 JOptionPane 弹出窗口对我来说很好。

要回答您的其他问题,请首先使用 DefaultListModel,它是可变的(允许您添加新元素)

public class Front_Menu {
//Fields

//...
private DefaultListModel model;
private JList list;
//...

/**
* Construct the GUI
*/
public void go() {
//...
String[] titleArray = {"Biology Set", title};
model = new DefaultListModel();
for (String title : titleArray) {
model.addElement(title);
}
list = new JList(model);

然后在您的 ActionListener 中,将输入添加到模型中...

@Override
public void actionPerformed(ActionEvent event) {
title = JOptionPane.showInputDialog(
null,
"What is the title of your new set? "
);
if (title != null) {
model.addElement(title);
}
}

看看How to Use Lists了解更多详情

关于java - 如何通过 JOptionPane 修改/添加字符串到 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com