当我向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);
}
}
答案 0 :(得分:3)
您只需使用add(0, object)
方法。
而不是listModel.addElement(name)
,listModel.add(0, name)
会在列表顶部添加名称。
对于JList的大小,您不应使用此边框,而是为JSCrollPane选择preferredSize:
package Gui;
...
import java.awt.Dimension;
public class GUI implements ActionListener {
...
public GUI(){
...
list = new JList(listModel);
JScrollPane listScrollPane = new JScrollPane(list);
listScrollPane.setPreferredSize(new Dimension(100, 240));
panel.add(listScrollPane);
...
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.add(0, name);
}
}
资源: