Refresh the JTable on updating the data - java

Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.

why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class

Related

Socket blocking client when sending image

So I'm making a simple chat where I'm sending content in the form of objects, in this case my problem is that when I'm sending and Image it just blocking my Client!, here's my shortened code.
I've isolated it mostly to the code below, as I've tested the rest and worked fine, I've also tried debugging this but I just can't seem to find the problem
Image
package com.example.mtc.Packets;
import java.io.Serializable;
public class Image extends Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3188407715959746920L;
private byte[] content;
private String type;
public Image(byte[] content,String type, int sourceID,int destinationID,String sourceUsername) {
super(destinationID,sourceID,sourceUsername);
this.content = content;
this.type = "." + type;
}
public byte[] getContent() {
return content;
}
public String getType() {
return type;
}
}
ClientReaderThread:
while (true) {
try {
inputData = in.readObject();
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300, java.awt.Image.SCALE_DEFAULT));
if (imagePacket.getDestinationID() == 0) {
if (Cliente.selectedChat == 0) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
} else if (imagePacket.getSourceID() == Cliente.selectedChat
|| imagePacket.getSourceID() == Cliente.getUserID()) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Cliente.gui, "Couldn't connect to Server!", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server Listener
private void Listener() {
// TODO Auto-generated method stub
while (connected) {
inputData = readObject();
if (inputData != null) {
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300,
java.awt.Image.SCALE_DEFAULT));
imageIcon.getImage().flush();
BufferedImage bi = new BufferedImage(
imageIcon.getIconWidth(),
imageIcon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
imageIcon.paintIcon(null, g, 0,0);
g.dispose();
try {
File imageFile = File.createTempFile("image", imagePacket.getType(),
new File("./serverImages/"));
insertLog(imageFile.getAbsolutePath(), imagePacket.getDestinationID(), true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Files.write(imageFile.toPath(), imageContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (imagePacket.getDestinationID() == 0) {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
t.sendObject(imagePacket);
}
}
}
} else {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
if (t.getUserID() == imagePacket.getDestinationID()) {
t.sendObject(imagePacket);
}
}
}
sendObject(imagePacket);
}
}
}
}
}
}
Managed to solve it by using SwingUtilities.invokeLater(), as advised by R.L.M

How to display value in combobox and save its id into database

I have a combobox that the value is shown instead of Id. id should be then insert into a database. I added a listener to combobox to get the Id. By sysout I can see but how could I insert into database????
here is the code:
public void comboboxpersonneldata() {
comboboxpersonnellist = FXCollections.observableArrayList();
handler = new DBHandler();
connection = handler.getConnection();
try {
rs = connection.createStatement().executeQuery("SELECT num_personnel,nom_personnel FROM personnel");
while (rs.next()) {
// comboboxpersonnellist.add(rs.getInt(1));
comboboxpersonnellist.addAll(new comboboxPersonnel(rs.getInt(1), rs.getString(2)));
}
combopersonnel.setItems(comboboxpersonnellist);
combopersonnel.valueProperty().addListener((obs, oldval, newval) -> {
if (newval != null) {
System.out.println(newval.getNum_personnel());
}
});
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the model class:
public class comboboxPersonnel {
int num_personnel;
String name_personnel;
public comboboxPersonnel(int num_personnel, String name_personnel) {
this.num_personnel = num_personnel;
this.name_personnel = name_personnel;
}
public int getNum_personnel() {
return num_personnel;
}
public String getName_personnel() {
return name_personnel;
}
#Override
public String toString() {
return name_personnel;
}
}

Is it possible to select the file name in a JFileChooser window?

I can set the default File Name: in a JFileChooser window using:
fileChooser.setSelectedFile();
I was wondering if it is also possible to select it, so that if you want to save the file as something else you can immediately start to overtype it. Thanks for any help on this.
package filetest;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
#SuppressWarnings("serial")
class Editor {
public static class TextClass extends JTextArea {
FileClass fileClass = new FileClass();
public void setKeyboardShortcuts() {
fileClass.setKeyboardShortcuts();
}
private class FileClass {
private File directory;
private String filepath = "";
private String filename = "";
private void setKeyboardShortcuts() {
Action ctrlo = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
openFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl O"), "ctrlo");
getActionMap().put("ctrlo", ctrlo);
Action ctrls = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
saveFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl S"), "ctrls");
getActionMap().put("ctrls", ctrls);
}
private String selectFile(String fileaction) throws FileNotFoundException {
JFileChooser filechooser = new JFileChooser();
if (directory != null) {
filechooser.setCurrentDirectory(directory);
} else {
filechooser.setCurrentDirectory(new File("."));
}
filechooser.setSelectedFile(new File(filepath));
int r = 0;
if (fileaction.equals("openfile"))
r = filechooser.showDialog(new JPanel(), "Open file");
else
r = filechooser.showDialog(new JPanel(), "Save file");
if (r == JFileChooser.APPROVE_OPTION) {
try {
directory = filechooser.getSelectedFile().getParentFile();
filename = filechooser.getSelectedFile().getName();
return filename;
} catch (Exception exception) {
return "";
}
} else {
return "";
}
}
private void openFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("openfile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("savefile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
createAndShowGui();
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
JTextArea textArea = new TextClass();
frame.add(textArea);
((TextClass) textArea).setKeyboardShortcuts();
frame.setVisible(true);
}
}
It does that by default on the machine I'm typing from:
package stackoverflow;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author ub
*/
public class StackOverflow
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png");
chooser.setFileFilter(filter);
chooser.setSelectedFile(new File("C:\\Users\\ub\\Pictures\\Capt.PNG"));
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
}
}
It's because when you first call .setSelectedFile your filepath is an empty string.
You set your filepath variable after having shown the file chooser to the user.
If you print to console the string value of filepath, right before invoking .showDialog, you should see this.
The problem seems to be caused by these lines:
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
If they are removed, the file name is highlighted as in Unai Vivi's example.

removing recently add JLabel on JTextPane

Hi I was doing a list of online users names using JLabel inside the JTextPane.
I used JLabel because I want the names to be clickable I was able to allign them horizontally using the styleddocument now my problem is
How can I delete the JLabel that was recently inserted ? I tried the remove method of JTextPane but it didnt work. I need to delete the JLabel when a user go offline.
My code:
public static void getUsernames()
{
try{
String query = "SELECT username FROM members WHERE status = 'offline'";
ps3 = con.prepareStatement(query);
rs2 = ps3.executeQuery();
}catch(Exception ex){ex.printStackTrace();}
}
public static void resultGetUsername(JTextPane jtp,StyledDocument sd)
{
try {
while (rs2.next())
{
final JLabel jl = new JLabel(rs2.getString("username"));
final String username = rs2.getString("username");
Border d = BorderFactory.createEmptyBorder(1,10,1,10);
Border d2 = BorderFactory.createLineBorder(Color.BLACK);
Border d3 = BorderFactory.createCompoundBorder(d2,d);
jl.setFont(new Font("Calibri",Font.BOLD,16));
jl.setBorder(d3);
jl.setOpaque(true);
jl.setBackground(Color.ORANGE);
jl.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
jl.setForeground(new Color(30,144,255));
}
public void mouseExited(MouseEvent arg0) {
jl.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
jl.setForeground(new Color(210,105,30));
jl.setBackground(new Color(154,205,50));
}
public void mouseReleased(MouseEvent e) {
jl.setBackground(Color.ORANGE);
jl.setForeground(Color.BLACK);
if(e.getClickCount() ==2)
new OneToOneChat(username);
}
});
Cursor c = new Cursor(Cursor.HAND_CURSOR);
jl.setCursor(c);
jtp.insertComponent(jl);
sd.insertString(sd.getLength(), "\n", SubPanel1.sas);
}
} catch (SQLException e) {
} catch (BadLocationException e) {
}
finally{
if (rs2 != null) {
try {
rs2.close();
} catch (SQLException sqlEx) { }
rs2 = null;
}
if (ps3 != null) {
try {
ps3.close();
} catch (SQLException sqlEx) { }
ps3 = null;
}
}
}
You can remove the labels from the JTextPane by using
setText("") or getStyledDocument().remove(0, doc.getLength())
if you need to get the labels this post could help: Get a component from a JTextPane through javax.swing.text.Element?
Then add the labels you want back into the JTextPane

drag and drop files from OS into JTable java

Can someone show me what I'm doing wrong? I was able to get drag and drop working with a regular panel but now trying with a table and I can't sort it out. I'm getting confused with the Points and DropTargets. Dont mind the "Add" button. I feel like I need to deal with the DnD first.
public class Table extends JFrame implements ActionListener {
private JTable table;
private JScrollPane scroll;
private JButton add;
private JFileChooser choose;
private JMenuBar menubar;
private JMenu menu;
private JMenuItem file;
private DefaultTableModel tm = new DefaultTableModel(new String[] { "File",
"File Type", "Size", "Status" }, 2);
public Table() {
// String column [] = {"Filename ","File Type", "Size", "Status" };
/*
* Object[][] data = { {"File1", ".jpg","32 MB", "Not Processed"},
* {"File2", ".txt"," 5 Kb", "Not Processed"}, {"File3", ".doc","3 Kb",
* "Not Processed"},
* };
*/
table = new JTable();
table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500, 300));
scroll = new JScrollPane(table);
table.setDropTarget(new DropTarget() {
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
super.drop(dtde);
}
});
scroll.setDropTarget(new DropTarget() {
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
// handle drop outside current table (e.g. add row)
super.drop(dtde);
}
});
add(scroll, BorderLayout.CENTER);
menubar = new JMenuBar();
menu = new JMenu("File");
file = new JMenuItem("file");
menu.add(file);
// menubar.add(menu);
add(menu, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon("lock_icon.png");
add = new JButton("Add", icon);
add.addActionListener(this);
JFileChooser choose = new JFileChooser();
choose.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
int returnValue = 0;
if (clicked == add) {
choose = new JFileChooser();
choose.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = choose.getSelectedFile();
file.getAbsolutePath();
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Table t = new Table();
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.pack();
t.setSize(600, 200);
t.setVisible(true);
t.setTitle("ZipLock");
t.setIconImage(null);
}
});
}
}
I personally would ditch the drop target on the scroll pane, it's going to cause you to many problems.
Your drop method is a little queezy...
This is a bad idea....
List fileList = null;
try {
fileList = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = (File) fileList.get(0);
table.setValueAt(f.getAbsolutePath(), row, column);
table.setValueAt(f.length(), row, column + 1);
Basically, you try and extract the file list from the transferable, and regardless of the success of the operation, you try and use it ?! You do no validation of the returned value at all...
Your drop code generally doesn't really care about what column the drop occurred on, as you have name and size columns already, so I'd actually ignore that altogether.
As for the row, now you have two choices. Either you add a new row when the user doesn't drop on an existing one or you reject the attempt.
Reject drag's "outside" of table
(Or reject drags that don't call over an existing row)
To reject the operation while the user is dragging, you need to override the dragOver method...
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
dtde.rejectDrag();
table.clearSelection();
} else {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
table.setRowSelectionInterval(row, row);
}
}
Now, I'm been a little smart here (and not in the clever way). Basically, if the user has dragged over a row, I've highlighted it. This makes it a little more obvious where the drop is going.
In your drop method, I would also make some additional checks...
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row >= 0) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setValueAt(f.getAbsolutePath(), row, 0);
model.setValueAt(f.length(), row, 2);
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
Accept Drag's "outside" of the table
The process is relativly the same, except now we can throw away the conditions that would have otherwise caused us to reject the drag/drop (obviously)
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
table.clearSelection();
} else {
table.setRowSelectionInterval(row, row);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
And the drop method
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (Object value : fileList) {
if (value instanceof File) {
File f = (File) value;
if (row < 0) {
System.out.println("addRow");
model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
} else {
System.out.println("insertRow " + row);
model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
row++;
}
}
}
}
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
Note. This will insert rows at the drop point, push all the existing rows down OR if not dropped on an existing row, will add them to the end...
TEST CODE
This a full running example I used to test the code...
public class DropTable {
public static void main(String[] args) {
new DropTable();
}
public DropTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private JTable table;
private JScrollPane scroll;
private DefaultTableModel tm = new DefaultTableModel(new String[]{"File", "File Type", "Size", "Status"}, 0);
public DropPane() {
table = new JTable();
table.setShowGrid(true);
table.setShowHorizontalLines(true);
table.setShowVerticalLines(true);
table.setGridColor(Color.GRAY);
table.setModel(tm);
table.setFillsViewportHeight(true);
table.setPreferredSize(new Dimension(500, 300));
scroll = new JScrollPane(table);
table.setDropTarget(new DropTarget() {
#Override
public synchronized void dragOver(DropTargetDragEvent dtde) {
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
if (row < 0) {
table.clearSelection();
} else {
table.setRowSelectionInterval(row, row);
}
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = dtde.getTransferable();
List fileList = null;
try {
fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
table.clearSelection();
Point point = dtde.getLocation();
int row = table.rowAtPoint(point);
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (Object value : fileList) {
if (value instanceof File) {
File f = (File) value;
if (row < 0) {
model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
} else {
model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
row++;
}
}
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
});
add(scroll, BorderLayout.CENTER);
}
}
}

Categories