import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
public class DynamicArray extends JFrame{
private JPanel contentPane;
private final JPanel panel = new JPanel();
//launch the application
public static void main(String[] args){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}catch(Throwable e){
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
DynamicArray frame = new DynamicArray();
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
//create the frame
public DynamicArray(){
setTitle("使用动态数组来保存水果名");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,337,269); //从(100,100)出现,大小为(337,269);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
contentPane.setLayout(new BorderLayout(0,0)); //采用边框布局
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane,BorderLayout.CENTER);
list = new JList();
scrollPane.setViewportView(list);
JPanel panel_1 = new JPanel();
scrollPane.setColumnHeaderView(panel_1);
JLabel label = new JLabel("水果");
panel_1.add(label);
textField = new JTextField();
panel_1.add(textField);
textField.setColumns(10);
panel.setPreferredSize(new Dimension(100,10));
contentPane.add(panel,BorderLayout.EAST);
panel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
JButton button = new JButton("增加水果");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_button_actionPerformed(e);
}
});
panel.add(button);
JButton button_1 = new JButton("删除水果");
button_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_button_1_actionPerformed(e);
}
});
panel.add(button_1);
}
private ArrayList<String> arrayList = new ArrayList<String>();
private JTextField textField;
private JList list;
protected void do_button_actionPerformed(ActionEvent e){
textField.requestFocusInWindow();
textField.selectAll();
String text = textField.getText();
if(text.isEmpty())
return;
arrayList.add(text);
replaceModel(); //把数组集合中的内容显示到界面列表控件中
}
protected void do_button_1_actionPerformed(ActionEvent e){
Object value = list.getSelectedValue();
arrayList.remove(value);
replaceModel(); //把数组集合中内容显示到界面列表控件中
}
private void replaceModel(){
list.setModel(new AbstractListModel(){
@Override
public int getSize(){
return arrayList.size();
}
@Override
public Object getElementAt(int index){
return arrayList.get(index);
}
});
}
}
Java实例——动态数组的使用
最新推荐文章于 2024-07-12 21:58:44 发布