Como criar exception corretamente

1 resposta
L

alguém pode me ajudar?
através desse código estou querendo tratar uma exceção quando um item estiver selecionado, mas após excluir todos não consigo repetir a operação de remover.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class AvaliacaoList extends JFrame implements ListSelectionListener {
    
    private JList list;
    private DefaultListModel listModel;
    private JButton addButton, removeButton;
    private JTextField caixaNome;

    public AvaliacaoList() {
        super("AvaliacaoList");

        listModel = new DefaultListModel();
        listModel.addElement("Nome 1");
        listModel.addElement("Nome 2");
        
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);

        addButton = new JButton("Adiciona");
        addButton.setActionCommand("Adiciona");
        addButton.addActionListener(new addListener());

        removeButton = new JButton("Remove");
        removeButton.setActionCommand("Remove");
        removeButton.addActionListener(new removeListener());

        caixaNome = new JTextField(15);
        caixaNome.addActionListener(new addListener());
        caixaNome.setText("");

        JPanel buttonPane = new JPanel();
        buttonPane.add(caixaNome);
        buttonPane.add(addButton);
        buttonPane.add(removeButton);

        Container contentPane = getContentPane();
        contentPane.add(listScrollPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.SOUTH);
    }

    class removeListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            
           try{
               if (list.getSelectedIndex()>=0){
                
            listModel.remove(caixaNome.getSelectionStart());
                     }
           }
             catch(Exception erro){
        JOptionPane.showMessageDialog(null,"os dados não foram selecionados");
    }
             
        }
    }

   
    class addListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {

	          listModel.addElement(caixaNome.getText());
  // implementar código para adicionar um valor
            
        }
    }

    public void valueChanged(ListSelectionEvent e) {
        
    }

    public static void main(String args[]) {
        JFrame janela = new AvaliacaoList();
        janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        janela.setSize(400,300);
        janela.setVisible(true);
    }
}

1 Resposta

Marky.Vasconcelos

No seu caso, você deve fazer através do if mesmo:

if (list.getSelectedIndex()>=0){  
                  
            listModel.remove(caixaNome.getSelectionStart());  
                     }  else
        JOptionPane.showMessageDialog(null,"os dados não foram selecionados");

Pois uma exception não será gerada se a condição for resolvida como true.

Para tratar como exceção talvez você poderia remover o if(? > 0) e capturar um IndexOutOfBoundsException.

Criado 24 de setembro de 2013
Ultima resposta 25 de set. de 2013
Respostas 1
Participantes 2