i have a problem loading image files.
There are 2 cases, i've tested. The problem occures only in the first one. In both cases a JDialog-window apears that displays a
downscaled image. After 300ms this window closes automatically (there is a timer in the constructor of ImageDialog and CardPrinter; this is only for debugging).
In the production version, the programm must be able to load 30-40 images (one by one) in a JDialog. The user types some text, and clicks on a button to show the next image.
To load the images i use ImageIO.read() in both cases. Alternatively i used CMYKJPEGImage (http://www.randelshofer.ch/blog/2011/08/reading-cmyk-jpeg-images-with-java-imageio/)
but it also produces the exception.
In Main there is myTimer that continusly opens the JDialog with an image-file (listFilesRecurse() should be called with an absolute path by setting the variable pathtofiles).
Case 1)
Loading images in JDialog with overlay layout manager (Main.java, CardPrinter.java, IDCardLayout.java).
For this, the lines from 'CardPrinter cp=null;' to 'cp.dispose();' in Main.java must be uncommented. The tricky part is in addIDCard()#CardPrinter.
Here will be the layout built up. After this paintComponent()#IDCardLayout will be called, if the content of the dialog-window should be actualised.
It seems, that the loaded images won't be destroyed, and the memory gets full (in Window's Taskmanager the memory usage can be seen).
Case 2)
Loading images in a JDialog with no layout manager (Main.java, ImageDialog.java).
(Uncomment the line 'mn.showDialog(mn.frame, file);').
Works perfect. No exceptions!
The function ImageIO.read() should be ok, because in the 2. case, there was no errors (even if the code runs for 20 minutes).
It's strange, it seems in the first case the layoutmanager prevents GC to unload the unused images...
The problem in the 1.case should be in CTR#CardPrinter and addIDCard()#CardPrinter. In CTR i use the OverlayLayout. In the 2.case, there is no Layoutmanager at all.
The Java version is: 1.7.0_80 on Windows7 SP1.
Can somebody help me please?
Thank you in advance,
Daniel
The exception:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferByte.(DataBufferByte.java:92)
at java.awt.image.ComponentSampleModel.createDataBuffer(ComponentSampleModel.java:415)
at java.awt.image.Raster.createWritableRaster(Raster.java:941)
at javax.imageio.ImageTypeSpecifier.createBufferedImage(ImageTypeSpecifier.java:1073)
at javax.imageio.ImageReader.getDestination(ImageReader.java:2896)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1066)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1034)
at javax.imageio.ImageIO.read(ImageIO.java:1448)
at javax.imageio.ImageIO.read(ImageIO.java:1308)
at test.IDCardLayout.loadPicture(IDCardLayout.java:128)
at test.CardPrinter.addIDCard(CardPrinter.java:142)
at test.CardPrinter.(CardPrinter.java:62)
at test.CardPrinter.createDialog(CardPrinter.java:91)
at test.Main$1.actionPerformed(Main.java:69)
at javax.swing.Timer.fireActionPerformed(Timer.java:312)
at javax.swing.Timer$DoPostEvent.run(Timer.java:244)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:745)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:715)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
package test;
/*Main.java*/
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main {
JFrame frame;
//list files recursively, using a filter (pattern). If pattern=*, all files will be listed.
public static void listFilesRecurse(String fullpath, String pattern[], Vector<File> foundFiles) throws IOException {
File dir = new File(fullpath);
File list[] = dir.listFiles();
for(File f: list) {
if( !f.isDirectory() ) {
for(String pt: pattern) {
if(pt.equals("*")) {
foundFiles.add(f);
break;
}
else if( f.getAbsolutePath().toUpperCase().endsWith(pt.toUpperCase()) ) {
foundFiles.add(f);
break;
}
}
} else {
listFilesRecurse(f.getAbsolutePath(), pattern, foundFiles);
}
}
}
public static void main(String[] args) {
final Main mn = new Main();
final String pathtofiles = "\\path\\to\\files\\";
ActionListener task = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Vector<File> list = new Vector<File>();
System.out.println("\nListing files ...");
try {
listFilesRecurse(pathtofiles, new String[]{"jpg", "png", "jpeg"}, list);
} catch (IOException e) {
e.printStackTrace();
}
for(int index=0; index<list.size(); index++) {
String file = list.get(index).getAbsolutePath();
System.out.println("\nLoading image - " + index + ": " + file);
//mn.showDialog(mn.frame, file);
CardPrinter cp=null;
try {
cp = CardPrinter.createDialog(mn.frame, "Max",
"Muster", "1122", "12345678", "01/2018", file);
} catch (Exception e) {
e.printStackTrace();
continue; //break; //return;
}
cp.setVisible(true);
cp.dispose();
}
}
};
final Timer myTimer = new Timer(100, task);
myTimer.setRepeats(true);
JFrame frame = new JFrame("JFrame Example");
mn.frame = frame;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("This is a label!");
JButton button = new JButton();
button.setText("Press me");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
myTimer.start();
}
});
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//opens the dialog that display an image (file).
public void showDialog(JFrame fr, String file) {
ImageDialog imgd = new ImageDialog(fr, "Testdialog", file);
imgd.setSize(300, 300);
imgd.setModal(true);
imgd.setLocation(250, 250);
imgd.setVisible(true);
}
}
package test;
/*ImageDialog.java*/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;
import org.monte.cmykdemo.CMYKJPEGImage;
public class ImageDialog extends JDialog {
String file;
public ImageDialog(JFrame frame, String title, String file) {
super(frame, title);
this.file = file;
//######For debugging only. This will close the dialog window after 300 ms (by calling ImageDialog.this.setVisible(false);).
ActionListener task = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
ImageDialog.this.dispose();
}
};
Timer cl = new Timer(300, task);
cl.start();
//#######
}
//renders the picture on screen.
#Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
setRenderingHints(g2d);
BufferedImage img=null;
try {
img = loadPicture(this.file);
} catch (IOException e) {
e.printStackTrace();
}
g2d.setColor(Color.BLUE);
g2d.drawRect(0, 0, this.getWidth(), this.getHeight());
g2d.drawImage(img, 10, 10, 80, 80, null, null);
}
void setRenderingHints(Graphics2D g2) {
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
}
public static BufferedImage loadPicture(String fullpath) throws IOException {
System.out.println("\nloadPicture(): " + fullpath);
//BufferedImage img = (BufferedImage) CMYKJPEGImage.loadImage( fullpath );
BufferedImage img = (BufferedImage) ImageIO.read( new File(fullpath) );
return img;
}
}
package test;
/*CardPrinter.java*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.OverlayLayout;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.BorderFactory;
import javax.swing.JButton;
public class CardPrinter extends JDialog /*implements Printable*/ {
protected JPanel jp;
protected JTextField tx;
protected JLabel lblCounter;
protected IDCardLayout idcard;
protected String vorname, nachname, id, gueltig, bild;
protected String chipid;
protected CardPrinter(Window owner, String vorname, String nachname, String id, String chipid,
String gueltig, String bild /*, DataReceiver drv*/) throws IOException {
super((Window)owner, "Assign_ChipID_DialogObject");
this.bild = bild;
//this.datareceiver = drv;
setTitle("Assign ID");
setModalityType(JDialog.DEFAULT_MODALITY_TYPE);
setResizable(false);
jp = new JPanel();
jp.setLayout(null);
jp.setOpaque(false);
addIDCard();
//setupButtons();
//setSize(this.getPreferredSize().width, this.getPreferredSize().height);
setSize(250, 250); //+++
setLocation(300, 300); //+++
//Overlay components: tx overlaps idcard
JPanel cnt = new JPanel();
cnt.setLayout(new OverlayLayout(cnt));
cnt.add(jp);
getContentPane().add(cnt);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//######For debugging only. This will close the dialog window after 300 ms (by calling CardPrinter.this.setVisible(false);).
ActionListener task = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CardPrinter.this.setVisible(false);
}
};
Timer closeWnd = new Timer(300, task);
closeWnd.start();
//######
}
//use this to create an instance of this class.
public static CardPrinter createDialog(Window owner, String vorname,
String nachname, String id, String chipid, String gueltig, String bild /*, DataReceiver drv*/) throws IOException {
return new CardPrinter(owner, vorname, nachname, id, chipid, gueltig, bild /*, drv*/);
}
protected void addIDCard() throws IOException {
int idcard_move_vert=15, idcard_move_hor=76;
tx = new JTextField(this.chipid, 8);
jp.add(tx);
tx.setBounds(idcard_move_hor+130, idcard_move_vert+6, 70, 20);
Border border = BorderFactory.createLineBorder(Color.RED);
tx.setBorder(border);
tx.requestFocus();
lblCounter = new JLabel("");
lblCounter.setBounds(idcard_move_hor+270, idcard_move_vert-6, 40, 30);
jp.add(lblCounter);
lblCounter.requestFocus();
System.out.println("\naddIDCard() ...");
BufferedImage picture = IDCardLayout.loadPicture(this.bild);
idcard = new IDCardLayout(/*this.vorname, this.nachname, this.id,*/ picture, this.bild /*, this.gueltig*/);
idcard.setLayout(null);
//idcard.setBounds(idcard_move_hor, idcard_move_vert, idcard.getPreferredSize().width, idcard.getPreferredSize().height);
idcard.setBounds(idcard_move_hor, idcard_move_vert, 50, 60);
idcard.setBorder( new LineBorder(Color.BLACK) );
jp.add(idcard);
//repaint();
}
}
package test;
/*IDCardLayout.java*/
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import org.monte.cmykdemo.CMYKJPEGImage;
public class IDCardLayout extends JPanel {
private BufferedImage bild;
private String bildfile;
public IDCardLayout(BufferedImage photo, String bildfile) {
this.bild = photo;
this.bildfile = bildfile;
}
/**
* Render graphics to the screen.
*/
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
System.out.println("\npaintComponent() ...");
prepareGraphics(g2d);
}
public static BufferedImage loadPicture(String fullpath) throws IOException {
//BufferedImage img = (BufferedImage) CMYKJPEGImage.loadImage( f.getAbsolutePath() );
BufferedImage img = (BufferedImage) ImageIO.read( new File(fullpath) );
return img;
}
//changing the rendering hints has no effect on Outofmemory-exception.
protected void setRenderingHints(Graphics2D g2, boolean normalText) {
if(true) {
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
}
}
/**
* Renders graphics to the screen.
*/
protected void prepareGraphics(Graphics2D g2) {
setRenderingHints(g2, true);
double newHeight = 60;
double scwidth = ( ((double)newHeight / (double)this.bild.getHeight()) ) * (double)this.bild.getWidth();
System.out.println("\nprepareGraphics() ..." + this.bildfile);
g2.drawImage(this.bild, 5, 5,
(int)scwidth,
(int)newHeight,
null, null);
}
}
The problem is solved. I don't use the class OverlayLayout anymore. The layout looks quite different, but now it works.
Related
This question already has answers here:
Why is my JTextArea not updating?
(6 answers)
JTextArea not updating dynamically
(2 answers)
Closed 2 years ago.
I have a code where I'm taking input from user and after clicking on SUBMIT button it executes my logic and shows user a JTextArea on a new frame but the problem is it shows after program executes totally. I have used System.out.println and consoleText.append to see if it's happening on both eclipse and JTextArea but console on eclipse was updating with the code executes but JTextArea only shows when code executes totally.
Here's the code -
MainApp.java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.skillnetinc.marker.utility.InputUtility;
public class MainApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI();
}
});
}
protected static void showGUI() {
JFrame inputFrame = new JFrame("Marker Deletion Script");
inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputFrame.setSize(800, 300);// 800 width and 500 height
inputFrame.setLayout(null);// using no layout managers
inputFrame.setVisible(true);// making the frame visible
inputFrame.setLocationRelativeTo(null);
InputUtility.showUserInputFields(inputFrame);
InputUtility.buttonActivity(inputFrame);
}
}
& InputUtility.java
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class InputUtility {
public static JFrame tableFrame;
public static JTextArea markerDesc, consoleText;
public static JLabel labelMarkerDesc;
public static void showUserInputFields(JFrame inputFrame) {
labelMarkerDesc = new JLabel("<html>Marker<br>Description</html>");
labelMarkerDesc.setBounds(50, 115, 100, 30);
markerDesc = new JTextArea(10, 20);
markerDesc.setBounds(150, 15, 300, 230);
markerDesc.setBorder(BorderFactory.createLineBorder(Color.gray));
inputFrame.add(markerDesc);
inputFrame.add(labelMarkerDesc);
}
public static void buttonActivity(JFrame inputFrame) {
JButton submit = new JButton("SUBMIT");
submit.setBounds(520, 50, 150, 40);
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
consoleText = new JTextArea();
consoleText.setEditable(false);
consoleText.setVisible(true);
JScrollPane sp = new JScrollPane(consoleText);
tableFrame = new JFrame("Script Result");
tableFrame.add(sp);
tableFrame.setSize(800, 300);
tableFrame.setVisible(true);
tableFrame.setLocationRelativeTo(null);
testConsole(consoleText);
}
});
inputFrame.add(submit);
}
public static void testConsole(JTextArea consoleText) {
String marker[] = InputUtility.markerDesc.getText().split("\n");
for (int i = 0; i < marker.length; i++) {
String posName = marker[i].split(" ")[0];
File file = new File("\\\\" + posName + "\\C$\\environment\\marker");
consoleText.append("\nChecking for marker inside " + file);
System.out.println("\nChecking for marker inside " + file);
File[] files = file.listFiles();
if (file.canRead()) {
consoleText.append("Found Total " + files.length + " markers inside " + file);
System.out.println("Found Total " + files.length + " markers inside " + file);
}
}
}
}
Input from user will be something like
192.168.75.18 startup.err
192.168.87.99 startup.err
192.168.66.38 startup.err
===============================================
Adding this here since it's too long for a comment:
I can see I was unclear. When running MaintTest/main, the JFrame with Test button is not the problem. The JFrame which gets displayed when you click the test button is the problem.
Commenting out the FileUtils.copyURLToFile try block makes the 2nd JFrame display so briefly it's not clear whether it shows the label and progbar or not. (The initial JFrame with the Test button appears normally, when I click the Test button, the 2nd JFrame appears for an instant and goes away. The JFrame with the Test button remains, as expected. I don't reproduce "a Test button 6 times in a row". That sounds like things are set up wrong maybe?)
Yes copyURLToFile is blocking, but I start the concurrent display of the 2nd JFrame before I call copyURLToFile, so shouldn't it run in a separate thread anyway? I have a reason to know trhat it does. In the original application from which this code is derived, the 2nd JFrame displays as desired sometimes.
JFrame displaying sometimes is always answered by saying setVisible has to be called last, but that does not address my situation. This appears to have something to do with concurrency and Swing that I don't understand.
===============================================
Usually I can find the answers via google (more often than not at SO). I must be missing something here.
I've whittled this down to a small portion of my actual code and am still not enlightened. Sorry if it's still a little large, but it's hard to condense it further.
There are 3 java files. This references commons-io-2.5.jar. I'm coding/running in Eclipse Neon.
If I run ProgressBar/main() I see the JFrame contents. If I run MainTest/main() I don't. Here are the 3 files (please excuse some indentation anomalies -- the SO UI and I didn't agree on such things):
MainTest
public class MainTest {
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
}
}
MainFrame
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
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.URL;
import java.net.URLConnection;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
public MainFrame() {
// Set up the content pane.
Container contentPane = this.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
jButton.setText("Test");
jButton.setActionCommand("Test");
jButton.addActionListener(this);
contentPane.add(jButton);
setup();
}
private void setup() {
Toolkit tk;
Dimension screenDims;
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void downloadExecutable(String str) {
URL url = null;
try {
url = new URL("http://pegr-converter.com/download/test.jpg");
} catch (MalformedURLException exc) {
JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
return;
}
if (url != null) {
String[] options = { "OK", "Change", "Cancel" };
int response = JOptionPane.NO_OPTION;
File selectedFolder = new File(getDownloadDir());
File selectedLocation = new File(selectedFolder, str + ".jpg");
while (response == JOptionPane.NO_OPTION) {
selectedLocation = new File(selectedFolder, str + ".jpg");
String msgStr = str + ".jpg will be downloaded to the following location:\n"
+ selectedLocation.toPath();
response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (response == JOptionPane.NO_OPTION) {
// Prompt for file selection.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(selectedFolder);
fileChooser.showOpenDialog(null);
selectedFolder = fileChooser.getSelectedFile();
}
}
if (response == JOptionPane.YES_OPTION) {
int size = 0;
URLConnection conn;
try {
conn = url.openConnection();
size = conn.getContentLength();
} catch (IOException exc) {
System.out.println(exc.getMessage());
}
File destination = new File(selectedFolder, str + ".jpg");
ProgressBar status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
try {
FileUtils.copyURLToFile(url, destination, 10000, 300000);
} catch (IOException exc) {
JOptionPane.showMessageDialog(null, "Download failed.");
return;
}
status.close();
}
}
}
public static String getDownloadDir() {
String home = System.getProperty("user.home");
File downloadDir = new File(home + "/Downloads/");
if (downloadDir.exists() && !downloadDir.isDirectory()) {
return home;
} else {
downloadDir = new File(downloadDir + "/");
if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
return downloadDir.getPath();
} else {
return home;
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
downloadExecutable("test");
}
}
ProgressBar
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import org.apache.commons.io.FileUtils;
public class ProgressBar {
private String title;
private File outputFile;
private int size;
private ProgressTimerTask task;
JFrame frame;
JLabel jLabelProgressTitle;
JProgressBar jProgressBarProportion;
public ProgressBar(String title, File output, int size) {
this.title = title;
this.outputFile = output;
this.size = size;
frame = new JFrame("BoxLayoutDemo");
jProgressBarProportion = new JProgressBar();
jProgressBarProportion.setPreferredSize(new Dimension(300, 50));
jLabelProgressTitle = new JLabel();
jLabelProgressTitle.setHorizontalAlignment(SwingConstants.CENTER);
jLabelProgressTitle.setText("Progress");
jLabelProgressTitle.setPreferredSize(new Dimension(300, 50));
//Set up the content pane.
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jLabelProgressTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(jLabelProgressTitle);
jProgressBarProportion.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(jProgressBarProportion);
setup();
task = new ProgressTimerTask(this, outputFile, size);
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 500);
}
private void setup() {
Toolkit tk;
Dimension screenDims;
frame.setTitle("Test");
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
frame.setLocation((screenDims.width - frame.getWidth()) / 2, (screenDims.height - frame.getHeight()) / 2);
jLabelProgressTitle.setText(title);
jProgressBarProportion.setVisible(true);
jProgressBarProportion.setMinimum(0);
jProgressBarProportion.setMaximum(size);
jProgressBarProportion.setValue((int) outputFile.length());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void close() {
task.cancel();
frame.dispose();
}
public static void main(String[] args) throws InterruptedException {
ProgressBar progBar = new ProgressBar("Test Title", new File(MainFrame.getDownloadDir() + "test.jpg"), 30000);
Thread.sleep(3000);
progBar.close();
}
}
class ProgressTimerTask extends TimerTask {
ProgressBar frame;
File outputFile;
int size;
public ProgressTimerTask(ProgressBar progressBar, File outputFile, int size) {
this.frame = progressBar;
this.outputFile = outputFile;
this.size = size;
}
public void run() {
frame.jProgressBarProportion.setValue((int) outputFile.length());
System.out.println("Running");
}
}
Thanks to #MadProgrammer for this comment:
I can tell you, that you probably won't see the ProgressBar frame because the FileUtils.copyURLToFile will block until it's finished, in that case, you really should be using a SwingWorker
I read up about SwingWorker at the tutorial https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html and subsequently modified my MainFrame.java module to look like this:
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
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.URL;
import java.net.URLConnection;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
static ProgressBar status;
static URL url;
public MainFrame() {
// Set up the content pane.
Container contentPane = this.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
jButton.setText("Test");
jButton.setActionCommand("Test");
jButton.addActionListener(this);
contentPane.add(jButton);
setup();
}
private void setup() {
Toolkit tk;
Dimension screenDims;
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void downloadExecutable(String str) {
url = null;
try {
url = new URL("http://pegr-converter.com/download/test.jpg");
} catch (MalformedURLException exc) {
JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
return;
}
if (url != null) {
String[] options = { "OK", "Change", "Cancel" };
int response = JOptionPane.NO_OPTION;
File selectedFolder = new File(getDownloadDir());
File selectedLocation = new File(selectedFolder, str + ".jpg");
while (response == JOptionPane.NO_OPTION) {
selectedLocation = new File(selectedFolder, str + ".jpg");
String msgStr = str + ".jpg will be downloaded to the following location:\n"
+ selectedLocation.toPath();
response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (response == JOptionPane.NO_OPTION) {
// Prompt for file selection.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(selectedFolder);
fileChooser.showOpenDialog(null);
selectedFolder = fileChooser.getSelectedFile();
}
}
if (response == JOptionPane.YES_OPTION) {
int size = 0;
URLConnection conn;
try {
conn = url.openConnection();
size = conn.getContentLength();
} catch (IOException exc) {
System.out.println(exc.getMessage());
}
//System.out.println("javax.swing.SwingUtilities.isEventDispatchThread=" + javax.swing.SwingUtilities.isEventDispatchThread());
File destination = new File(selectedFolder, str + ".jpg");
status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
try {
FileUtils.copyURLToFile(url, destination, 10000, 300000);
} catch (IOException exc) {
JOptionPane.showMessageDialog(null, "Download failed.");
}
return null;
}
public void done() {
status.close();
}
};
worker.execute();
}
}
}
public static String getDownloadDir() {
String home = System.getProperty("user.home");
File downloadDir = new File(home + "/Downloads/");
if (downloadDir.exists() && !downloadDir.isDirectory()) {
return home;
} else {
downloadDir = new File(downloadDir + "/");
if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
return downloadDir.getPath();
} else {
return home;
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
downloadExecutable("test");
}
}
This worked beautifully.
Question I have is I am trying to update my gui with a timer(this works and changes the image for mypic but, it will not update mytext label for some weird reason any help would be very much appreciated!
*I should add that mytext isn't showing up at all on my gui since introducing the timer...but mypic does????
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by xxxxxxzz on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = null;
JLabel mypic = null;
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
//Tried setting it like this and still doesn't work
// myText = new JLabel("HOT");
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
UPDATE with suggestions still isn't working..
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by jsnow on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = new JLabel();
JLabel mypic = new JLabel();
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
Here's a working solution which you can tailor to your use. The cause seemed to be the way you had tried to display the Components rather than the code in your action listener.
Your approach was just replacing myText with myPic when you initially set up the JFrame. Instead you need to use a layout manager. The example I've given is with overlaying using JLayeredPane. You may wish to use a layout manager instead if this is not the desired outcome, see the Oracle Tutorial on using layout managers.
Widget class
package widget;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Widget extends JFrame {
private static final int UPDATE_TICK = 5_000;
private static final int WIDGET_WIDTH = 150;
private static final int WIDGET_HEIGHT = 150;
private JLabel myText = new JLabel();
private JLabel myPic = new JLabel();
private Weather weather = new Weather();
private Timer simpleTimer;
public void createAndShow() {
setUndecorated(true);
setSize(WIDGET_WIDTH, WIDGET_HEIGHT);
Shape shape = new Ellipse2D.Float(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
// AWTUtilities.setWindowShape(this, shape);
setShape(shape); // do this instead
myText.setHorizontalAlignment(JLabel.CENTER);
myPic.setHorizontalAlignment(JLabel.CENTER);
JLayeredPane layered = new JLayeredPane();
myText.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
myPic.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
layered.add(myPic, 1, 0);
layered.add(myText, 2, 0);
add(layered);
simpleTimer = new Timer(UPDATE_TICK, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
update();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
simpleTimer.start();
}
private void update() {
myText.setText(weather.getTemp());
myPic.setIcon(new ImageIcon(weather.getImage(WIDGET_WIDTH, WIDGET_HEIGHT)));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Widget w = new Widget();
w.createAndShow();;
}
});
}
}
Weather class for demonstration purposes
package widget;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Weather {
private static final Random rand = new Random();
private static final Color[] randColors = {Color.YELLOW,
Color.GREEN,
Color.WHITE};
public String getTemp() {
return Integer.toString(rand.nextInt(100));
}
public BufferedImage getImage(int width, int height) {
int colorIndex = rand.nextInt(randColors.length);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.setRGB(x, y, randColors[colorIndex].getRGB());
}
}
return img;
}
}
I've been wondering if for example:
JTextPane chatTextArea = new JTextPane();
s.replaceAll(":\\)", emoticon());
public String emoticon(){
chatTextArea.insertIcon(new ImageIcon(ChatFrame.class.getResource("/smile.png")));
return "`";
}
can put a picture and a "`" everywhere ":)" is found. When I run it like this if s contains a ":)" then the whole s gets replaced just by the icon.
Is there a way to do it?
Here is a small example I made (+1 to #StanislavL for the original), simply uses DocumentListener and checks when a matching sequence for an emoticon is entered and replaces it with appropriate image:
NB: SPACE must be pressed or another character/emoticon typed to show image
import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;
public class JTextPaneWithEmoticon {
private JFrame frame;
private JTextPane textPane;
static ImageIcon smiley, sad;
static final String SMILEY_EMOTICON = ":)", SAD_EMOTICON = ":(";
String[] emoticons = {SMILEY_EMOTICON, SAD_EMOTICON};
private void initComponents() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
//add docuemntlistener to check for emoticon insert i.e :)
((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(final DocumentEvent de) {
//We should surround our code with SwingUtilities.invokeLater() because we cannot change document during mutation intercepted in the listener.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
StyledDocument doc = (StyledDocument) de.getDocument();
int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1));
int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength());
String text = doc.getText(start, end - start);
for (String emoticon : emoticons) {//for each emoticon
int i = text.indexOf(emoticon);
while (i >= 0) {
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start + i).getAttributes());
if (StyleConstants.getIcon(attrs) == null) {
switch (emoticon) {//check which emtoticon picture to apply
case SMILEY_EMOTICON:
StyleConstants.setIcon(attrs, smiley);
break;
case SAD_EMOTICON:
StyleConstants.setIcon(attrs, sad);
break;
}
doc.remove(start + i, emoticon.length());
doc.insertString(start + i, emoticon, attrs);
}
i = text.indexOf(emoticon, i + emoticon.length());
}
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {//attempt to get icon for emoticons
smiley = new ImageIcon(ImageIO.read(new URL("http://facelets.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/e/m/emoticons0001.png")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
sad = new ImageIcon(ImageIO.read(new URL("http://zambia.primaryblogger.co.uk/files/2012/04/sad.jpg")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTextPaneWithEmoticon().initComponents();
}
});
}
}
References:
How to add smileys in java swing?
How to solve run time exception of this code ?
when click button file chooser and add file from it the panel color Disappear (wrong thing happen in panel)
This is my code:
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.border.BevelBorder;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
public class pan extends JPanel implements DropTargetListener {
private DefaultListModel listModel = new DefaultListModel();
private DropTarget dropTarget;
private JScrollPane droparea;
private JList list;
private JButton addbutton;
// Create the panel.
//and add to it component
public pan() {
setLayout(null);
addbutton = new JButton("New button");
addbutton.setBounds(10, 10, 90, 100);
addbutton.addActionListener(new Action());
add(addbutton);
list = new JList();
dropTarget = new DropTarget(list, this);
list.setModel(listModel);
list.setDragEnabled(true);
FileListCellRenderer renderer = new FileListCellRenderer();
list.setCellRenderer(renderer);
list.addMouseListener(new mouselistner());
list.clearSelection();
list.setFixedCellHeight(40);
droparea = new JScrollPane();
droparea.setViewportView(list);
droparea.setBounds(10, 150, 635, 330);
add(droparea);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
public void dragEnter(DropTargetDragEvent arg0) {
// nothing
}
public void dragOver(DropTargetDragEvent arg0) {
// nothing
}
public void dropActionChanged(DropTargetDragEvent arg0) {
// nothing
}
public void dragExit(DropTargetEvent arg0) {
// nothing
}
public void drop(DropTargetDropEvent evt) {
int action = evt.getDropAction();
evt.acceptDrop(action);
try {
Transferable data = evt.getTransferable();
if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> files = (List<File>) data
.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : files) {
listModel.addElement(file);
}
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
evt.dropComplete(true);
}
}
/** A FileListCellRenderer for a File. */
class FileListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = -7799441088157759804L;
private FileSystemView fileSystemView;
private JLabel label;
private Color textSelectionColor = Color.BLACK;
private Color backgroundSelectionColor = Color.CYAN;
private Color textNonSelectionColor = Color.BLACK;
private Color backgroundNonSelectionColor = Color.WHITE;
FileListCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean selected, boolean expanded) {
label.setBorder(new BevelBorder(BevelBorder.RAISED,
Color.LIGHT_GRAY, Color.GRAY, null, null));
File file = (File) value;
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(Color.blue);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
class Action implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==addbutton){
// FileSystemView fsv=FileSystemView.getFileSystemView();
JFileChooser filechooser=new JFileChooser();
filechooser.setMultiSelectionEnabled(true);
filechooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
File files=filechooser.getSelectedFile();
filechooser.showDialog(null, "add"); //here panel problem i think
listModel.addElement(files); //and here run time error genrate
}
}
}
}
The two problem on the 2 last line
The problem is that you get the selected files before you show your JFileChooser dialog, so the selected files will be null. Swap these 2 lines to get:
int returnValue = filechooser.showDialog(null, "add");
if (returnValue == JFileChooser.APPROVE_OPTION) {
File files = filechooser.getSelectedFile();
listModel.addElement("fooooo");
}
Also better to use a return value for the JFileChooser in the event that the cancel button is clicked.