• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Problem with the JScrollPane

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Everybody there

I am creating an application....

In my application i put a JScrollPane, in the JScrollPane is a JPanel, on the JPanel are thumbnails views of many images with the help of ImageIcons for which i used array of JLabels... Every thing is fine working untill i drag down the scrollbar... as soon as i drag down the JScrollPane's vertical or horizontal bar.. i dont know why but all the other images becomes hazy(very unclear) except those images which is shown first when i click on an image folder... i tried many options but all in vain... please help..

My Code is as follows:
***********************************************************************

import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import java.awt.Rectangle;
import javax.swing.JTree;
import javax.swing.JPanel;
import javax.swing.JLabel;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.SimpleDateFormat;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.Panel;
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
import javax.swing.JTextArea;
import javax.swing.JList;

import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JSpinner;
import java.awt.GridBagLayout;
import java.awt.event.ContainerEvent;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;

public class SnapsGallery extends JFrame
{
public static final ImageIcon ICON_COMPUTER =new ImageIcon("computer.gif");
public static final ImageIcon ICON_DISK =new ImageIcon("disk.gif");
public static final ImageIcon ICON_FOLDER =new ImageIcon("folder.gif");
public static final ImageIcon ICON_EXPANDEDFOLDER =new ImageIcon("expandedfolder.gif");

protected DefaultTreeModel m_model;
protected JPopupMenu m_popup;
protected Action m_action;
protected TreePath m_clickedPath;

ImageIcon firstImage;
Color bgColor;
String[] holdPat=null;
BufferedImage[] images;
JLabel label[];
JCheckBox imageCheckBox[];
JLabel jLabel1 = new JLabel();


public String path="";
public String filePath="";
private Vector imageNames;
Dimension size = new Dimension(80, 60);

private JScrollPane jScrollPane1 = new JScrollPane();
private JTree jTree1;
private JScrollPane jScrollPane2 = new JScrollPane();
private JPanel jPanel1 = new JPanel();
private BorderLayout borderLayout1 = new BorderLayout();

// = new JTree();

public static void main(String a[])
{
SnapsGallery obj=new SnapsGallery();
obj.setVisible(true);
}
public SnapsGallery()
{
DefaultMutableTreeNode top = new DefaultMutableTreeNode(new IconData(ICON_COMPUTER, null, "My Computer")); // for the root of the tree

DefaultMutableTreeNode node;
File[] roots = File.listRoots(); /// for the nodes of the tree
for (int k=0; k<roots.length; k++)
{
node = new DefaultMutableTreeNode(new IconData(ICON_DISK,
null, new FileNode(roots[k])));
top.add(node);
node.add(new DefaultMutableTreeNode( new Boolean(true) ));
}

m_model = new DefaultTreeModel(top);
jTree1 = new JTree(m_model);
jTree1.putClientProperty("JTree.lineStyle", "Angled");

TreeCellRenderer renderer = new
IconCellRenderer();
jTree1.setCellRenderer(renderer);

jTree1.addTreeExpansionListener(new
DirExpansionListener());

jTree1.addTreeSelectionListener(new
DirSelectionListener());

jTree1.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
jTree1.setShowsRootHandles(true);
jTree1.setEditable(false);

m_popup = new JPopupMenu(); // to pop-up the nodes when clicked
m_action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
if (m_clickedPath==null)
return;
if (jTree1.isExpanded(m_clickedPath))
jTree1.collapsePath(m_clickedPath);
else
jTree1.expandPath(m_clickedPath);
}
};
m_popup.add(m_action);
m_popup.addSeparator();

Action a1 = new AbstractAction("Delete")
{
public void actionPerformed(ActionEvent e)
{
jTree1.repaint();
JOptionPane.showMessageDialog(SnapsGallery.this,
"Delete option is not implemented",
"Info", JOptionPane.INFORMATION_MESSAGE);
}
};
m_popup.add(a1);

Action a2 = new AbstractAction("Rename")
{
public void actionPerformed(ActionEvent e)
{
jTree1.repaint();
JOptionPane.showMessageDialog(SnapsGallery.this,
"Rename option is not implemented",
"Info", JOptionPane.INFORMATION_MESSAGE);
}
};
m_popup.add(a2);
jTree1.add(m_popup);
jTree1.addMouseListener(new PopupTrigger());

setVisible(true);
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}

}

private void jbInit() throws Exception
{
this.getContentPane().setLayout(null);
this.setSize(new Dimension(601, 574));

jScrollPane1.setBounds(new Rectangle(0, 0, 160, 545));
jScrollPane2.setBounds(new Rectangle(160, 0, 400, 515));
jScrollPane2.getViewport().setLayout(borderLayout1);
jScrollPane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jScrollPane2.setBackground(Color.orange);
jPanel1.setLayout(null);
jPanel1.setBackground(SystemColor.activeCaptionText);
jPanel1.setPreferredSize(new Dimension(5000,5000));

jPanel1.repaint();


jScrollPane1.getViewport().add(jTree1, null);

jScrollPane2.getViewport().add(jPanel1, BorderLayout.CENTER);
this.getContentPane().add(jScrollPane2, null);
this.getContentPane().add(jScrollPane1, null);
}
DefaultMutableTreeNode getTreeNode(TreePath path)
{
return (DefaultMutableTreeNode)(path.getLastPathComponent());
}
FileNode getFileNode(DefaultMutableTreeNode node)
{
if (node == null)
return null;
Object obj = node.getUserObject();
if (obj instanceof IconData)
obj = ((IconData)obj).getObject();
if (obj instanceof FileNode)
return (FileNode)obj;
else
return null;
}
class DirSelectionListener
implements TreeSelectionListener
{
public void valueChanged(TreeSelectionEvent event)
{
repaint();
DefaultMutableTreeNode node = getTreeNode(
event.getPath());
FileNode fnode = getFileNode(node);
if (fnode != null)
{
String holdPath=fnode.getFile().getAbsolutePath();

File myDirectory = new File(fnode.getFile().getAbsolutePath());

if ( myDirectory.exists() && myDirectory.isDirectory() )
{
// List the files
String[] fileNameList = myDirectory.list();

String holdFiles="";

for(int u=0;u<fileNameList.length;u++)
{
holdFiles=holdFiles+" "+fileNameList[u];
}

showLists(holdFiles,holdPath);
}
}
}
}

public void showLists(String files,String holdPath)
{

String imageNamesString=files;
path=holdPath.replace('\\','/');
imageNames = parseList(imageNamesString);

int is=imageNames.size();
String holdFileName="";
String extent="";
int s=0;

for(int i=0;i<imageNames.size();i++)
{
holdFileName= imageNames.elementAt(i).toString();
extent=holdFileName.substring(holdFileName.lastIndexOf('.')+1,holdFileName.length());
extent=extent.toLowerCase();

if(extent.equals("jpg") || extent.equals("jpeg") || extent.equals("gif") || extent.equals("png"))
{
s++;
}
}

holdPat=new String[s];

try
{
for(int i=0,m=0;i<imageNames.size();i++)
{
holdFileName= imageNames.elementAt(i).toString();
extent=holdFileName.substring(holdFileName.lastIndexOf('.')+1,holdFileName.length());
extent=extent.toLowerCase();

if(extent.equals("jpg") || extent.equals("jpeg") || extent.equals("gif") || extent.equals("png"))
{
holdPat[m]=path+"/"+imageNames.elementAt(i);
m++;
}
}
}
catch (Exception e)
{
System.out.println("To Err Is Human: "+e);
}

try
{
images= new BufferedImage[holdPat.length];

for(int j = 0; j < holdPat.length; j++)
{
try
{
File input = new File(holdPat[j]);
images[j] = ImageIO.read(input);
}
catch(MalformedURLException mue)
{
System.out.println("url: " + mue.getMessage());
}
catch(IOException ioe)
{
System.out.println("read: " + ioe.getMessage());
}
catch(OutOfMemoryError ome)
{
System.out.println("read: " + ome.getMessage());
}
}
}
catch (Exception e)
{
System.out.println("To Err Is Human Being: "+e);
}

try
{
BufferedImage[] tnails = createThumbnails(images);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
gbc.weightx = 1.0;

ImageIcon ima[] = new ImageIcon[images.length];
label=new JLabel[images.length];
imageCheckBox=new JCheckBox[images.length];

int flag=0;

jPanel1.removeAll();

int a=30,b=20;

for(int j = 0,n=1; j < images.length; j++)
{
gbc.gridwidth = gbc.RELATIVE;
ima[j]=new ImageIcon(tnails[j]);
label[j]=new JLabel(ima[j]);

label[j].setBounds(a, b, 100,100 );
label[j].setBorder(new javax.swing.border.LineBorder(Color.blue, 1));

imageCheckBox[j]=new JCheckBox();
imageCheckBox[j].setBounds(a+40, b+100, 20,20 );
imageCheckBox[j].setBackground(SystemColor.activeCaptionText);

if((n%3)!=0)
{
a=a+125;
}
else
{
b=b+125;
a=30;
}
jPanel1.add(label[j],gbc);
jPanel1.add(imageCheckBox[j],null);
repaint();
}
}
catch (Exception e)
{
System.out.println("To Err Is Gentleman: "+e);
}
}

private BufferedImage[] createThumbnails(BufferedImage[] origs)
{
final int WIDTH = 100;
final int HEIGHT = 100;
BufferedImage[] images = new BufferedImage[origs.length];
try
{
AffineTransform at;

for(int j = 0; j < origs.length; j++)
{
if(origs[j]==null)
{
break;
}

images[j] = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = images[j].createGraphics();
g2.setPaint(bgColor);
g2.fillRect(0, 0, WIDTH, HEIGHT);
// scale to fit

double xScale = (double)WIDTH / origs[j].getWidth();
double yScale = (double)HEIGHT / origs[j].getHeight();


double scale = Math.min(xScale, yScale);
// center thumbnail image
double x = 1;//(WIDTH - origs[j].getWidth() * scale)/2;
double y = 1;//(HEIGHT - origs[j].getHeight() * scale)/2;
at = AffineTransform.getTranslateInstance(x, y);
at.scale(scale, scale);
g2.drawRenderedImage(origs[j], at);
g2.dispose();
}
}
catch (Exception e)
{
System.out.println("To Err Is Mr.Human: "+e);
}
return images;
}

protected static Vector parseList(String theStringList)
{
Vector v=new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(theStringList, " ");
while (tokenizer.hasMoreTokens())
{
String image = tokenizer.nextToken();
v.addElement(image);
}
return v;
}
class DirExpansionListener implements TreeExpansionListener
{
public void treeExpanded(TreeExpansionEvent event)
{
final DefaultMutableTreeNode node = getTreeNode(
event.getPath());
final FileNode fnode = getFileNode(node);

Thread runner = new Thread()
{
public void run()
{
if (fnode != null && fnode.expand(node))
{
Runnable runnable = new Runnable()
{
public void run()
{
m_model.reload(node);
}
};
SwingUtilities.invokeLater(runnable);
}
}
};
runner.start();
}

public void treeCollapsed(TreeExpansionEvent event) {}
}
class PopupTrigger extends MouseAdapter
{
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
int x = e.getX();
int y = e.getY();
TreePath path = jTree1.getPathForLocation(x, y);
if (path != null)
{
if (jTree1.isExpanded(path))
m_action.putValue(Action.NAME, "Collapse");
else
m_action.putValue(Action.NAME, "Expand");
m_popup.show(jTree1, x, y);
m_clickedPath = path;
}
}
}
}

protected static ImageIcon createImageIcon(String path)
{
File f=new File(path);
URL imgURL=null;

try
{
imgURL = f.toURL();
}
catch (MalformedURLException e)
{
}

if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}

}// end of main class




class FileNode
{
protected File m_file;

public FileNode(File file)
{
m_file = file;
}

public File getFile()
{
return m_file;
}

public String toString()
{
return m_file.getName().length() > 0 ? m_file.getName() :
m_file.getPath();
}

public boolean expand(DefaultMutableTreeNode parent)
{
DefaultMutableTreeNode flag =
(DefaultMutableTreeNode)parent.getFirstChild();
if (flag==null) // No flag
return false;
Object obj = flag.getUserObject();
if (!(obj instanceof Boolean))
return false; // Already expanded

parent.removeAllChildren(); // Remove Flag

File[] files = listFiles();
if (files == null)
return true;

Vector v = new Vector();

for (int k=0; k<files.length; k++)
{
File f = files[k];
if (!(f.isDirectory()))
continue;

FileNode newNode = new FileNode(f);

boolean isAdded = false;
for (int i=0; i<v.size(); i++)
{
FileNode nd = (FileNode)v.elementAt(i);
if (newNode.compareTo(nd) < 0)
{
v.insertElementAt(newNode, i);
isAdded = true;
break;
}
}
if (!isAdded)
v.addElement(newNode);
}

for (int i=0; i<v.size(); i++)
{
FileNode nd = (FileNode)v.elementAt(i);
IconData idata = new IconData(SnapsGallery.ICON_FOLDER,
SnapsGallery.ICON_EXPANDEDFOLDER, nd);
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(idata);
parent.add(node);

if (nd.hasSubDirs())
node.add(new DefaultMutableTreeNode(
new Boolean(true) ));
}

return true;
}

public boolean hasSubDirs()
{
File[] files = listFiles();
if (files == null)
return false;
for (int k=0; k<files.length; k++)
{
if (files[k].isDirectory())
return true;
}
return false;
}

public int compareTo(FileNode toCompare)
{
return m_file.getName().compareToIgnoreCase(
toCompare.m_file.getName() );
}

protected File[] listFiles()
{
if (!m_file.isDirectory())
{
JOptionPane.showMessageDialog(null,"Error reading directory "+m_file.getAbsolutePath(),"Warning", JOptionPane.WARNING_MESSAGE);
return null;
}
try
{
return m_file.listFiles();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null,
"Error reading directory "+m_file.getAbsolutePath(),
"Warning", JOptionPane.WARNING_MESSAGE);
return null;
}
}
}// end of FileNode class

class IconCellRenderer
extends JLabel
implements TreeCellRenderer
{
protected Color m_textSelectionColor;
protected Color m_textNonSelectionColor;
protected Color m_bkSelectionColor;
protected Color m_bkNonSelectionColor;
protected Color m_borderSelectionColor;

protected boolean m_selected;

public IconCellRenderer()
{
super();
m_textSelectionColor = UIManager.getColor(
"Tree.selectionForeground");
m_textNonSelectionColor = UIManager.getColor(
"Tree.textForeground");
m_bkSelectionColor = UIManager.getColor(
"Tree.selectionBackground");
m_bkNonSelectionColor = UIManager.getColor(
"Tree.textBackground");
m_borderSelectionColor = UIManager.getColor(
"Tree.selectionBorderColor");
setOpaque(false);
}

public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus)

{
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)value;
Object obj = node.getUserObject();
setText(obj.toString());

if (obj instanceof Boolean)
setText("Retrieving data...");

if (obj instanceof IconData)
{
IconData idata = (IconData)obj;
if (expanded)
setIcon(idata.getExpandedIcon());
else
setIcon(idata.getIcon());
}
else
setIcon(null);

setFont(tree.getFont());
setForeground(sel ? m_textSelectionColor :
m_textNonSelectionColor);
setBackground(sel ? m_bkSelectionColor :
m_bkNonSelectionColor);
m_selected = sel;
return this;
}

public void paintComponent(Graphics g)
{
Color bColor = getBackground();
Icon icon = getIcon();

g.setColor(bColor);
int offset = 0;
if(icon != null && getText() != null)
offset = (icon.getIconWidth() + getIconTextGap());
g.fillRect(offset, 0, getWidth() - 1 - offset,
getHeight() - 1);

if (m_selected)
{
g.setColor(m_borderSelectionColor);
g.drawRect(offset, 0, getWidth()-1-offset, getHeight()-1);
}

super.paintComponent(g);
}
}//end of IconCellRenderer class

class IconData
{
protected Icon m_icon;
protected Icon m_expandedIcon;
protected Object m_data;

public IconData(Icon icon, Object data)
{
m_icon = icon;
m_expandedIcon = null;
m_data = data;
}

public IconData(Icon icon, Icon expandedIcon, Object data)
{
m_icon = icon;
m_expandedIcon = expandedIcon;
m_data = data;
}

public Icon getIcon()
{
return m_icon;
}

public Icon getExpandedIcon()
{
return m_expandedIcon!=null ? m_expandedIcon : m_icon;
}

public Object getObject()
{
return m_data;
}

public String toString()
{
return m_data.toString();
}
}//end of IconData
***********************************************************************

"A Friend There To Help Me Out"

Thanks
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please do not post the same question more than once. It causes confusion and duplication of effort as the community tries to help everyone.
If you are going to post code, try to narrow your problem code down first. Few people around here have the time to debug hundreds of lines of code.
Have a look at our FAQ, How To Ask Questions On JavaRanch. The better questions you ask, the more help you will get.
 
reply
    Bookmark Topic Watch Topic
  • New Topic