No se que estoy haciendo mal al añadir una nueva fila al jlist porque me los borra todos y se vuelve loco el JMenu
Les adjunto el código a ver si véis que esta fallando
Código:
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; public class MainClass implements ActionListener { private Vector<Vector<String>> data; private JFrame frame; private JPanel panel; private JList table; private JPopupMenu popupMenu; private JMenuItem deleteItem; private JButton addButton; static int selected = -1; protected void initUI() { frame = new JFrame(); panel = new JPanel(); data = new Vector<Vector<String>>(); for (int i = 0; i < 5; i++) { Vector<String> row = new Vector<String>(); row.add("aaaa " + (i + 1)); data.add(row); } table = new JList<Object>(data); popupMenu = new JPopupMenu(); deleteItem = new JMenuItem("Delete"); table.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if ( SwingUtilities.isLeftMouseButton( e ) ) { selected = table.getSelectedIndex(); } else if ( SwingUtilities.isRightMouseButton( e )) { selected = table.getSelectedIndex(); int rowNumber = table.getSelectedIndex(); System.out.println(rowNumber); ListSelectionModel model = table.getSelectionModel(); model.setSelectionInterval( rowNumber, rowNumber ); if (!model.isSelectionEmpty()) { selected = rowNumber; mostrarPopupMenu(e); frame.repaint(); } } } private void mostrarPopupMenu(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = table.getSelectedIndex(); System.out.println(index); data.remove(index); table.clearSelection(); frame.repaint(); } }); popupMenu.add(deleteItem); addButton=new JButton("add"); addButton.setBounds(300,250,100,30); addButton.addActionListener(this); panel.add(new JScrollPane(table), BorderLayout.CENTER); frame.add(addButton); frame.add(panel); frame.pack(); frame.setBounds(0,0,450,350); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()==addButton) { Vector<String> row = new Vector<String>(); data.add(row); frame.repaint(); } } public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { new MainClass().initUI(); } }; EventQueue.invokeLater(r); } }
Gracias de antemano
Un saludo!