i am making simple graphics editor, and on the beggining ive got a problem.
I am doing double windows program, i want to click button in one window, choose path of the image, and after that image appear on the second window. I ve done almost everything, but it looks like that: i start the program nothing appears in second window, i read image and it doesnt appear on the second window, it looks like i need something to refresh second window after i read image, but i dont know how to do that, please help.
I know that there is repaint() method, but i dont know how to use repaint in one window and force it to repaint the second one
First file:
package edytor;
import java.awt.*;
import javax.swing.*;
public class Edytor extends JFrame {
public static boolean pom, pom1;
public static Image obraz;
public static String sciezka;
public Edytor() {
super("Edytor 2D");
setBounds(420,50,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
CObrazek obraz = new CObrazek();
con.add(obraz);
przybornik przyb = new przybornik();
pom = false;
pom1=false;
Edytor.obraz = new ImageIcon(Edytor.sciezka).getImage();
setVisible(true);
}
public static void main(String args[]) {
new Edytor();
}
}
class CObrazek extends Canvas {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(Edytor.obraz, 0,0,null);
g2d.drawString("Wsp x: " , 300, 400);
}
}
Second file:
package edytor;
import java.io.*;
import javax.swing.*;
public class przybornik extends javax.swing.JFrame {
public przybornik() {
initComponents();
setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
read_but = new javax.swing.JButton();
save_but = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
read_but.setText("Wczytaj");
read_but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
read_butActionPerformed(evt);
}
});
save_but.setText("Zapisz");
save_but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
save_butActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(read_but, javax.swing.GroupLayout.PREFERRED_SIZE,
184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(save_but, javax.swing.GroupLayout.DEFAULT_SIZE,
178, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(read_but)
.addComponent(save_but))
.addContainerGap(266, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void read_butActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new
File(System.getProperty("user.home")));
int path = fileChooser.showOpenDialog(this);
if (path == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
Edytor.sciezka = selectedFile.getAbsolutePath();
}
System.out.print(Edytor.sciezka);
}
private void save_butActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(przybornik.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() {
new przybornik().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton read_but;
private javax.swing.JButton save_but;
// End of variables declaration
}
I just show you the places I changed and added.
EDIT:
public class Edytor extends JFrame{
CObrazek obraz = new CObrazek();//here (new place)
public static boolean pom, pom1;
public static Image image;
public static String sciezka;
public void EdytorShow(String image_path) {//changed
setBounds(420,50,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
//CObrazek obraz = new CObrazek();//disabled
przybornik przyb = new przybornik();//here (new place)
/**
* We do not want the window to appear without selecting an image.
* For this reason we will use "if"
*/
if(!image_path.equals("null")){
con.add(obraz);
// przybornik przyb = new przybornik();//Moved out of if ;)
pom = false;
image = new ImageIcon(image_path).getImage();
setVisible(true);
}//if
}
public static void main(String args[]) {
Edytor et = new Edytor();
et.EdytorShow("null");
}
}
And in the "przybornik.java" file:
private static boolean isWindowActive = false; //for window active.
public przybornik() {
initComponents();
if(isWindowActive == false){ //window active check here.
setVisible(true);
isWindowActive = true;
}
}
//-------- and:
Edytor edytor = new Edytor();//here (new place)
private void read_butActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new
File(System.getProperty("user.home")));
int path = fileChooser.showOpenDialog(this);
if (path == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
//Edytor.sciezka = selectedFile.getAbsolutePath();
//new Edytor().EdytorShow(selectedFile.getAbsolutePath());//disabled(Moved out of function ;)
edytor.EdytorShow(selectedFile.getAbsolutePath());//newly added
}
System.out.print(Edytor.sciezka);
}
Related
I am trying to update a JTextBox with data from a serial port in java swing. The problem I am facing is that the JTextBox is not getting updated.
I tried repaint() and revalidate functions also but not use. I also tried putting the setText() inside a runnable. Nothing works. Please guide me in this.
public class PrinterUI extends javax.swing.JFrame{
/**
* Creates new form PrinterUI
*/
public PrinterUI() {
initComponents();
initOtherUI();
}
public void initOtherUI(){
menu = new ArrayList<javax.swing.JMenuItem>();
}
public void showSensorValueOnScreen(long id, int pres, int temp){
System.out.println(Long.toHexString(id));
sensorID = id;
System.out.println(Long.toHexString(sensorID));
opText.setText(Long.toHexString(sensorID));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenu3 = new javax.swing.JMenu();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
opText = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
printerMenuBar = new javax.swing.JMenu();
mobileMenuBar = new javax.swing.JMenu();
jMenu3.setText("jMenu3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Print");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jLabel1.setText("Sensor Output");
opText.setText("jTextField1");
opText.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
opTextPropertyChange(evt);
}
});
printerMenuBar.setText("Printer");
printerMenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
printerMenuBarMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
printerMenuBarMouseEntered(evt);
}
});
jMenuBar1.add(printerMenuBar);
mobileMenuBar.setText("Mobile");
jMenuBar1.add(mobileMenuBar);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jButton1))
.addContainerGap(236, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(108, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(jButton1)
.addGap(105, 105, 105))
);
getAccessibleContext().setAccessibleName("jLabel1");
pack();
}// </editor-fold>
private void printerMenuBarMouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("clicked");
}
private void printerMenuBarMouseEntered(java.awt.event.MouseEvent evt) {
String[] portNames = null;
portNames = SerialPortList.getPortNames();
for (String string : portNames) {
System.out.println(string);
}
if (portNames.length == 0) {
System.out.println("There are no serial-ports");
} else {
SerialPort serialPort = new SerialPort("COM25");
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
PortReader portReader = new PortReader(serialPort);
serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
} catch (Exception e) {
System.out.println("There are an error on writing string to port т: " + e);
}
}
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
System.out.println("Print Click");
opText.setText(Long.toString(sensorID));
System.out.println(Long.toHexString(sensorID));
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrinterUI.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() {
new PrinterUI().setVisible(true);
}
});
}
private List<javax.swing.JMenuItem> menu;
PrintService pservice = null;
public static long sensorID;
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu mobileMenuBar;
private javax.swing.JTextField opText;
private javax.swing.JMenu printerMenuBar;
// End of variables declaration
}
class PortReader implements SerialPortEventListener{
SerialPort serialPort;
public int[] incomingData = new int[20];
public int dataIndex=0;
public long sensorID=0;
public int pressure;
public int temperature;
public PortReader(SerialPort serialPort) {
this.serialPort = serialPort;
}
#Override
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readHexString();
for(int x=0;x<receivedData.length();x=x+2){
int data = Integer.parseInt(receivedData.substring(x, x+2),16);
//System.out.println(data);
if((dataIndex==0)&&(data==170)){
incomingData[dataIndex++]=data;
}else if(dataIndex>0){
incomingData[dataIndex++]=data;
if(dataIndex>=14){
dataIndex=0;
long tyreId =(long)(((int)incomingData[6])*16777216 + ((int)incomingData[7])*65536 + ((int)incomingData[8])*256 + ((int)incomingData[9]));
tyreId = tyreId & 0x00000000FFFFFFFFL;
int press = incomingData[10];
int temp = incomingData[11];
sensorID = tyreId;
pressure = press;
temperature = temp;
PrinterUI obj = new PrinterUI();
obj.showSensorValueOnScreen(sensorID, pressure, temperature);
System.out.println("ID: " + Long.toHexString(tyreId) + ", Pressure: " + pressure + ", Temperature: " + temperature);
}
}else{
dataIndex=0;
}
}
} catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
When a serial data is received, serialEvent is called in PortReader class which in turn calls the showSensorValueOnScreen() method in the PrinterUI class. The JTextBox widget doesnt gets updated.
But when a button on the UI is pressed, the JTextBox gets updated.
Why doesnt it get updated when I call it from outside the class?. Please help me out here.
I found out the issue. I am trying to update the UI from another class by creating a new object for the UI. The actual UI was created from void main using a different object.
I resolved it by passing the existing object to the class that was calling the UI update function.
Thank you for your help people.
I'm trying to implement a JprogressBar to show the data insertion progress.
Basically the user select how many data sources will be imported to database.
With this parameter the main program Start a method to list those parameters and with a foreach loop it calls the insertion Thread and the ProgressBar update Thread.
for (Maquina i : m.listar()) {
//Passing to Import Thread the object with the data and a Date parameter
ImportarDados imp = new ImportarDados(i, jDateInicial.getDate());
//Calling progress bar update Thread with the progressbar itself and progress parameter
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
}
The threads kinda work on their own, but the result is not the one I want, cause the data is being imported and the progressbar is being updated, but it is being update to 100% after all data is imported. I need to update the progress bar as long as the import thread finish the importation for each (Maquina i) object.
If it is necessary I can provide the threads code...but i don't know if this calling method can provide the result I want. Searching on the forum i found something about EDT and i think it is the problem that the bar is not being updated. Can you guys help me solving this?
Minimal and Verifiable example:
My code is pretty short. The code generated by netbeans is huge, sry for that.
That code simulate my problem. The windows is refreshed only after the for loop is finished. But the BarraDeProgresso thread is running at the same as and SysOut some info...
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class Minimo extends javax.swing.JFrame {
public Minimo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int progImportacao[] = {0};
progresso.setMaximum(15);
for (int i = 0; i <= 15; i++) {
ImportarDados imp = new ImportarDados(i,lblProgresso);
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
progImportacao[0] += 1;
}
}
Component Initialization (Netbeans Generated)
private void initComponents() {
progresso = new javax.swing.JProgressBar();
lblProgresso = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblProgresso.setText("...");
jButton1.setText("IMPORT DATA");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblProgresso)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(47, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(191, 191, 191))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addComponent(lblProgresso)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37))
);
pack();
}// </editor-fold>
Runnable classes
class BarraDeProgresso implements Runnable {
public JProgressBar jProgressBar1;
public int progresso[];
public BarraDeProgresso(JProgressBar barra, int progresso[]) {
this.jProgressBar1 = barra;
this.progresso = progresso;
}
#Override
public void run() {
try {
Thread.sleep(0);
System.out.println("TBARRA PROG " + progresso[0]);
jProgressBar1.setValue(progresso[0]);
jProgressBar1.repaint();
} catch (InterruptedException e) {
}
}
}
class ImportarDados implements Runnable {
private int pi = 0;
JLabel x;
public ImportarDados(int i, JLabel tag) {
this.pi = i;
this.x = tag;
}
#Override
public void run() {
try {
Thread.sleep(500);
x.setText(Integer.toString(pi)+" /15");
} catch (InterruptedException ex) {
Logger.getLogger(Minimo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Main (Netbeans Generated)
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Minimo.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() {
new Minimo().setVisible(true);
}
});
}
Your current code creates no background thread. Yes you've got Runnables, but you call run() on them, meaning you are calling them on the Swing event thread. When you do this, you block the event thread, effectively freezing your program. Instead, you need to:
Create a true background thread by passing your Runnable into a Thread object's constructor and calling start() on that Thread.
Not mutate Swing components from within these background threads
Or use a SwingWorker as per the Lesson: Concurrency in Swing which will help solve both of the above issues.
For an example of use of a SwingWorker, please see:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Minimo2 extends JPanel {
private static final int EB_GAP = 15;
private static final int PROG_BAR_WDTH = 400;
public static final int MAX_DATA = 15;
private JProgressBar progresso;
private JLabel lblProgresso;
private JButton jButton1;
private Action importDataAction = new ImportDataAction("Import Data");
public Minimo2() {
initComponents();
}
private void initComponents() {
progresso = new JProgressBar(0, MAX_DATA);
lblProgresso = new JLabel(" ");
jButton1 = new JButton(importDataAction);
int progBarHeight = progresso.getPreferredSize().height;
progresso.setPreferredSize(new Dimension(PROG_BAR_WDTH, progBarHeight));
progresso.setStringPainted(true);
JPanel btnPanel = new JPanel();
btnPanel.add(jButton1);
JPanel labelPanel = new JPanel();
labelPanel.add(lblProgresso);
JPanel progressPanel = new JPanel();
progressPanel.add(progresso);
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(btnPanel);
add(Box.createVerticalStrut(EB_GAP));
add(labelPanel);
add(Box.createVerticalStrut(EB_GAP));
add(progressPanel);
}
private class ImportDataAction extends AbstractAction {
public ImportDataAction(String name) {
super(name); // give the button text
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic); // give it a hot key
}
#Override
public void actionPerformed(ActionEvent e) {
setEnabled(false); // disable our button
ImportDataWorker worker = new ImportDataWorker(MAX_DATA);
worker.addPropertyChangeListener(new WorkerListener());
worker.execute();
}
}
private class WorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progValue = (int) evt.getNewValue();
progresso.setValue(progValue);
String text = String.format("%02d/15", progValue);
lblProgresso.setText(text);
} else if ("state".equals(evt.getPropertyName())) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
#SuppressWarnings("rawtypes")
SwingWorker worker = (SwingWorker)evt.getSource();
try {
worker.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
progresso.setValue(MAX_DATA);
String text = String.format("%02d/15", MAX_DATA);
lblProgresso.setText(text);
importDataAction.setEnabled(true);
}
}
}
}
private class ImportDataWorker extends SwingWorker<Void, Void> {
private static final long SLEEP_TIME = 500;
private int max;
public ImportDataWorker(int max) {
this.max = max;
}
#Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < max; i++) {
setProgress(i);
Thread.sleep(SLEEP_TIME);
}
return null;
}
}
private static void createAndShowGui() {
Minimo2 mainPanel = new Minimo2();
JFrame frame = new JFrame("Minimo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I am trying to make a simple Java GUI that allows you to enter a time, and once the time runs out, it plays a sound. For some reason I find an error despite looking a many different sources that all tell me to use Timer or Handler. Here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author CIS
*/
import java.io.*;
import sun.audio.*;
import java.util.TimerTask;
public class Timer extends javax.swing.JFrame {
public Timer() {
initComponents();
initEditable();
}
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop1 = null;
AudioPlayer ABC = AudioPlayer.player;
AudioStream ABCD;
AudioData ABCDE;
ContinuousAudioDataStream loop2 = null;
public void initEditable(){
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textFieldTimer = new javax.swing.JTextField();
buttonTest = new javax.swing.JButton();
buttonSet = new javax.swing.JButton();
labelTimeRemaining = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonTest.setText("Test Sound");
buttonTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTestActionPerformed(evt);
}
});
buttonSet.setText("Set");
buttonSet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSetActionPerformed(evt);
}
});
labelTimeRemaining.setText("time remaing");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(textFieldTimer)
.addComponent(buttonTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonSet)
.addComponent(labelTimeRemaining)))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonSet, buttonTest, labelTimeRemaining, textFieldTimer});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldTimer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTimeRemaining))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTest)
.addComponent(buttonSet)))
);
pack();
}// </editor-fold>
int hello = 1000;
public void music1(){
ContinuousAudioDataStream loop = null;
try
{
InputStream alert = new FileInputStream("alert.wav");
BGM = new AudioStream(alert);
AudioPlayer.player.start(BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD)
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop1);
}
private void buttonSetActionPerformed(java.awt.event.ActionEvent evt) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
music1();
}
}, 2000);
}
private void buttonTestActionPerformed(java.awt.event.ActionEvent evt) {
music1();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Timer.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() {
new Timer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonSet;
private javax.swing.JButton buttonTest;
private javax.swing.JLabel labelTimeRemaining;
private javax.swing.JTextField textFieldTimer;
// End of variables declaration
}
When I get to the line new Timer().schedule(new TimerTask() {
I get on error on the schedule.
I apologize if my method of presenting my problem is incorrect, I'm new here and new to Java programming as well.
Your class has the same name as the java.util.Timer class. You must disambiguate by fully qualifying that class name:
new java.util.Timer().schedule(new TimerTask() {
I can't get this to work:
public void ru() throws InterruptedException {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
}
private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
try {
ru();
} catch (InterruptedException ex) {
}
}
Any solutions?
I want a jLabel to show a slide show when a mouse enters a certain button and stays like that as long as the mouse is still in a button. If the mouse happens to exit the button, the jlabel will return to a null state. (no more anything.) Is that possible? Please help. I also tried using for statement but no good. I'm using netbeans by the way.
First thing you need to implement a javax.swing.Timer. Trying to call Thread.sleep() will block the Event Dispatch Thread. See How to use Swing Timers. Here is the basic construct
Timer(int delay, ActionListener listener)
where delay is the time in milliseconds you want delayed and the listener will listen for the Timer ActionEvent fired every delay milliseconds.
So you want something like this
public class MyFrame extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[3];
int index = -1;
public MyFrame() {
initComponents();
icons[0] = new ImageIcon(...);
icons[1] = new ImageIcon(...);
icons[2] = new ImageIcon(...);
timer = new Timer(2000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (index + 1 > 2) {
index = 0;
jLabel3.setIcon(icons[index]);
} else {
index++;
jLabel3.setIcon(icons[index]);
}
}
});
}
}
For your button, you need to use mouseEntered and mouseExited, then you can just call timer.start() or timer.stop()
private void jButton1MouseExited(MouseEvent e) {
timer.stop();
}
private void jButton1MouseEntered(MouseEvent e) {
timer.start();
}
If you don't know how to add the MouseListener just right click on the button from the design view and select Event -> Mouse -> mouseEntered. Do the same for mouseExited. You should see the above methods auto-generated for you.
UPDATE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class ImageViewer extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[5];
int index = -1;
public ImageViewer() {
initComponents();
try {
icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index + 1 > 4) {
index = 0;
jLabel1.setIcon(icons[index]);
} else {
index++;
jLabel1.setIcon(icons[index]);
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new JButton();
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
jButton1MouseEntered(evt);
}
public void mouseExited(MouseEvent evt) {
jButton1MouseExited(evt);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>
private void jButton1MouseEntered(MouseEvent evt) {
timer.start();
}
private void jButton1MouseExited(MouseEvent evt) {
timer.stop();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageViewer.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() {
new ImageViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JButton jButton1;
private JLabel jLabel1;
// End of variables declaration
}
You want to add a MouseAdapter to the JLabel and use its mouseEntered() and mouseExited() as follows:
jLabel3.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
} catch(InterruptedException e) {
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
//whatever you mean by "null state"
}
});
I found on the Web code: http://java-sl.com/tip_autoreplace_smiles.html which I edited to my own needs, take a look:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Emotes extends JEditorPane {
public Emotes() {
super();
this.setEditorKit(new StyledEditorKit());
this.initListener();
}
private void replace (String text, StyledDocument doc, ImageIcon icon, int start, String what) throws BadLocationException
{
int i = text.indexOf(what);
while(i >= 0)
{
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
if (StyleConstants.getIcon(attrs) == null)
{
StyleConstants.setIcon(attrs, icon);
doc.remove(start+i, what.length());
doc.insertString(start+i,what, attrs);
}
i = text.indexOf(what, i+what.length());
}
}
private void initListener() {
getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent event) {
final DocumentEvent e=event;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (e.getDocument() instanceof StyledDocument) {
try {
StyledDocument doc=(StyledDocument)e.getDocument();
int start= Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
String text=doc.getText(start, end-start);
replace(text, doc, createEmoticon("wink.png"), start, ";)");
replace(text, doc, createEmoticon("wink.png"), start, "<wink>");
replace(text, doc, createEmoticon("sad.png"), start, ":(");
replace(text, doc, createEmoticon("sad.png"), start, "<sad>");
replace(text, doc, createEmoticon("smile.png"), start, ":)");
replace(text, doc, createEmoticon("smile.png"), start, "<smile>");
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
}
static ImageIcon createEmoticon(String icon)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File(icon));
Graphics g = img.getGraphics();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}catch (IOException ex)
{
}
return new ImageIcon(img);
}
}
which works great. But I created in Netbeans a new GUI (JDialog Window) with JEditorPane on it, where I want to use this feature on JDialog window:
but it doesnt want to work at all. When I type ":)" its not changing in an image.
Just try to run that code:
public class NewJDialog extends javax.swing.JDialog {
/** Creates new form NewJDialog */
public NewJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jEditorPane1 = new Emotes();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jScrollPane1.setViewportView(jEditorPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
And the emotes I use are:
An application is compiled to a .jar file. Normal File I/O then does not take (the current directory varies depending on the call). Take the images out of the jar/class path as:
img = ImageIO.read(Emotes.class.getResourceAsStream(icon));