aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Problem with getSelectedValues() ...!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Problem with getSelectedValues() ...!!!" Watch "Problem with getSelectedValues() ...!!!" New topic
Author

Problem with getSelectedValues() ...!!!

sachchu boy
Greenhorn

Joined: Dec 03, 2004
Posts: 1
Hello!

I am having some problem with this code....

It works fine for the compression of data. But in the extraction, even if the files are selected from the JFileChooser, its not recognizing that.

In the module extract archive()�


Object [ ] selObj = null;
selObj = m_zipEntries.getSelectedValues();


if (selObj.length == 0)
{
setStatus("No entries have been selected for extraction");
chooser1.removePropertyChangeListener(lst);
chooser1.remove(p);
return;
}

the control goes inside the if condn. I don�t know why selObj.length is zero.

Please help me�..

Thanks in advance

Bye

This is the complete code. Please run the code to know what exactly is happening.








import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;
import java.beans.*;
import java.text.SimpleDateFormat;

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




public class ZipJarManager extends JFrame
{
public static int BUFFER_SIZE = 10240;

protected JFileChooser chooser1;
protected JFileChooser chooser2;

protected File m_currentDir = new File(".");
protected SimpleFilter m_zipFilter;
protected SimpleFilter m_jarFilter;
protected ZipFileView m_view;

protected JButton m_btCreate;
protected JButton m_btExtract;
protected JLabel m_status;

protected JList m_zipEntries;
protected File m_selectedFile;
protected int [] m_tabs[] = null;

public ZipJarManager()
{
super("ZIP/JAR Manager");

JWindow jwin = new JWindow();
jwin.getContentPane().add(new JLabel(
"Loading ZIP/JAR Manager...", SwingConstants.CENTER));
jwin.setBounds(200,200,200,100);
jwin.setVisible(true);

chooser1 = new JFileChooser();
chooser2 = new JFileChooser();

JPanel p = new JPanel(new GridLayout(3, 1, 10, 10));
p.setBorder(new EmptyBorder(10, 10, 10, 10));

m_btCreate = new JButton("Create new Archive");
ActionListener lst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
m_btCreate.setEnabled(false);
m_btExtract.setEnabled(false);
createArchive();
m_btCreate.setEnabled(true);
m_btExtract.setEnabled(true);
}
};
m_btCreate.addActionListener(lst);
m_btCreate.setMnemonic('c');
p.add(m_btCreate);

m_btExtract = new JButton("Extract from Archive");
lst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
m_btCreate.setEnabled(false);
m_btExtract.setEnabled(false);
extractArchive();
m_btCreate.setEnabled(true);
m_btExtract.setEnabled(true);
}
};
m_btExtract.addActionListener(lst);
m_btExtract.setMnemonic('e');
p.add(m_btExtract);

m_status = new JLabel();
m_status.setBorder(new BevelBorder(BevelBorder.LOWERED,
Color.white, Color.gray));
p.add(m_status);

m_zipFilter = new SimpleFilter("zip", "ZIP Files");
m_jarFilter = new SimpleFilter("jar", "JAR Files");
m_view = new ZipFileView();

chooser1.addChoosableFileFilter(m_zipFilter);
chooser1.addChoosableFileFilter(m_jarFilter);
chooser1.setFileView(m_view);
chooser1.setMultiSelectionEnabled(false);
chooser1.setFileFilter(m_jarFilter);

javax.swing.filechooser.FileFilter ft =
chooser1.getAcceptAllFileFilter();
chooser1.removeChoosableFileFilter(ft);

getContentPane().add(p, BorderLayout.CENTER);
setBounds(0,0,300,150);
WindowListener wndCloser = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
addWindowListener(wndCloser);

jwin.setVisible(false);
jwin.dispose();

setVisible(true);
}

public void setStatus(String str)
{
m_status.setText(str);
m_status.repaint();
}


protected void createArchive() {

JFileChooser archiveChooser = new JFileChooser();
archiveChooser.addChoosableFileFilter(m_zipFilter);
archiveChooser.addChoosableFileFilter(m_jarFilter);
archiveChooser.setFileView(m_view);
archiveChooser.setMultiSelectionEnabled(false);
archiveChooser.setFileFilter(m_jarFilter);

javax.swing.filechooser.FileFilter ft = archiveChooser.getAcceptAllFileFilter();
archiveChooser.removeChoosableFileFilter(ft);

archiveChooser.setCurrentDirectory(m_currentDir);
archiveChooser.setDialogType(JFileChooser.SAVE_DIALOG);
archiveChooser.setDialogTitle("New Archive");

if(archiveChooser.showDialog(this,"Create") != JFileChooser.APPROVE_OPTION)
return;

m_currentDir=archiveChooser.getCurrentDirectory();

final File archiveFile = archiveChooser.getSelectedFile();

if(!isArchiveFile(archiveFile))
return;

JFileChooser entriesChooser = new JFileChooser();
entriesChooser.setCurrentDirectory(m_currentDir);
entriesChooser.setDialogType(JFileChooser.OPEN_DIALOG);
entriesChooser.setDialogTitle("Select Content Fof " +archiveFile.getName());

entriesChooser.setMultiSelectionEnabled(true);
entriesChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

if(entriesChooser.showDialog (this,"Add") != JFileChooser.APPROVE_OPTION)
return;

m_currentDir = entriesChooser.getCurrentDirectory();
final File[ ] selected = entriesChooser.getSelectedFiles();
String name = archiveFile.getName().toLowerCase();

if(name.endsWith(".zip")) {
Thread runner = new Thread() {
public void run() {
createZipArchive(archiveFile, selected);
}
};

runner.start();
}

/*else if(name.endsWith(".jar") ) {
Thread runner = new Thread() {
public void run() {
createJarArchive(archiveFile, selected);
}
};
runner.start();
}*/
else {
setStatus("No Jar or zip File has been selected");
}
}

protected void extractArchive()
{
// Show dialog to select archive and entries
chooser1.setCurrentDirectory(m_currentDir);
chooser1.setDialogType(JFileChooser.OPEN_DIALOG);
chooser1.setDialogTitle("Open Archive");
chooser1.setMultiSelectionEnabled(false);
chooser1.setPreferredSize(new Dimension(470,490));

m_zipEntries = new JList();
m_zipEntries.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);


TabListCellRenderer renderer = new TabListCellRenderer();
renderer.setTabs(new int [ ] {240,300,360});
m_zipEntries.setCellRenderer(renderer);

/* new one */
JPanel p = new JPanel(new BorderLayout());
p.setBorder(new EmptyBorder(5,5,5,5));
p.add(new JLabel ("files to Extract"),BorderLayout.WEST);
JScrollPane ps = new JScrollPane(m_zipEntries);
p.add(ps, BorderLayout.EAST);
chooser1.add(p,BorderLayout.EAST);


PropertyChangeListener lst = new PropertyChangeListener()
{
SimpleDateFormat m_sdf = new SimpleDateFormat(
"MM/dd/yyyy hh:mm a");
DefaultListModel m_emptyModel = new DefaultListModel();

public void propertyChange(PropertyChangeEvent e)
{
if (e.getPropertyName() == JFileChooser.FILE_FILTER_CHANGED_PROPERTY)
{
m_zipEntries.setModel(m_emptyModel);
return;
}
else if (e.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
File f = chooser1.getSelectedFile();

if (f != null)
{
if (m_selectedFile!=null && m_selectedFile.equals(f)
&& m_zipEntries.getModel().getSize() > 0)
{
return;
}

String name = f.getName().toLowerCase();
if (!name.endsWith(".zip") && !name.endsWith(".jar"))
{
m_zipEntries.setModel(m_emptyModel);
return;
}

try
{
ZipFile zipFile = new ZipFile(f.getPath());
DefaultListModel model = new DefaultListModel();
Enumeration en = zipFile.entries();
while (en.hasMoreElements())
{
ZipEntry zipEntr = (ZipEntry)en.
nextElement();
Date d = new Date(zipEntr.getTime());
String str = zipEntr.getName()+'\t'+
zipEntr.getSize()+'\t'+m_sdf.format(d);
model.addElement(str);
}
zipFile.close();
m_zipEntries.setModel(model);
m_zipEntries.setSelectionInterval(0,
model.getSize()-1);
}
catch(Exception ex)
{
ex.printStackTrace();
setStatus("Error: "+ex.getMessage());
}
}
}
else
{
m_zipEntries.setModel(m_emptyModel);
return;
}
}
};

chooser1.addPropertyChangeListener(lst);
chooser1.cancelSelection();

if (chooser1.showDialog(this, "Extract") !=
JFileChooser.APPROVE_OPTION)
{
chooser1.remove(p);
chooser1.removePropertyChangeListener(lst);
return;
}
m_currentDir = chooser1.getCurrentDirectory();
final File archiveFile = chooser1.getSelectedFile();

if (!archiveFile.exists() || !isArchiveFile(archiveFile))
{
chooser1.remove(p);
chooser1.removePropertyChangeListener(lst);
return;
}

Object [ ] selObj = null;
selObj = m_zipEntries.getSelectedValues();


if (selObj.length == 0)
{
setStatus("No entries have been selected for extraction");
chooser1.removePropertyChangeListener(lst);
chooser1.remove(p);
return;
}

final String[] entries = new String[selObj.length];

for (int k=0; k < selObj.length; k++)
{
String str = selObj[k].toString();
int index = str.indexOf('\t');
entries[k] = str.substring(0, index);
}

// Show dialog to select output directory
chooser2.setCurrentDirectory(m_currentDir);
chooser2.setDialogType(JFileChooser.OPEN_DIALOG);
chooser2.setDialogTitle("Select destination directory for " + archiveFile.getName());
chooser2.setMultiSelectionEnabled(false);
chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

if (chooser2.showDialog(this, "Select") !=
JFileChooser.APPROVE_OPTION)
{
chooser1.remove(p);
chooser1.removePropertyChangeListener(lst);
return;
}

m_currentDir = chooser2.getCurrentDirectory();
final File outputDir = chooser2.getSelectedFile();

Thread runner = new Thread()
{
public void run()
{
try
{
byte buffer[] = new byte[BUFFER_SIZE];
// Open the archive file
FileInputStream stream =
new FileInputStream(archiveFile);
ZipInputStream in = new ZipInputStream(stream);

// Find archive entry
while (true)
{
ZipEntry zipExtract = in.getNextEntry();
if (zipExtract == null)
break;
boolean bFound = false;
for (int k = 0; k < entries.length; k++)
{
if (zipExtract.getName().equals(entries[k]))
{
bFound = true;
break;
}
}
if (!bFound)
{
in.closeEntry();
continue;
}
setStatus("Extracting "+zipExtract.getName());

// Create output file and chack required directory
File outFile = new File(outputDir,
zipExtract.getName());
File parent = outFile.getParentFile();
if (parent != null && !parent.exists())
parent.mkdirs();

// Extract unzipped file
FileOutputStream out =
new FileOutputStream(outFile);
while (true)
{
int nRead = in.read(buffer,
0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
out.close();
in.closeEntry();
}

in.close();
stream.close();
setStatus("Extracting completed OK");
}
catch (Exception ex)
{
ex.printStackTrace();
setStatus("Error: "+ex.getMessage());
}
}
};
runner.start();
chooser1.removePropertyChangeListener(lst);
chooser1.remove(p);
}


protected void createZipArchive(File archiveFile, File[] selected)
{
try
{
byte buffer[] = new byte[BUFFER_SIZE];
// Open archive file
FileOutputStream stream =
new FileOutputStream(archiveFile);
ZipOutputStream out = new ZipOutputStream(stream);

for (int k = 0; k < selected.length; k++)
{
if (selected[k]==null || !selected[k].exists() ||
selected[k].isDirectory())
continue;// Just in case...
setStatus("Adding "+selected[k].getName());

// Add archive entry
ZipEntry zipAdd = new ZipEntry(selected[k].getName());
zipAdd.setTime(selected[k].lastModified());
out.putNextEntry(zipAdd);

// Read input & write to output
FileInputStream in = new FileInputStream(selected[k]);
while (true)
{
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
}

out.close();
stream.close();
setStatus("Adding completed OK");
}
catch (Exception e)
{
e.printStackTrace();
setStatus("Error: "+e.getMessage());
return;
}
}


/************************************************/
/*
public String [ ] getSelectedEntries(JFileChooser chooser) {
Object [ ] selObj = m_zipEntries.getSelectedValues() ;
String [] entries = new String [selObj.length];

for(int k=0;k<selObj.length; k++) {
String str = selObj[k].toString();
int index = str.indexOf('\t');
entries[k] = str.substring(0,index);
}

return entries;
}
/* */

/*

public static File[] getSelectedFiles(JFileChooser chooser)
{
// Although JFileChooser won't give us this information,
// we need it...
Container c1 = (Container)chooser.getComponent(3);
JList list = null;
while (c1 != null)
{
Container c = (Container)c1.getComponent(0);
if (c instanceof JList)
{
list = (JList)c;
break;
}
c1 = c;
}
Object[] entries = list.getSelectedValues();
File[] files = new File[entries.length];
for (int k = 0; k < entries.length; k++)
{
if (entries[k] instanceof File)
files[k] = (File)entries[k];
}
return files;
}
*/
/**********************************************************************/
public static boolean isArchiveFile(File f)
{
String name = f.getName().toLowerCase();
return (name.endsWith(".zip") || name.endsWith(".jar"));
}

public static void main(String argv[])
{
new ZipJarManager();
}
}

class SimpleFilter extends javax.swing.filechooser.FileFilter
{
private String m_description = null;
private String m_extension = null;

public SimpleFilter(String extension, String description)
{
m_description = description;
m_extension = "."+extension.toLowerCase();
}

public String getDescription()
{
return m_description;
}

public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return f.getName().toLowerCase().endsWith(m_extension);
}
}

class ZipFileView extends javax.swing.filechooser.FileView
{
protected static ImageIcon ZIP_ICON = new ImageIcon("archive.gif");
protected static ImageIcon JAR_ICON = new ImageIcon("jar.gif");

public String getName(File f)
{
String name = f.getName();
return name.equals("") ? f.getPath() : name;
}

public String getDescription(File f)
{
return getTypeDescription(f);
}

public String getTypeDescription(File f)
{
String name = f.getName().toLowerCase();
if (name.endsWith(".zip"))
return "ZIP Archive File";
else if (name.endsWith(".jar"))
return "Java Archive File";
else
return "File";
}

public Icon getIcon(File f)
{
String name = f.getName().toLowerCase();
if (name.endsWith(".zip"))
return ZIP_ICON;
else if (name.endsWith(".jar"))
return JAR_ICON;
else
return null;
}

public Boolean isTraversable(File f)
{
return ( f.isDirectory() ? Boolean.TRUE : Boolean.FALSE);
}

}

class TabListCellRenderer extends JLabel implements ListCellRenderer {
protected static Border m_noFocusBorder;
protected FontMetrics m_fm = null;
protected Insets m_insets = new Insets(0,0,0,0) ;

protected int m_defaultTab = 50;
protected int [] m_tabs = null;

public TabListCellRenderer() {
super();
m_noFocusBorder = new EmptyBorder(1,1,1,1);
setOpaque(true);
setBorder(m_noFocusBorder);
}

public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString() );

setBackground(isSelected ? list.getSelectionBackground() : list.getBackground() );

setForeground(isSelected ? list.getSelectionForeground() : list.getForeground() ) ;

setFont(list.getFont() );
setBorder ((cellHasFocus) ? UIManager.getBorder ( "List.focusCellHighlightBorder") : m_noFocusBorder);

return this;
}

public void setDefaultTab(int defaultTab) {
m_defaultTab = defaultTab;
}

public int getDefaultTab() {
return m_defaultTab;
}

public void setTabs(int [ ] tabs) {
m_tabs=tabs;
}

public int [ ] getTabs() {
return m_tabs;
}

public int getTab(int index) {
if(m_tabs == null)
return m_defaultTab*index;

int len = m_tabs.length;
if(index>=0 && index<len)
return m_tabs[index];

return m_tabs[len -1] + m_defaultTab*(index-len+1);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
m_fm=g.getFontMetrics();

g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight() );

getBorder().paintBorder(this,g,0,0,getWidth(),getHeight());

g.setColor(getForeground());
g.setFont(getFont());

m_insets=getInsets();
int x = m_insets.left;
int y = m_insets.top+m_fm.getAscent();

StringTokenizer st = new StringTokenizer(getText(), "\t");

while (st.hasMoreTokens())
{
String sNext = st.nextToken();
g.drawString(sNext,x,y);
x += m_fm.stringWidth(sNext);

if(!st.hasMoreTokens())
break;
int index=0;
while (x>=getTab(index))
index++;
x=getTab(index);
}
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with getSelectedValues() ...!!!