So I'm making a simple chat where I'm sending content in the form of objects, in this case my problem is that when I'm sending and Image it just blocking my Client!, here's my shortened code.
I've isolated it mostly to the code below, as I've tested the rest and worked fine, I've also tried debugging this but I just can't seem to find the problem
Image
package com.example.mtc.Packets;
import java.io.Serializable;
public class Image extends Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3188407715959746920L;
private byte[] content;
private String type;
public Image(byte[] content,String type, int sourceID,int destinationID,String sourceUsername) {
super(destinationID,sourceID,sourceUsername);
this.content = content;
this.type = "." + type;
}
public byte[] getContent() {
return content;
}
public String getType() {
return type;
}
}
ClientReaderThread:
while (true) {
try {
inputData = in.readObject();
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300, java.awt.Image.SCALE_DEFAULT));
if (imagePacket.getDestinationID() == 0) {
if (Cliente.selectedChat == 0) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
} else if (imagePacket.getSourceID() == Cliente.selectedChat
|| imagePacket.getSourceID() == Cliente.getUserID()) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Cliente.gui, "Couldn't connect to Server!", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server Listener
private void Listener() {
// TODO Auto-generated method stub
while (connected) {
inputData = readObject();
if (inputData != null) {
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300,
java.awt.Image.SCALE_DEFAULT));
imageIcon.getImage().flush();
BufferedImage bi = new BufferedImage(
imageIcon.getIconWidth(),
imageIcon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
imageIcon.paintIcon(null, g, 0,0);
g.dispose();
try {
File imageFile = File.createTempFile("image", imagePacket.getType(),
new File("./serverImages/"));
insertLog(imageFile.getAbsolutePath(), imagePacket.getDestinationID(), true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Files.write(imageFile.toPath(), imageContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (imagePacket.getDestinationID() == 0) {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
t.sendObject(imagePacket);
}
}
}
} else {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
if (t.getUserID() == imagePacket.getDestinationID()) {
t.sendObject(imagePacket);
}
}
}
sendObject(imagePacket);
}
}
}
}
}
}
Managed to solve it by using SwingUtilities.invokeLater(), as advised by R.L.M
Related
This code used to work with Eclipse Kepler. But the developer that wrote it is gone and it is no longer working with an upgrade to Neon plugins. I am getting this exception:
Caused by: org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalArgumentException: Argument cannot be null)
at org.eclipse.swt.SWT.error(SWT.java:4533)
at org.eclipse.swt.SWT.error(SWT.java:4448)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:185)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4536)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4154)
at com.example.server.commons.SysTrayThread.localRun(SysTrayThread.java:141)
at com.example.server.commons.SysTrayThread$2.run(SysTrayThread.java:87)
With this code:
private static final String SYSTEM_BUNDLE_ID = "org.eclipse.osgi"; //$NON-NLS-1$
private volatile boolean working = true;
private final Bundle bundle;
private final String logoPath;
private Display display;
public SysTrayThread (final Bundle bundle, final String logoPath) {
this.bundle = bundle;
this.logoPath = logoPath;
}
#Override
public void run() {
if(System.getProperty("os.name").equals("Mac OS X")) {
Class<?> comAppleConcurrentDispatch = null;
try {
comAppleConcurrentDispatch = Class.forName("com.apple.concurrent.Dispatch");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Method getInstance = null;
Object dispatchInstance = null;
Method getNonBlockingMainQueueExecutor = null;
Executor executor = null;
try {
getInstance = comAppleConcurrentDispatch.getMethod("getInstance", (Class<?>[]) null);
dispatchInstance = getInstance.invoke(null, (Object[]) null);
getNonBlockingMainQueueExecutor = dispatchInstance.getClass().getMethod("getNonBlockingMainQueueExecutor",(Class<?>[]) null);
executor = (Executor) getNonBlockingMainQueueExecutor.invoke(dispatchInstance, (Object[]) null);
executor.execute(new Runnable() {
public void run() {
try {
localRun();
} catch(Throwable t) {
}
}
}
);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
localRun();
}
});
}
}
public void localRun()
{
try {
SysTrayThread.this.display = Display.getDefault();
} catch (org.eclipse.swt.SWTError ex) {
return;
}
URL url = SysTrayThread.this.bundle.getEntry(SysTrayThread.this.logoPath);
try {
Image image = null;
Shell shell = new Shell(SysTrayThread.this.display);
InputStream stream = url.openStream();
try {
image = new Image(SysTrayThread.this.display, new ImageData(stream));
} finally {
stream.close();
}
final Menu menu = new Menu(shell, SWT.POP_UP);
MenuItem exitMenuItem = new MenuItem(menu, SWT.PUSH);
exitMenuItem.setText(Messages.SHUTDOWN_MENU_ITEM);
exitMenuItem.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(final SelectionEvent event) {
Bundle bundle = Platform.getBundle(SysTrayThread.SYSTEM_BUNDLE_ID);
try {
bundle.stop();
} catch (BundleException ex) {
throw new RuntimeException(ex);
}
}
});
Tray tray = SysTrayThread.this.display.getSystemTray();
TrayItem trayItem = new TrayItem(tray, SWT.NONE);
trayItem.addListener(SWT.MenuDetect, new Listener() {
#Override
public void handleEvent(final Event event) {
menu.setVisible(true);
}
});
trayItem.setImage(image);
while (SysTrayThread.this.working && !shell.isDisposed()) {
if (!SysTrayThread.this.display.readAndDispatch()) { // line 141
SysTrayThread.this.display.sleep();
}
}
tray.dispose();
image.dispose();
if (!shell.isDisposed()) {
shell.dispose();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void setWorking(final boolean working) {
if (this.display != null) {
this.display.syncExec(new Runnable() {
#Override
public void run() {
SysTrayThread.this.display.close();
}
});
}
this.working = working;
}
I had a look for RCP specific information on this problem, but the answers relate to setting an SWT element to null. As you can see I am not setting a value, just calling readAndDispatch().
Any ideas?
i am currently working on a chat server as a project an need a bit of help. i have a multithreaded chat server where i want the clients to be able to close their chat window without crashing the server because it loses connection. So far so good. i have a working gui, and when i have a single client logged in to the server it works just fine to close the window and so closing the clientIOProcessor without the server crashing.
However, when i have multiple clients logged in to the server and want to close one of them the hole thing crashes
here is the ClientIOProcessor:
public class ClientIOProcessor extends Object implements Runnable, InputListener {
private ObjectInput socketInput;
private ObjectOutput socketOutput;
private boolean keepRunning;
private ClientModelDistributor assignedModelDistributor;
private MessageImplementation currentMessage;
private UserHub userHub;
public ClientIOProcessor(ClientModelDistributor _assignedModelDistributor, ObjectInput _socketInput,
ObjectOutput _socketOutput) {
this.assignedModelDistributor = _assignedModelDistributor;
this.socketInput = _socketInput;
this.socketOutput = _socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
keepRunning = true;
}
public ClientIOProcessor(ClientLoginProcessor clientLoginProcessor, UserHub userHub) {
assignedModelDistributor = clientLoginProcessor.assignedModelDistributor;
socketInput = clientLoginProcessor.socketInput;
socketOutput = clientLoginProcessor.socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(userHub);
keepRunning = true;
this.userHub = userHub;
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
if(currentMessage == null) return;
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRJOINED:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRLEFT:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case TERMINATE:
this.terminateConnection();
break;
default:
System.out.println("An error occurred.");
}
}
}
public void terminateConnection() {
keepRunning = false;
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this.userHub);
assignedModelDistributor.getInputHandler().removeInputListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
// System.exit(0);
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByServer = null;
try {
messageSentByServer = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByServer;
}
/**
* This method can be used to send <code>messages</code> to the server.
*
* #param message
* #throws IOException
*/
public void send(Message message) throws IOException {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method is called whenever the user enters input to this
* <code>InputListener</code>'s corresponding <code>InputHandler</code>.
*/
#Override
public void inputEntered(String input) {
try {
send(assignedModelDistributor.buildUserMessage(input));
} catch (IOException e) {
e.printStackTrace();
}
}
}
the clientIO processor gets the TERMINATE message from the server and calls the terminateConnection() Method to end the Streams.
Here is the ServerIOProcessor:
public class ServerIOProcessor implements Runnable, IncomingMessageListener {
private ServerModelDistributor assignedModelDistributor;
private User assignedUser;
private boolean keepRunning;
private ObjectInputStream socketInput;
private ObjectOutputStream socketOutput;
private MessageImplementation currentMessage;
private final String SYSTEM = "System";
public ServerIOProcessor(User _assignedUser, ObjectOutputStream _socketOutput, ObjectInputStream _socketInput,
ServerModelDistributor _assignedModelDistributor) {
assignedUser = _assignedUser;
socketInput = _socketInput;
socketOutput = _socketOutput;
assignedModelDistributor = _assignedModelDistributor;
keepRunning = true;
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(this);
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case NEWTASK:
createNewTask();
break;
case TASKASSGNMNT:
assignTaskToUser();
break;
case NEWLEADER:
determineLeaderOfTeam();
break;
case ADDTEAM:
addTeam();
break;
case RMVTEAM:
removeTeam();
break;
case ADDTEAMMEMBER:
addUserToTeam();
break;
case RMVTEAMMEMBER:
removeUserFromTeam();
break;
case JOINTEAM:
joinTeam();
break;
case LEAVETEAM:
leaveTeam();
break;
case EDITDETAILS:
editUserDetails();
break;
case TERMINATE:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
letClientLeaveServer();
break;
default:
send(newSystemMessage(MessageType.ERROR));
System.out.println("An error occured in one of the server's active IO processes.");
break;
}
}
}
private void createNewTask() {
}
private void assignTaskToUser() {
// TODO Auto-generated method stub
}
private void determineLeaderOfTeam() {
// TODO Auto-generated method stub
}
private void addTeam() {
// TODO Auto-generated method stub
}
private void removeTeam() {
// TODO Auto-generated method stub
}
private void addUserToTeam() {
// TODO Auto-generated method stub
}
private void removeUserFromTeam() {
// TODO Auto-generated method stub
}
private void joinTeam() {
// TODO Auto-generated method stub
}
private void leaveTeam() {
// TODO Auto-generated method stub
}
private void editUserDetails() {
// TODO Auto-generated method stub
}
private void letClientLeaveServer() {
// TODO Auto-generated method stub
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
keepRunning = false;
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByUser = null;
try {
messageSentByUser = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByUser;
}
private MessageImplementation newSystemMessage(MessageType msgtype) {
return new MessageImplementation(SYSTEM, msgtype);
}
//TODO Check expected purpose of this method.
/**
* This method is called whenever a <code>Message</code> is entered to the
* corresponding <code>IncomingMessageHandler</code>.
*/
#Override
public void messageEntered(Message message) {
// assignedModelDistributor.getIncomingMessageHandler().enterMessage(message);
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Writes the given <code>Message</code> to the Socket's
* <code>ObjectInputStream</code>.
*
* #throws IOException
*/
void send(Message message) {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (Exception r) {
System.out.println("Error!");
r.printStackTrace();
}
}
}
the important part here is the letClientLeaveServer() method to end the streams here as well. however, i think this is the wrong way, because i think this ends the Input/Ouput Streams for all logged in Clients.
The ServerSocket it self is initialized in another class ConnectionProcessor which starts the Socket on a given port and accepts it. then the connectionProcessor starts the serverLogInProcessor which starts a new Thread for the serverIOProcessor.
Here the ConnectionProcessor:
public class ConnectionProcessor implements Runnable {
private ServerModelDistributor assignedModelDistributor;
private boolean keepRunning;
private ServerSocket serverSocket;
private int assignedPort;
public ConnectionProcessor(int _assignedPort, ServerModelDistributor _assignedModelDistributor) {
assignedModelDistributor = _assignedModelDistributor;
assignedPort = _assignedPort;
keepRunning = true;
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (keepRunning) {
if(serverSocket.isClosed()) {
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Socket socketCreatedForLoginProcess = serverSocket.accept();
serverSocket.close();
Thread serverLoginProcessor = new Thread(
new ServerLoginProcessor(this, socketCreatedForLoginProcess, assignedModelDistributor),
"loginProcess");
serverLoginProcessor.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I don't know why but when I export my project into an executable jar file, there are somethings that don't turn out as if you would run the program from eclipse. One frame doesn't open up, which just contains text in it. I have another internal frame which is a split pane and contains questions on the right hand side and information on the left hand side panel. But in the executable jar file it doesn't show the information on the left hand side. I don't know why this is happening, I also have tried many options when exporting the project (making a jar file) but nothing seems to work. Any help would be appreciated.
Here is my code for the frame that doesn't open up:
public class About implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
private MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null && !frame.isIconifiable()){
frame = new MyInternalFrame("SAD Imaging");
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
frame.addInternalFrameListener(this);
}
else {
try {
//frame.setIcon(true);
frame.setMaximizable(true);
frame.setIconifiable(false);
frame.setSelected(true);
frame.moveToFront();
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(600,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}
This file just contains text information.
Same problem with the split pane. Here is the code for it.
public class FrequentQuestions implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
JPanel panelQuestions = new JPanel();
JPanel panelAnswers = new JPanel();
JTextArea text = new JTextArea();
JTextPane tPane = new JTextPane();
String file ="";
//private FrequentQuestions quest;
JSplitPane pane ;
MyInternalFrame frame;
public FrequentQuestions(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null){
frame = new MyInternalFrame("Frequently Asked Questions");
String [] options = {"How to open/save images", "What formats can SAD Imaging open", "How to show information about an image",
"Compute FFT/Inverse", "Graphs"};
JList list = new JList(options);
//list.setBorder(BorderFactory.createLineBorder(Color.black));
//panelQuestions.add(list);
list.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if(e.getValueIsAdjusting() == false)
return;
JList list = (JList) e.getSource();
if (list.isSelectionEmpty()) {
System.out.println("list selection is empty!");
}
int index = ((JList)e.getSource()).getSelectedIndex();
if(index == 0){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("openSave.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("I am outputting!");
}
else if(index == 1){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("format.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
//String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("2nd item selected");
}
else{
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("showInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("3rd item selected");
}
}
});
JScrollPane scroll1 = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll = new JScrollPane(tPane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scroll1, scroll);
pane.setAutoscrolls(true);
pane.setOpaque(true);
panelQuestions.setMinimumSize(new Dimension(259,50));
panelQuestions.setBackground(new Color(0,0,0,0));
panelAnswers.setMinimumSize(new Dimension(600,30));
pane.setOneTouchExpandable(true);
pane.setDividerLocation(290);
scroll1.setBackground(new Color(0,0,0,0));
//Border border = new Border();
//scroll1.setBorder(BorderFactory.createLineBorder(Color.black));
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(pane);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e1) {
}
}
else{
try {
//frame.setIcon(true);
//frame.setMaximizable(true);
frame.setSelected(true);
frame.moveToFront();
//frame.toFront();
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(800,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}
You are trying to load the file from the filesystem. Instead, you need to load it via a classloader.
Getting Resources from a jar: classloader vs class resourceasstream
Edit: I'm assuming that the executable jar contains this text file. Is that the case?
Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
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(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.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() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.
why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class
I need Your help!
So I got this app on an Android device, in which I get data from the accelerometer, and button presses which get this data to an edittext, and sets listeners on the edittextes.
When it's changed, there's a functions that creates a socket, sends data, and closes the socket.
Then I have a server app on my computer, in which I create serversockets, and create two threads that are waiting for serversocket.accept() that gets the data and put it into texbox. Simple as that.
I'm glad that I got it working anyway :-) but the point is, it's not working so well. I believe that whole communication is bad and not optimized. It sends data well, but often freezes, then unfreezes and sends quickly all previous data and so on.
I'm sorry for my bad code, but can someone please take a good look on this, and propose what I should change and how I could make it work more smooth and stable? :-(
Here's the Client code:
package com.test.klienttcp;
//import's...
public class Klient extends Activity implements SensorListener {
final String log = "Log";
EditText textOut;
EditText adres;
EditText test;
EditText gazuje;
TextView textIn;
TextView tekst;
TextView dziala;
String numer = null;
float wspk = 0; // wspolczynniki kalibracji
float wychylenietmp = 0;
float wychylenie = 0;
int tmp = 0;
int i = 0;
boolean wysylaj = false;
SensorManager sm = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
adres = (EditText)findViewById(R.id.adres);
gazuje = (EditText)findViewById(R.id.gazuje);
Button kalibracja = (Button)findViewById(R.id.kalibracja);
Button polacz = (Button)findViewById(R.id.polacz);
Button gaz = (Button)findViewById(R.id.gaz);
Button hamulec = (Button)findViewById(R.id.hamulec);
kalibracja.setOnClickListener(kalibracjaOnClickListener);
polacz.setOnClickListener(polaczOnClickListener);
gaz.setOnTouchListener(gazOnTouchListener);
hamulec.setOnTouchListener(hamulecOnTouchListener);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
//text listener steering
textOut.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Wyslij();
}
}
});
//text listener for throttle
gazuje.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Gaz();
}
}
});
}
Button.OnClickListener polaczOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(wysylaj==false)
{
wysylaj = true;
}
else
{
wysylaj = false;
}
}};
//throttle button handler
Button.OnTouchListener gazOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("1");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//brake button handler
Button.OnTouchListener hamulecOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("2");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//sensor handler
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
wychylenie = values[0] * 10;
tmp = Math.round(wychylenie);
wychylenie = tmp / 10;
if(wychylenie != wychylenietmp)
{
textOut.setText(Float.toString(wychylenie - wspk));
wychylenietmp = wychylenie;
}
}
}
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(log, "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this, SensorManager.SENSOR_ORIENTATION
| SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
//callibration handler
Button.OnClickListener kalibracjaOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
wspk = wychylenie;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
// sending steering data
public void Wyslij()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//sending throttle data
public void Gaz()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8889);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(gazuje.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
And here's Server code:
//import's...
public class Okno
{
public static float wychylenie;
public static String gaz="0";
public static float jedzie;
public static int skrecam, gazuje;
public static String wiadomosc="100";
private static int maxConnections=0, port=8888, portg=8889;
public static void main(String[] args)
{
skrecam = 0;
gazuje = 0;
Window ok = new Window();
ok.setDefaultCloseOperation(3);
ok.setVisible(true);
ok.setResizable(false);
ok.setTitle("Serwer TCP");
int i=0;
try{
Robot robot = new Robot();
Robot robotgaz = new Robot();
ServerSocket listener = new ServerSocket(port);
ServerSocket listenergaz = new ServerSocket(portg);
while((i++ < maxConnections) || (maxConnections == 0)){
//create thread for steering
if(skrecam == 0)
{
skrecam=1;
doComms conn_c= new doComms(listener);
Thread t = new Thread(conn_c);
t.start();
}
//create thread for throttle
if(gazuje == 0)
{
gazuje=1;
doCommsgaz conn_gaz= new doCommsgaz(listenergaz);
Thread tgaz = new Thread(conn_gaz);
tgaz.start();
}
ok.pole3.setText(wiadomosc);
ok.pole2.setText(gaz);
}
}
catch (AWTException e) {
e.printStackTrace();
}
catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doComms(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.wiadomosc = in.readUTF();
server.close();
Okno.skrecam=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doCommsgaz implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doCommsgaz(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.gaz = in.readUTF();
server.close();
Okno.gazuje=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class Window extends JFrame {
private JButton ustaw;
public JTextField pole1;
public JTextField pole2;
public JTextField pole3;
Window()
{
setSize(300,200);
getContentPane().setLayout(new GridLayout(4,1));
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(1));
getContentPane().add(panel1);
pole1 = new JTextField(15);
panel1.add(pole1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(1));
getContentPane().add(panel2);
pole2 = new JTextField(15);
panel2.add(pole2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(1));
getContentPane().add(panel3);
pole3 = new JTextField(15);
panel3.add(pole3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(1));
getContentPane().add(panel4);
ustaw = new JButton("Ustaw");
panel4.add(ustaw);
//action button handler
ustaw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent zdarz){
try{
}
catch(Exception wyjatek){}
pole1.setText("costam");
}
});
}
}
Once again, sorry for the non optimized, and hard-to-read code. But please, if someone knows what would be better, please respond.
Thanks a lot!
The client socket code should go into an AsyncTask. Google has a good into to it here. This will not speed anything up but it will stop your app from freezing. You can put in a "Processing" message while displaying a progress dialog to let the user know that something is happening.