Displaying HTML in Swing - java

I am working on a project of sorts to load HTML files from a server and display them in swing.
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.swing.*;
public class webloader {
public static void loadcode(){
URL url = null;
try {
url = new URL("web"+File.separator+web.url+File.separator+"index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection con = null;
try {
con = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = null;
try {
r = new InputStreamReader(con.getInputStream(), charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder buf = new StringBuilder();
while (true) {
int ch = 0;
try {
ch = r.read();
} catch (IOException e) {
e.printStackTrace();
}
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
JFrame mainframe = new JFrame(web.url);
mainframe.setSize(800, 750);
mainframe.setResizable(false);
JPanel website = new JPanel();
JLabel webcontent = new JLabel(str);
website.add(webcontent);
mainframe.add(website);
mainframe.setVisible(true);
}
}
Error:
Loading test.com
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation
roblem:
Syntax error on token ""web"", delete this token
at webloader.loadcode(webloader.java:11)
at web$1.actionPerformed(web.java:46)
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 Sou
ce)
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 Sou
ce)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sou
ce)
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 Sou
ce)
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 am quite new to Java, so if I seem to be stupid or not know what I am doing, that's because I am.

I was trying to access the file wrong.
Correct code:
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.swing.*;
public class webloader {
static JComponent page;
public static void loadcode(){
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
try {
jep.setPage("http://(server):(port)/" + web.url);
}
catch (IOException e) {
jep.setContentType("text/html");
jep.setText("<html>Could not load webpage</html>");
}
JScrollPane scrollPane = new JScrollPane(jep);
JFrame f = new JFrame(web.url);
f.getContentPane().add(scrollPane);
f.setSize(512, 342);
f.show();
}
}

Related

Unhandled Exception Type Java

I am using Sikuli with Java to create a small automation tool. I am having trouble with this Unhandled Exception error. I am trying to pass a method I created to the GUI actionPerformed method.
package mission;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import tools.ChooseMission;
public class Story {
public static void runStoryMissions(int chapter, int stage) throws FindFailed, InterruptedException {
Screen screen = new Screen();
ChooseMission.ChooseChapter(screen,chapter);
ChooseMission.ChooseStage(screen, stage);
int dailyBiometricCount = ChooseMission.dailyBiometricCount(screen);
Pattern start = new Pattern("img/chapters/start.png");
Pattern replay = new Pattern("img/chapters/replay.png");
Pattern next = new Pattern("img/chapters/next.png");
Pattern mission_finish_bar = new Pattern("img/chapters/mission_finish_bar.png");
screen.click(start);
System.out.println("The mission has started.");
Thread.sleep(2000);
while (find(screen, mission_finish_bar) == false) {
System.out.println("Still playing the mission...");
}
if (screen.exists(mission_finish_bar) != null){
System.out.println("The mission has finished.");
}
System.out.println("Wait for 5 Seconds");
Thread.sleep(5000);
System.out.println("Click repeat button");
screen.click(replay);
}
Here is the code for my actionPerformed listener button:
btnStartMissions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int chapter = Integer.parseInt(txtFldChapter.getText());
int stage = Integer.parseInt(txtFldStage.getText());
System.out.println("Chapter #: " + chapter);
System.out.println("Stage #: " + stage);
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is a error at Story. runStoryMissions(chapter,stage) it says: Unhandled Exception type FindFailed and InterruptedException
Stack Trace:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at mission.Story.runStoryMissions(Story.java:12)
at GuiFrame1$2.actionPerformed(GuiFrame1.java:94)
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)
Caused by: java.lang.IllegalThreadStateException: Cannot call method from the event dispatcher thread
at java.awt.Robot.checkNotDispatchThread(Unknown Source)
at java.awt.Robot.waitForIdle(Unknown Source)
at org.sikuli.script.Mouse.move(Mouse.java:345)
at org.sikuli.script.Mouse.move(Mouse.java:318)
at org.sikuli.script.Mouse.init(Mouse.java:59)
at org.sikuli.script.Screen.initScreens(Screen.java:89)
at org.sikuli.script.Screen.<clinit>(Screen.java:58)
... 38 more
Okay, I found the answer to my problem if anyone is interested.
Sikuli uses the java.awt features so scripts cannot implement and use Swing elements.
Java AWT Robot actions cannot be called froma Java swing container.
Solution is to create a new Thread:
new Thread(() -> {
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();

Cannot delete file because it is open due to merger class (pdf)

I am getting the following error while running this code. I found that it happens because of the merger.mergesPagesFromPdfFiles() function. How can i prevent this to happen? I tried several things but nothing worked.
java.nio.file.FileSystemException: C:\Users\Ben\Desktop\Post\Klanten\10817 - TEST TEST\Factuur TEST TEST.pdf: (Translated) The process does not have access because the file is used by another process
Merger merger = new Merger();
merger.mergesPagesFromPdfFiles(filesToSend, getPathPostTS().toString() + "\\"
+ CustomFunctions.generatePersonalFileName("Documenten", client) + ".pdf");
//Runtime.getRuntime().gc();
//merger = null;
for (String file : filesToSend) {
File fileEntry = new File(file);
try {
fileEntry.setWritable(true);
java.nio.file.Files.deleteIfExists(fileEntry.toPath());
//Another way of trying to delete it
if (fileEntry.delete()) {
System.out.println(fileEntry.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(folder.list());
if (folder.list().length > 0) {
folder.delete();
} else {
JOptionPane.showMessageDialog(null, "FOLDER IS NIET LEEG, KIJK NA");
}
And here is the merger class creating the conflict.
public Merger() {
}
public void mergesPagesFromPdfFiles(List<String> pdfFiles, String outputFileLocation) {
try {
Document document = new Document();
FileOutputStream fos = new FileOutputStream(outputFileLocation);
PdfCopy writer = new PdfCopy(document,fos );
writer.setMergeFields();
document.open();
for (String pdf : pdfFiles) {
int index = pdf.lastIndexOf("\\");
String pdfName = pdf.substring(index + 1, pdf.indexOf(".pdf"));
PdfReader reader = new PdfReader(pdf);
// if(reader.getNumberOfPages() < mergePageNr){
// System.err.println("'" + pdfName + "' has not enough pages to
// merge. Skipped to next pdf!");
// continue;
// }
writer.addDocument(reader);
}
System.out.println("Files merged!");
document.close();
writer.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks for helping out!
edit: complete error plus changed code to close fos
Files merged!
java.nio.file.FileSystemException: C:\Users\Ben\Desktop\Post\Klanten\10817 - TEST TEST\Factuur TEST TEST.pdf: Het proces heeft geen toegang tot het bestand omdat het door een ander proces wordt gebruikt.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(Unknown Source)
at java.nio.file.Files.deleteIfExists(Unknown Source)
at generalClasses.Generator.sendAllFilesWithPost(Generator.java:243)
at factuurGen.FactuurGenerator.(FactuurGenerator.java:63)
at factuurGen.FactuurOptionPanel.generate(FactuurOptionPanel.java:31)
at view.MainView.generateAllDocuments(MainView.java:368)
at view.MainView.lambda$1(MainView.java:309)
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)

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

Can't fine the error with Operation not allowed after ResultSet closed

Method where im getting an error on:
public ArrayList<Log> selectAllLogs(){
if(openConn()){
ArrayList<Log> list = new ArrayList<Log>();
Boolean doesLogExists = false;
String query = "SELECT * FROM logs a LEFT JOIN log_lines s on a.log_id = s.log_id";
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
Log log = null;
while(rs.next()){
for (Log l : list) {
if(l.getLogId() == rs.getInt("log_id")){
log = l;
doesLogExists = true;
System.out.println("check");
}
}
if(doesLogExists){
log.getLogLines().add(rs.getString("log_lines"));
Iterator<Log> iter = list.iterator();
int i = 0;
System.out.println("true");
while(iter.hasNext()){
if(iter.next().getLogId() == ((list.get(i).getLogId()))){
list.remove(i);
list.add(i, log);
break;
}
i++;
}
doesLogExists = false;
} else {
System.out.println("false");
log = new Log();
log.setDateName(rs.getString("log_name"));
log.setLogId(rs.getInt("log_id"));
log.getLogLines().add(rs.getString("log_lines"));
list.add(log);
}
}
}
catch(SQLException sqle){
sqle.printStackTrace();
}
try {
closeConn();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
try {
closeConn();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Stackstrace:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:852)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at DataLayer.DatabaseConnector.selectAllLogs(DatabaseConnector.java:313)
at model.LogContainer.<init>(LogContainer.java:15)
at model.LogContainer.getInstance(LogContainer.java:20)
at view.LogOverview.initGui(LogOverview.java:91)
at view.LogOverview.<init>(LogOverview.java:27)
at controller.MainFrameController.actionPerformed(MainFrameController.java:65)
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)
Im getting an error on this piece of code, it is out of the else part in the while loop.
list.add(log);
I have googled the exception but i don't understand it. Can someone help me?
You can see from the stacktrace that the statement where the exception occurs in the method selectAllLogs is actually the call to com.mysql.jdbc.ResultSetImpl.getString, and not the statement list.add(log); There's an off by one error in where you thought the exception was occuring.
The reason that you're getting the SQLException is probably because you're not closing the ResultSet. This question is about the same issue.

Categories