|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
[JAVA] Aprire file tramite JTable
Ho una JTable che contiene varie informazioni, tra cui il path di un file. vorrei che cliccando sulla cella con il nome del file mi apra in automatico il file associato.
Probabilmente dovrò ridefinire il CellRender, ma mi chiedevo, è possibile farlo per una singola colonna? Oppure posso aggiungere un listener che in base alla id della colonna mi riconosce la colonna giusta e mi preleva il file?
__________________
My gaming placement |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
|
Puoi farlo per la singola colonna.
Se 'table' è la tua JTable e 'N' è l'indice (nel modello della tablella) della colonna, con: Codice:
TableColumnModel column = table.getColumnModel().getColumn(N); A quel punto, se 'myRenderer' è la tua implementazione di TableCellRenderer, è sufficiente invocare: Codice:
column.setCellRenderer(myRenderer); Codice:
column.setCellEditor(myEditor); Per quanto riguarda il tuo problema: non ho capito bene che cosa vorresti fare.
__________________
As long as you are basically literate in programming, you should be able to express any logical relationship you understand. If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it. (Chris Crawford) Ultima modifica di banryu79 : 22-05-2012 alle 09:39. |
|
|
|
|
|
#3 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
l'ultima colonna contiene i file "associati" a tutto quello che c'è precedentemente. in pratica vorrei metterci un pulsante che quando ci clicco sopra lo apre in automatico.
grazie per il resto.
__________________
My gaming placement |
|
|
|
|
|
#4 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
in pratica questo
http://www.java2s.com/Tutorial/Java/...CellEditor.htm mi era sfuggito alla prima googlata
__________________
My gaming placement |
|
|
|
|
|
#5 | |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
Quote:
mentre per il codice postato da te "non funziona", nel senso che non mi riconosce quei metodi Codice:
column.setCellEditor(myEditor); column.setCellRenderer(myRenderer);
__________________
My gaming placement |
|
|
|
|
|
|
#6 | |
|
Senior Member
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
|
Quote:
Io facevo riferimento a Swing. Per essere chiari a tutta la gerarchia di classi e package a partire da: javax.swing.
__________________
As long as you are basically literate in programming, you should be able to express any logical relationship you understand. If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it. (Chris Crawford) |
|
|
|
|
|
|
#7 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
si ma lo stesso non mi trova quelle classi...comunque oggi ci perdo un pò di tempo e vedo se riesco a risolvere
__________________
My gaming placement |
|
|
|
|
|
#8 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
aspèp che non si capisce cosa volevo dire:
si mi sono accorto anche io che fà riferimento ad swt (gli import sono tutti org.eclipse....) dicevo che se copio "pari pari" il tuo codice non funziona...ora sto vedendo se trovo altre "soluzioni"
__________________
My gaming placement |
|
|
|
|
|
#9 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
Come da tutorial oracle:
http://docs.oracle.com/javase/tutori...le.html#editor Solo JTextField, JCheckBox, or JComboBox vanno nel DefaultCellEditor, quindi devo prima ricreare il CellEditor. Rileggendo la tua prima risposta ora sto ricomponendo i pezzi
__________________
My gaming placement |
|
|
|
|
|
#10 | ||
|
Senior Member
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
|
Quote:
Quote:
Comunque nella pagina che hai linkato dei java Tutorials guarda l'esempio ColorEditor.java: è l'implementazione di un editor che in realtà è un bottone la cui pressione attiva una dialog per impostare il colore. Se non ho capito male a te servirebbe un meccanismo simile: un editor-bottone la cui pressione scatena la tua azione (aperture del file).
__________________
As long as you are basically literate in programming, you should be able to express any logical relationship you understand. If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it. (Chris Crawford) |
||
|
|
|
|
|
#11 | |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
Quote:
grazie mille
__________________
My gaming placement |
|
|
|
|
|
|
#12 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
mi sono perso da qualche parte...
allora ho creato il mio render personalizzato a pulsante, come da esempio: Codice:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package graphicComponent;
import java.awt.Component;
import java.util.Map;
import java.util.WeakHashMap;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class TableButtonRender extends AbstractCellEditor
implements TableCellRenderer, TableCellEditor {
private Map<String, JButton> renderButtons = new WeakHashMap<String, JButton>();
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton) value;
JButton renderButton = renderButtons.get(button.getText());
if (renderButton == null) {
renderButton = new JButton(button.getText());
renderButtons.put(button.getText(), renderButton);
}
return renderButton;
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
return (JButton) value;
}
}
Codice:
private void visualizzaTabella() {
HashMap<String, Protocollo> listaProtocolli = this.archivioProtocollo.getListaProtocolli();
Set<String> chiavi = this.archivioProtocollo.getListaProtocolli().keySet();
int rigaTabella = 0;
TableModel model = this.tabellaProtocollo.getModel();
TableColumn column = this.tabellaProtocollo.getColumnModel().getColumn(8);
TableButtonRender render=new TableButtonRender();
column.setCellRenderer(render);
((DefaultTableModel) model).setNumRows(listaProtocolli.size() + 1);
for (String key : chiavi) {
final Protocollo protocollo = listaProtocolli.get(key);
if (protocollo.getDirezione().equalsIgnoreCase("entrata")) {
model.setValueAt(protocollo.getId(), rigaTabella, 0);
model.setValueAt(protocollo.getData(), rigaTabella, 1);
model.setValueAt(protocollo.getMittente(), rigaTabella, 2);
model.setValueAt(protocollo.getOggetto(), rigaTabella, 3);
model.setValueAt(protocollo.getMezzo(), rigaTabella, 4);
model.setValueAt("", rigaTabella, 5);
model.setValueAt("", rigaTabella, 6);
model.setValueAt("", rigaTabella, 7);
JButton pulsante = new JButton("Apri File");
pulsante.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(protocollo.getFile().equals("") || protocollo.getFile() ==null)
JOptionPane.showMessageDialog(null, "File non presente");
else
launchFile(protocollo.getFile());
}
});
model.setValueAt(pulsante, rigaTabella, 8);
} else {
model.setValueAt(protocollo.getId(), rigaTabella, 0);
model.setValueAt(protocollo.getData(), rigaTabella, 1);
model.setValueAt(protocollo.getMittente(), rigaTabella, 6);
model.setValueAt(protocollo.getOggetto(), rigaTabella, 5);
model.setValueAt(protocollo.getMezzo(), rigaTabella, 7);
model.setValueAt("", rigaTabella, 3);
model.setValueAt("", rigaTabella, 4);
model.setValueAt("", rigaTabella, 2);
JButton pulsante = new JButton("Apri File");
pulsante.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(protocollo.getFile().equals("") || protocollo.getFile() ==null)
JOptionPane.showMessageDialog(null, "File non presente");
else
launchFile(protocollo.getFile());
}
});
model.setValueAt(pulsante, rigaTabella, 8);
rigaTabella++;
}
this.tabellaProtocollo.setModel(model);
}
}
Codice:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at graphicComponent.TableButtonRender.getTableCellRendererComponent(TableButtonRender.java:25) at javax.swing.JTable.prepareRenderer(JTable.java:5735) at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114) at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016) at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812) at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161) at javax.swing.JComponent.paintComponent(JComponent.java:778) at javax.swing.JComponent.paint(JComponent.java:1054) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paint(JComponent.java:1063) at javax.swing.JViewport.paint(JViewport.java:725) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paint(JComponent.java:1063) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paint(JComponent.java:1063) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paint(JComponent.java:1063) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paint(JComponent.java:1063) at javax.swing.JLayeredPane.paint(JLayeredPane.java:585) at javax.swing.JComponent.paintChildren(JComponent.java:887) at javax.swing.JComponent.paintToOffscreen(JComponent.java:5228) at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1482) at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1413) at javax.swing.RepaintManager.paint(RepaintManager.java:1206) at javax.swing.JComponent.paint(JComponent.java:1040) at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:39) at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:78) at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:115) at java.awt.Container.paint(Container.java:1967) at java.awt.Window.paint(Window.java:3867) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:781) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:728) at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:677) at javax.swing.RepaintManager.access$700(RepaintManager.java:59) at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1621) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705) at java.awt.EventQueue.access$000(EventQueue.java:101) at java.awt.EventQueue$3.run(EventQueue.java:666) at java.awt.EventQueue$3.run(EventQueue.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:675) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) Codice:
JButton renderButton = renderButtons.get(button.getText()); ora, dove mi sono perso? salto qualche passaggio? sinceramente non ci sto capendo più niente anche perchè nel frattempo sto leggendo iText in Action 2.0 e sinceramente sto sbattendo anche lì X_X
__________________
My gaming placement |
|
|
|
|
|
#13 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
aggiorno perchè ancora non ho risolto:
allora facendo un breve riepilogo di quello che mi serve e dei problemi che sto riscontrando...: Mi serve che una colonna debba renderizzare un JButton che poi debba svolgere una funzione determinata (aprire un file). Ora ho capito che per la JTable il JButton non è renderizzabile nativamente, quindi dobbiamo costruirlo noi: Codice:
package graphicComponent;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class ButtonRender extends JButton implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public ButtonRender() {
super();
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText("Lancia File");
this.setEnabled(true);
return this;
}
}
Ora per rendere funzionale secondo le mie specifiche devo anche ridefinire l'editor della cella, in questo caso ho fatto in questo modo: Codice:
package graphicComponent;
import java.awt.Component;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.WeakHashMap;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
public class ButtonEditor extends AbstractCellEditor implements TableCellEditor {
private Map<String, String> button = new WeakHashMap<String, String>();
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
String path =(String) value;
System.out.println("Stampati riga: "+row+" colonna: "+column+" e valore: "+value);
if (path.equals("") || path == null || path.equals(" ")) {
JOptionPane.showMessageDialog(null, "Nessun file associato");
} else {
launchFile(path);
}
button.put(path, path);
return null;
}
private URI getFileURI(String filePath) {
URI uri = null;
filePath = filePath.trim();
if (filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0) {
if (filePath.indexOf("\\") == 0) {
filePath = "file:" + filePath;
filePath = filePath.replaceAll("#", "%23");
}
try {
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
} else {
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
public void launchFile(File file) {
if (!Desktop.isDesktopSupported()) {
return;
}
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException ex) {
launchFile(file.getPath());
}
}
public void launchFile(String filePath) {
if (filePath == null || filePath.trim().length() == 0) {
return;
}
if (!Desktop.isDesktopSupported()) {
return;
}
Desktop dt = Desktop.getDesktop();
try {
dt.browse(getFileURI(filePath));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In pratica mi succede questo ora, che se assegno un file va tutto bene, ma se non assegno file mi ESPLODE generanto nullpointer sul "path". se serve posto anche il codice di "riempimento" della tabella
__________________
My gaming placement |
|
|
|
|
|
#14 |
|
Senior Member
Iscritto dal: May 2005
Città: Roma
Messaggi: 7938
|
dopo vari tentativi ho risolto:
Codice:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package graphicComponent;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.WeakHashMap;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
/**
*
* @author Utente1
*/
public class ButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private JButton pulsante;
private String path;
public ButtonEditor() {
pulsante = new JButton("Lancia File!");
pulsante.addActionListener(this);
}
@Override
public Object getCellEditorValue() {
return path;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
path = (String) value;
if (path.equalsIgnoreCase("") || path.equalsIgnoreCase(" ")) {
JOptionPane.showMessageDialog(null, "Nessun File Associato", "Errore apertura file", JOptionPane.ERROR_MESSAGE);
}
return pulsante;
}
private URI getFileURI(String filePath) {
URI uri = null;
filePath = filePath.trim();
if (filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0) {
if (filePath.indexOf("\\") == 0) {
filePath = "file:" + filePath;
filePath = filePath.replaceAll("#", "%23");
}
try {
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
} else {
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
public void launchFile(File file) {
if (!Desktop.isDesktopSupported()) {
return;
}
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException ex) {
launchFile(file.getPath());
}
}
public void launchFile(String filePath) {
if (filePath == null || filePath.trim().length() == 0) {
return;
}
if (!Desktop.isDesktopSupported()) {
return;
}
Desktop dt = Desktop.getDesktop();
try {
dt.browse(getFileURI(filePath));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
launchFile(path);
}
}
Codice:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package graphicComponent;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
/**
* @version 1.0 11/09/98
*/
public class ButtonRender extends JButton implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
public ButtonRender() {
super();
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText("Lancia File");
this.setEnabled(true);
return this;
}
}
__________________
My gaming placement |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 16:49.




















