Salut à tous,

J'ai un problème avec un lien hypertexte sur une JTable, le code fonctionne sur un simple label mais pas avec ma JTable.
Voici ma classe complète fonctionnel :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
 
package table;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
 
public class TestLinkPerso extends JFrame
{
	private static final long serialVersionUID = 1L;
 
	private static final String LABEL_TEXT = "For further information visit:";
	private static String A_VALID_LINK;
	private static final String A_HREF = "<a href=\"";
	private static final String HREF_CLOSED = "\">";
	private static final String HREF_END = "</a>";
	private static final String HTML = "<html>";
	private static final String HTML_END = "</html>";
 
	private JTable table;
	private JScrollPane elevator;
 
	private JPopupMenu popupMenu;
	private JMenuItem menuItemCopyAll;
	private JMenuItem menuItemRemoveAll;
 
	public TestLinkPerso() {
		this.setTitle("HTML link via a JLabel");
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 
		table = new JTable();
		final DefaultTableModel model = (DefaultTableModel) table.getModel();
		model.addColumn("Links");
		/*table.getColumnModel().getColumn(0)
				.setCellRenderer(new CustomTableCellRenderer(label));
		*/
		table.setAutoCreateRowSorter(true);
		table.setEnabled(false);
		//table.setBackground(Color.lightGray);
		//table.setGridColor(Color.lightGray);
		table.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		table.getSelectionModel().clearSelection();
		// constructs the popupMenu
		popupMenu = new JPopupMenu();
		menuItemCopyAll = new JMenuItem("Copy All Rows");
		menuItemRemoveAll = new JMenuItem("Remove All Rows");
 
		//menuItemCopyAll.addActionListener(new Events());
		menuItemCopyAll.setToolTipText("Click to copy all lines");
 
		//menuItemRemoveAll.addActionListener(new Events());
		menuItemRemoveAll.setToolTipText("Click to remove all lines");
 
		popupMenu.add(this.menuItemCopyAll);
		popupMenu.add(this.menuItemRemoveAll);
 
        // sets the popup menu for the table
		table.setComponentPopupMenu(this.popupMenu); 
		//table.addMouseListener(new MouseReleased(table));
 
		final Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
 
		JPanel panNorth = new JPanel();
		final JPanel panSouth = new JPanel();
 
		final JLabel label = new JLabel(LABEL_TEXT);
		panNorth.add(label);
 
		final JTextField text = new JTextField(10);
		panNorth.add(text);
 
		JButton button = new JButton("Show Link");
		button.addActionListener(new ActionListener()
		{	
			@Override
			public void actionPerformed(ActionEvent e)
			{	
				if (!text.getText().isEmpty())
				{
					A_VALID_LINK = "http://"+ text.getText();
					JLabel link = new JLabel();
					link.setText(A_VALID_LINK);
					link.setToolTipText("Click to go to : "+ A_VALID_LINK);
					if (isBrowsingSupported())
					{
						JPanel panel = createPane(link, new LinkMouseListener());
						panSouth.add(panel);
					}
					else if (!isBrowsingSupported())
					{
						JOptionPane.showMessageDialog(null,"This links is unsupported");
					}
				}
				contentPane.add(panSouth, BorderLayout.SOUTH);
				pack();
			}
		});
		contentPane.add(panNorth, BorderLayout.NORTH);
		contentPane.add(button);
 
		pack();
	}
 
	private JPanel createPane(JLabel label, MouseListener ml)
	{
		DefaultTableModel model = (DefaultTableModel) table.getModel();
 
        assert ml != null;
		label.setText(htmlIfy(linkIfy(label.getText())));
		label.setCursor(new Cursor(Cursor.HAND_CURSOR));
		label.addMouseListener(ml);
		//"<a href=\"http://www.google.fr\">Url</a>"
		model.insertRow(0, new Object[]{label.getText()});
		table.repaint();
		// NOTE 2: Using a custom cell renderer
        table.setDefaultRenderer(String.class, new CustomTableCellRenderer(label));
 
        // Add into a scrollpane / regular pane
        elevator = new JScrollPane(table,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		elevator.getViewport().setBackground(Color.WHITE);
        JPanel panel = new JPanel();
        panel.add(elevator);
 
        return panel;
    }
 
	private static boolean isBrowsingSupported() {
		if (!Desktop.isDesktopSupported()) {
			return false;
		}
		boolean result = false;
		Desktop desktop = Desktop.getDesktop();
		if (desktop.isSupported(Desktop.Action.BROWSE)) {
			result = true;
		}
		return result;
	}
 
	private static class LinkMouseListener extends MouseAdapter
	{
		@Override
		public void mouseClicked(MouseEvent evt)
		{
			JLabel l = (JLabel) evt.getSource();
			try {
				URI uri = new URI(TestLinkPerso.getPlainLink(l.getText()));
				(new LinkRunner(uri)).execute();
			} catch (URISyntaxException use) {
				throw new AssertionError(use + ": " + l.getText()); // NOI18N
			}
		}
	}
 
	private static class LinkRunner extends SwingWorker<Void, Void> {
 
		private final URI uri;
 
		private LinkRunner(URI u)
		{
			if (u == null) {
				throw new NullPointerException();
			}
			uri = u;
		}
 
		@Override
		protected Void doInBackground() throws Exception
		{
			Desktop desktop = Desktop.getDesktop();
			desktop.browse(uri);
			return null;
		}
 
		@Override
		protected void done()
		{
			try {
				get();
			} catch (ExecutionException ee) {
				handleException(uri, ee);
			} catch (InterruptedException ie) {
				handleException(uri, ie);
			}
		}
 
		private static void handleException(URI u, Exception e)
		{
			JOptionPane
					.showMessageDialog(
							null,
							"Sorry, a problem occurred while trying to open this link in your system's standard browser.",
							"A problem occured", JOptionPane.ERROR_MESSAGE);
		}
	}
 
	private static String getPlainLink(String s) {
		return s.substring(s.indexOf(A_HREF) + A_HREF.length(),
				s.indexOf(HREF_CLOSED));
	}
 
	// WARNING
	// This method requires that s is a plain string that requires
	// no further escaping
	private static String linkIfy(String s) {
		return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
	}
 
	// WARNING
	// This method requires that s is a plain string that requires
	// no further escaping
	private static String htmlIfy(String s) {
		return HTML.concat(s).concat(HTML_END);
	}
 
	/**
         * @param args
         *            the command line arguments
         */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
 
			@Override
			public void run() {
				new TestLinkPerso().setVisible(true);
			}
		});
	}
}
N'hésitez pas pour les idée de customisation du code.
Et la classe CustomTableCellRenderer :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 
package table;
 
import java.awt.Color;
import java.awt.Component;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
 
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
 
/**
 * <h1>Custom table cell</h1>
 * <p>Change of color of messages info</p>
 * 
 * @author t0163126
 */
public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(TableLabel.class
			.getName());
	private JLabel label;
 
	public CustomTableCellRenderer(JLabel label) {
		this.label = label;
	}
 
	@Override
	protected void setValue(Object value)
	{
		super.setValue(value);
		String val = (String) value; 
		if (val.contains(".fr"))
		{
			this.setForeground(Color.blue);
		}
		else if (val.contains(".com"))
		{
			this.setForeground(Color.green);
		}
	}
 
	public Component getTableCellRendererComponent(JTable table,
			Object value, boolean isSelected, boolean hasFocus, int row,
            int column)
	{
        LOGGER.info("Rendering (" + row + "," + column + ") - "
                + value.toString() + " as a label");
        label = new JLabel(value.toString());
        try {
            // BTW: Ensure you are allowed to use the icons -
            // This page seems to allow their use;
            // http://www.iconarchive.com/show/hat-icons-by-rob-sanders/Hat-cowboy-black-icon.html
            label.setIcon(new ImageIcon(new URL(
                    "http://www.iconarchive.com/icons/rob-sanders/hat/32/Hat-cowboy-black-icon.png")));
        } catch (MalformedURLException mfe) {
            LOGGER.severe("Aargh I cannot find the icon");
        }
        return label;
    }
}
Merci