【发布时间】:2021-06-02 09:11:05
【问题描述】:
我目前正在尝试开发一个桌面志愿者应用程序,该应用程序允许用户通过文本框输入名称,然后在 JList 的同一窗口中显示该名称。但是,目前我的代码没有显示我的面板/列表或我添加的滚动条。
我的代码如下。非常感谢任何帮助!
import javax.swing.*;
import java.awt.event.*;
public class StudentViewer implements ActionListener {
JFrame frame = new JFrame("View Students");
JPanel panel = new JPanel();
JButton button = new JButton();
JButton button2 = new JButton();
JTextField field = new JTextField("", 25);
DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>(model);
public StudentViewer() {
button = new JButton("Click to add to the list");
button.setFocusPainted(false);
button.addActionListener(this);
button2 = new JButton("New Window");
button2.setFocusPainted(false);
button2.addActionListener(this);
panel.add(field);
panel.add(button);
panel.add(button2);
list = new JList(model);
list.setFixedCellWidth(300);
list.setFixedCellHeight(50);
list.setLayoutOrientation(JList.VERTICAL);
// scroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// panel.add(scroll);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String text = field.getText();
model.addElement(text);
JOptionPane.showMessageDialog(frame, "Added to the list", "Done",
JOptionPane.INFORMATION_MESSAGE);
frame.dispose();
} else if (e.getSource() == button2) {
System.exit(0);
}
}
public static void main(String[] args) {
Runnable r = () -> {
new StudentViewer();
};
SwingUtilities.invokeLater(r);
}
}
【问题讨论】:
-
更新您的问题并在此处添加我们无法从图像中复制的代码!
-
阅读 How to Use Lists 上的 Swing 教程部分。
ListDemo示例代码完全符合您的要求。该代码还将向您展示如何更好地构建您的类以在Event Dispatch Thread (EDT)上创建 GUI。
标签: java swing user-interface textfield jlist