Java tutorial
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; public class Main { static int N = 12; JDialog dlg = new JDialog(); DefaultListModel model = new DefaultListModel(); JList list = new JList(model); JScrollPane sp = new JScrollPane(list); int count; public Main() { list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); JPanel panel = new JPanel(); panel.add(new JButton(new AbstractAction("Add") { @Override public void actionPerformed(ActionEvent e) { append(); if (count <= N) { list.setVisibleRowCount(count); dlg.pack(); } } })); panel.add(new JButton(new AbstractAction("Remove") { @Override public void actionPerformed(ActionEvent e) { int itemNo = list.getSelectedIndex(); if (itemNo > -1) { removeActionPerformed(e, itemNo); } } })); for (int i = 0; i < N - 2; i++) { this.append(); } list.setVisibleRowCount(N - 2); dlg.add(sp, BorderLayout.CENTER); dlg.add(panel, BorderLayout.SOUTH); dlg.pack(); dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dlg.setVisible(true); } private void removeActionPerformed(ActionEvent e, int itemNo) { model = (DefaultListModel) list.getModel(); if (model.size() > 0) { if (itemNo > -1) { model.remove(itemNo); } } } private void append() { model.addElement("String " + String.valueOf(++count)); list.ensureIndexIsVisible(count - 1); } public static void main(String[] a_args) { Main pd = new Main(); } }