我将列表项添加到 JList
numbersList.add("first example");
numbersList.add("second example");
numbersList.add("third example");
当我向字段添加新文本或数字时,它将被添加到列表中并显示在 JList 中。这是我的代码,我只想让当我按下按钮时,新元素出现在 JListfullList
中的列表中,该列表numberList
已从 textfield 添加numberTxtFld
。
ps 我已经删除了一些不必要的代码。
package average;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
public class Surface extends JLabel{
private JTextField numberTxtFld;
private JLabel topLabel;
private JLabel sumLabel;
private JLabel avgLabel;
private JLabel maxLabel;
private JLabel minLabel;
private JLabel amountLabel;
private JLabel listLabel;
private JLabel resultLabel;
private JLabel sumAnswerFld;
private JLabel avgAnswerFld;
private JLabel maxAnswerFld;
private JLabel minAnswerFld;
private JLabel amountAnswerFld;
private JLabel fullListLabel;
private JList fullList;
final List<String> numbersList = new ArrayList<String>();
private JButton submitBtn;
private JButton closeBtn;
private JPanel panel;
private int arrayIndex = 0;// used for components adding into array
public Surface(){
panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setSize(300, 300);
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
topLabel = new JLabel("Enter your number and push submit");
gbc.gridwidth = 3;
gbc.gridx = 0; // column
gbc.gridy = 0; // row
panel.add(topLabel, gbc);
gbc.gridwidth = 1; // setting grid column with to default
fullListLabel = new JLabel("Full list");
gbc.gridx = 2;
gbc.gridy = 1;
panel.add(fullListLabel, gbc);
amountLabel = new JLabel("Amount");
gbc.gridx = 0;
gbc.gridy = 5;
panel.add(amountLabel, gbc);
amountAnswerFld = new JLabel("0");
gbc.gridx = 1;
gbc.gridy = 5;
panel.add(amountAnswerFld, gbc);
numberTxtFld = new JTextField();
numberTxtFld.setColumns(10);
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(numberTxtFld, gbc);
submitBtn = new JButton("Submit");
gbc.gridx = 1;
gbc.gridy = 1;
submitBtn.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
String text = numberTxtFld.getText();
numbersList.add(text);
}
}
);
panel.add(submitBtn, gbc);
numbersList.add("first example");
numbersList.add("second example");
numbersList.add("third example");
fullList = new JList(numbersList.toArray());
fullList.setVisibleRowCount(6);
fullList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
gbc.gridheight = 6;
gbc.gridx = 2;
gbc.gridy = 2;
panel.add(new JScrollPane(fullList), gbc);
gbc.gridheight = 1; // setting grid column with to default
add(panel);
}
}