Java:Jswing:Jlist
当我向 Jlist 输入名称时,该名称会输出到列表的下半部分,如何使其到达名称设置在窗口顶部的位置
package Gui;
//import java.awt.BorderLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI implements ActionListener {
JButton button;
JTextField field;
JList list;
JTextField name1;
DefaultListModel listModel;
String name;
public GUI(){
listModel = new DefaultListModel();
listModel.addElement(null);
listModel.setSize(1);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
field = new JTextField("Enter Name", 10);
button = new JButton("Click");
list = new JList(listModel);
list.setBorder(BorderFactory.createEmptyBorder(120, 20, 20, 120));
JScrollPane listScrollPane = new JScrollPane(list);
panel.add(listScrollPane);
listScrollPane.setWheelScrollingEnabled(true);
panel.add(button);
panel.add(field);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.addElement(name);
}
}
When i input a name to the Jlist, the name gets outputted to the lower section of the list, how do i make it to where the name is set to the top of the window
package Gui;
//import java.awt.BorderLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI implements ActionListener {
JButton button;
JTextField field;
JList list;
JTextField name1;
DefaultListModel listModel;
String name;
public GUI(){
listModel = new DefaultListModel();
listModel.addElement(null);
listModel.setSize(1);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
field = new JTextField("Enter Name", 10);
button = new JButton("Click");
list = new JList(listModel);
list.setBorder(BorderFactory.createEmptyBorder(120, 20, 20, 120));
JScrollPane listScrollPane = new JScrollPane(list);
panel.add(listScrollPane);
listScrollPane.setWheelScrollingEnabled(true);
panel.add(button);
panel.add(field);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.addElement(name);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需使用
add(0, object)
方法即可。listModel.add(0, name)
会将名称添加到列表顶部,而不是listModel.addElement(name)
。对于 JList 的大小,您不应使用此边框,而应为 JSCrollPane 选择首选大小:
资源:
DefaultListModel.add(int, Object)
You can simply use the
add(0, object)
method.Instead of
listModel.addElement(name)
,listModel.add(0, name)
will add the name at the top of the List.For the size of the JList you shouldn't use this border but instead select a preferredSize for your JSCrollPane :
Resources :
DefaultListModel.add(int, Object)