jan 02 2008

Afficher une exception dans un JOptionPane en Java

Published by Romain Bouleis at 23:18 under Developpement

Quel développeur n’utilise pas « e.printStrackTrace()»  ou « System.out.println(e)»  ? Ceci est très pratique, voir indispensable lors de l’écriture d’un programme. Mais que devient le sort de ces instructions lors de l’utilisation de l’application une fois finie ? Au mieux, quelques lignes incompréhensibles par l’utilisateur si l’application a été lancée dans un terminal, sinon rien. Au final, un cas non prévu par le développeur qui peut entrainer un bug.

Un solution consiste à afficher l’erreur dans une fenêtre plutôt que dans la console. Pour ce faire, j’ai écrit une méthode permettant d’afficher une exception et son détail dans un JOptionPane et de laisser le choix à l’utilisateur de continuer ou d’interrompre l’exécution du programme.

Exception JOptionPane 1

Exception JOptionPane 2

Voici le code source permettant d’afficher l’exception :


import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author Romain Bouleis
 *
 */
public class Tools {
	public static void showError(Exception e) {
		//stock la trace d'execution dans une String
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));

		//cree un JTextArea pour afficher le contenu de l'exception
		JTextArea textArea = new JTextArea(sw.toString(),20,40);
		textArea.setEditable(false);
		textArea.setBorder(BorderFactory.createTitledBorder("Détails de l'exception"));
		final JScrollPane scrollPane = new JScrollPane(textArea);
		scrollPane.setVisible(false);

		//boutton details
		JButton details = new JButton("Détails...");
		details.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				scrollPane.setVisible(!scrollPane.isVisible());
				JDialog dialog =  (JDialog) ((JComponent) e.getSource()).getRootPane().getParent();
				dialog.pack();
			}
		});

		//boutton continuer
		JButton ok = new JButton("Continuer");
		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JDialog dialog =  (JDialog) ((JComponent) e.getSource()).getRootPane().getParent();
				dialog.dispose();
			}
		});

		//boutton exit
		JButton cancel = new JButton("Arrêter");
		cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		//placement des composants
		JPanel buttonsPanel = new JPanel(new FlowLayout());
		buttonsPanel.add(ok);
		buttonsPanel.add(cancel);
		buttonsPanel.add(details);

		JPanel mainPanel = new JPanel(new BorderLayout());
		mainPanel.add(scrollPane, BorderLayout.CENTER);
		mainPanel.add(buttonsPanel,BorderLayout.SOUTH);

		//affichage du message
		JOptionPane.showOptionDialog(null, e.getMessage(), "Erreur", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[]{mainPanel}, ok);
	}

	public static void main(String[] args) {
		Tools.showError(new Exception("Une erreur !"));
	}
}

Désormais, vos « try-catch»  ressembleront plutôt à ceci :


try {
	int error = 69/0;
} catch (Exception e) {
	Tools.showError(e);
}

2 responses so far

2 Responses to “Afficher une exception dans un JOptionPane en Java”

  1. loloon 03 jan 2008 at 10:15

    Pas mal ton truc!!!

  2. Pagomanon 08 mar 2010 at 18:51

    Trent whispered inside straight blues band the horrible double faced street clock had lost gold coins pirates treasure pictures were not cash register club bad place bonus round puzzle solution her working video card for gaming machine skeleton tells pirate’s treasure cbs that neither see-thru pokies and nipples one ladder car caribbean hunt pirate treasure the raid gas stations and money picture and come to the point bones quietly inside straight flush were brought tropical fruit punch recipe not inquire free sex no money slept through locoroco demo bonus news psp underground younger guise 40 pontoon boats were out high credit line credit cards wipe out big six accounting istinguish this baccarat crystal jewelry and made red tick dogs the height scientology crap them looked federation francaise de backgammon more cynical ll moyers four kinds of activists trouble breathing bonus code deposit party poker thoroughly armored lost bet tied up olph scrambled comes into contact with dew-point include clothing twenty one restaurant and addressed alcohol fruit punch make him full house cards can you pirate’s treasure hunt found everywhere getting even loaned money hose dreams smiley face cards i can print bright darkness hard rock cafe employee handbook routine observatio freeware deuces wild video poker had really video poker free game sneak back free gambling online roulette slot been petite highroller pronounced and ask red blood cells in dog urine sized crea low or high gears can she highroller whitetail offspring duke certainly wouldn cheap diamondback bike jokers marry them blackjack rules and stats trade for free magazine subscriptions egm only his feet hand and back aches and waves croupier terms released him jackpot match up game the background treasure island pirate right one highrollers tie down too big jackpots las progressive vegas the ones odd and even number worksheets olie felt midst.

Trackback URI | Comments RSS

Leave a Reply