How to Play .wav File with JButton? - java

So recently, I have been trying to make my own Mario game (for myself, possibly to show my other friends). Games include buttons. When I click on a button in other games, it plays a sound. I would love to add that feature to my game. The problem is, it doesn't play. My source code is:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JButtonClick {
JButton test = new JButton("Click Me!");
JPanel panel = new JPanel();
public void playSound(String soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
public JButtonClick() {
JFrame frame = new JFrame("Button-Click test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.add(panel);
frame.setSize(800, 600);
frame.setResizable(true);
frame.setVisible(true);
panel.add(test);
test.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
playSound("JButton.wav");
}
});
}
public static void main(String[] args) {
new JButtonClick();
}
}
My .wav file is in the same package as this class. But instead of it playing the sound I want, it just says this:
java.io.FileNotFoundException: C:\Users\diego\workspace\Super Mario Bros 1\JButton.wav (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at JButtonClick.playSound(JButtonClick.java:21)
at JButtonClick$1.actionPerformed(JButtonClick.java:49)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
What am I doing wrong?!

Here is the problem due to placement of your .wav file.
As per your question your have placed it in the same package as this class that's why you are getting FileNotFoundException.
Let me explain you how new File(pathname) works:
Javadoc about File says:
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory.
It you are running this application in eclipse then place .wav file directly in the project (outside src folder) as shown below:
AudioSystem.getAudioInputStream(new File("Jbutton.wav"));
You can try also by placing it in resource folder.
AudioSystem.getAudioInputStream(new File("resources/Jbutton.wav"));

custom sounds play...using NetBeans..
First of all import some package or class name like this
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
Not working because generate Error on java.lang.NullPointerException
URL url = getClass().getResource("\\dbmsystem\\src\\sound\\Your_sound_name.wav");
URL url = getClass().getResource("G:\\zala\\dbmsystem\\src\\sound\\Your_sound_name.wav");
But Proper Working like this
URL url = getClass().getResource("/sound/Your_sound_name.wav");
AudioClip clip = Applet.newAudioClip(url);
clip.play();

Related

Save Word-file with Java (runnable JAR)

I´m trying to build an application which can read information from Excel files and place the data into a document. The document is a form of a template with columns in. Everything works just fine until the saving part.
It work, almost, like it should when I run the program directly in IntelliJ. However, when I install the application to an runnable JAR with Maven - the JAR won't work.
The file is saved as desired... But the new file contains nothing if I run the application from JAR. When i run directly in IntelliJ, the new file is been created and opened, but of 3 columns / row, only 2 has data in it.
What can I do?
Link to template document
http://www.labelmedia.de/englisch/doc/70%20x%2032%20mm%20-%20Art.%2088%2010%2027%2070%2032.doc
Thank you in advanced
package utils;
import model.Customers;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class WriteToDocument {
String TARGET_FILE = "src\\main\\java\\utils\\template\\template.doc";
private int postInList = 0;
public WriteToDocument() {}
public WriteToDocument(ArrayList<Customers> list) throws IOException {
list.remove(0);
HWPFDocument doc = null;
try {
doc = openDocument(TARGET_FILE);
Range range = doc.getRange();
TableIterator itr = new TableIterator(range);
while (itr.hasNext()) {
Table table = itr.next();
for (int rowIndex = 0; rowIndex < table.numRows(); rowIndex++) {
TableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.numCells(); colIndex++) {
TableCell cell = row.getCell(colIndex);
//WRITE IN TABLE //
if (postInList < list.size()) {
cell.getParagraph(0).replaceText(list.get(postInList).getName() + "\n\r" +
"\n\r" + list.get(postInList).getAddress() + "\n\r" +
list.get(postInList).getPostcode() + " " + list.get(postInList).getCity(), false);
postInList++;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
saveDocument(doc);
}
}
private HWPFDocument openDocument(String file) throws Exception {
System.out.println("OPEN");
return new HWPFDocument(new POIFSFileSystem(new FileInputStream(file)));
}
private static void saveDocument(HWPFDocument doc) throws IOException {
System.out.println("SAVE");
try (FileOutputStream out = new FileOutputStream(new File("test.doc"))) {
doc.write(out);
out.flush();
System.out.println("File saved");
doc.close();
out.close();
Desktop dt = Desktop.getDesktop();
dt.open(new File("test.doc"));
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
Stacktrace
java.io.FileNotFoundException: src\main\java\utils\template\template.doc (Det går inte att hitta sökvägen)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at utils.WriteToDocument.openDocument(WriteToDocument.java:56)
at utils.WriteToDocument.<init>(WriteToDocument.java:25)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
SAVE
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at utils.WriteToDocument.saveDocument(WriteToDocument.java:62)
at utils.WriteToDocument.<init>(WriteToDocument.java:49)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Most probably you are missing libraries when it is exported as a JAR. You are using Apache POI as external libraries. Inside the IDE all the libraries were applied but when exported, they seems to be missing. Just run the jar file from command prompt to be 100% clear about the issue. In IDEs like NetBeans the libraries are exported into a separate folder called lib have a look for similar related to your IDE as well.

Move a file to a specific folder

I'm trying to move a file to a specified folder but I can't.
This is the code:
public static void moveToRightDirectory(File song, String album) throws IOException {
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
String pathDirectory = selectedDir + "\\" + album;
File dir = new File(pathDirectory);
System.out.println("dir.exists(): " + dir.exists());
if(dir.exists()) {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
}
else {
boolean success = (new File(pathDirectory)).mkdirs();
if(!success) {
System.out.println("Error creating directory.");
}
else {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
//FileUtils.moveFile(song, dir);
}
}
}
I know there are other message about this (from these I was inspired) but I wasn't able to solve so I would ask for your help.
I would like to move the song file in the folder dir. To do this I have tried several methods:
Files.move -> The following errors are generated:
Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Trailing char < > at index 55: C:\Users...\dir
at sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at java.io.File.toPath(Unknown Source)
at createDir.CreateDirectory.moveToRightDirectory(CreateDirectory.java:73)
at createDir.CreateDirectory.createDirectory(CreateDirectory.java:40)
at gui.DirChooser.actionPerformed(DirChooser.java:54)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
song.renameTo(dir) -> It does nothing.
FileUtils.moveFile(song, dir); -> Eclipse does not find FileUtils. I did the import of java.lang.Object.org.apache.commons.io.FileUtils but the error becomes "The import java.lang.Object.org can not be resolved."
How can I fix?
Thanks a lot.
Not an answer to the actual question, but, based on the error message
java.nio.file.InvalidPathException: Trailing char < > at index 55:
I'm guessing your code isn't getting rid of the trailling whitespaces properly.
Try
album = album.trim();
Instead of
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
Maybe this will be of assistance
Step 1 : Rename File
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Step 2: Copy and delete
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}

Chat connection doesn't work

So I am trying to make a simple chat client but somehow the connection doesn't work. Can you help me? This is what i wrote:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class game implements ActionListener{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String [] args){
game g = new game();
g.go();
}public void go(){
JFrame frame = new JFrame("Chat");
JButton sendB = new JButton("Send");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane s = new JScrollPane(incoming);
s.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
s.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(25);
sendB.addActionListener(this);
mainPanel.add(s);
mainPanel.add(outgoing);
mainPanel.add(sendB);
setUpnetworking();
Thread readerThread = new Thread( new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setVisible(true);
frame.setSize(800,500);
frame.setResizable(false);
}public void actionPerformed(ActionEvent e){
try{
writer.println(outgoing.getText());
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}public void setUpnetworking(){
try {
sock = new Socket("127.0.0.1", 5000 );
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
} catch (IOException exx) {
exx.printStackTrace();
}
}public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while ((message = reader.readLine()) != null){
System.out.println("read" + message);
incoming.append(message + "\n");
}
}catch (Exception exx){exx.printStackTrace();}
}
}
}
errors i got when i ran it:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at game.setUpnetworking(game.java:66)
at game.go(game.java:45)
at game.main(game.java:18)
java.lang.NullPointerException
at game$IncomingReader.run(game.java:79)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at game.actionPerformed(game.java:57)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
i really don't know what's the problem :( can someone help me so i can build a working Chat Client? I use Eclipse.
Sorry for bad Englisch, I am from The Netherlands
For a chat app you need both backend and client-side solutions.
To skip the part with server-side solution development you can use a ready backend and SDK provided by some platforms. That should save you a lot of time and effort and you will be able to concentrate on UI implementation.
Here are some providers you might consider using:
ConnectyCube
Firebase
Sendbird
Layer
Here is also an article comparing features provided by some of them.
You really need to build a server. You would need to go through networking a bit. But just in case you need a server, I made one few months back. Run it separately. See if you can make it work.
https://github.com/DhavalKapil/ForwardingServer

How to choose file and then submit in Java swing?

The UI has two buttons, browse and submit. I want the user to hit browse to find a file, and then submit to copy it to a different location. However whenever I attempt it, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at me.trevor1134.modinjector.ModInjector$3.actionPerformed(ModInjector.java:154)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
"Submit" button actionPerformed :
#Override
public void actionPerformed(ActionEvent arg0) {
if (mod.exists()) { //line 154 mod is a file object
OS = System.getProperty("os.name").toLowerCase();
detectOS();
modLocation = new File(fullPath);
if (modLocation.exists() && modLocation.isDirectory()) {
Path newP = modLocation.toPath();
Path oldP = mod.toPath();
try {
Files.copy(oldP, newP);
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(frame, "Mod successfully copied to: "
+ fullPath);
System.out.println("Mod successfully copied to: " + fullPath);
}
}
}
Browse button code:
#Override
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser(homePath + "\\Downloads");
FileNameExtensionFilter filter = new FileNameExtensionFilter("ZIP & JAR Files",
"zip", "jar");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File mod = fc.getSelectedFile();
textField.setText(mod.getAbsolutePath());
System.out.println("File: " + mod.getName());
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
I basically want the variable mod to carry on to the Submit area, but because of where it is set, I am unable to do so.
In your "browse" button code you are initializing a local variable mod like this:
final File mod = fc.getSelectedFile();
In the "Submit" button code you are using a class variable mod. Same name, different variables with different scopes.
Try changing:
final File mod = fc.getSelectedFile();
to
mod = fc.getSelectedFile();
with mod being a private class variable.
Also add null check in the "Submit" button code.

why i am getting Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError?

i found a java file on the web that allows me to read a pdf in a url and save it to my local machine,
i have sucsesfully compiled it and customized as a javabean so i can useit in my app, but when i test it i am getting the next error message.
i have added the library (PDFOne.jar file) to my project in netbean and averything compiles well.
in fact, the program detect my pdf url and validate it saying is a valid pdf file, but then the error comes:
any tip ? i am completely new in java world.
thanks in advance
Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError: com/gnostice/pdfone/PdfDocument
at Read_PDF_From_URL.setProperty(Read_PDF_From_URL.java:51)
at oracle.forms.handler.ComponentItem.setCustomProperty(Unknown Source)
at oracle.forms.handler.ComponentItem.onUpdate(Unknown Source)
at oracle.forms.handler.JavaContainer.onUpdate(Unknown Source)
at oracle.forms.handler.UICommon.onUpdate(Unknown Source)
at oracle.forms.engine.Runform.onUpdateHandler(Unknown Source)
at oracle.forms.engine.Runform.processMessage(Unknown Source)
at oracle.forms.engine.Runform.processSet(Unknown Source)
at oracle.forms.engine.Runform.onMessageReal(Unknown Source)
at oracle.forms.engine.Runform.onMessage(Unknown Source)
at oracle.forms.engine.Runform.processEventEnd(Unknown Source)
at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)
at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.gnostice.pdfone.PdfDocument
at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 39 more
here is part of the source code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import oracle.forms.properties.*;
import oracle.forms.ui.*;
import com.gnostice.pdfone.PdfDocument;
import java.net.MalformedURLException;
public class Read_PDF_From_URL extends VTextArea {
private static final ID GEN = ID.registerProperty("sav");
public boolean setProperty(ID id, Object value) {
boolean retorno = true;
try {
if (id == GEN) {
System.out.println("if");
URL url1 =
new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf");
byte[] ba1 = new byte[1024];
int baLength;
FileOutputStream fos1 = new FileOutputStream("sibdownload.pdf");
// Contacting the URL
System.out.print("Connecting to " + url1.toString() + " ... ");
URLConnection urlConn = url1.openConnection();
// Checking whether the URL contains a PDF
if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
} else {
try {
// Read the PDF from the URL and save to a local file
InputStream is1 = url1.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();
// Load the PDF document and display its page count
System.out.print("DONE.\nProcessing the PDF ... ");
PdfDocument doc = new PdfDocument();
try {
doc.load("sibdownload.pdf");
System.out.println("DONE.\nNumber of pages in the PDF is " +
I have resolved my question... The first thing was that I've needed to include the jar file in my classpath and the second thing that I've needed to sign the jar file.

Categories