I have two buttons and and Timer. When I run the code it gets connected to the Socket. For every 1000 milliseconds timer should send the command(message) to the Socket and simultaneously when I click a button it should send other message as in the code. But problem is that when I click a button either the messages which are sent are delayed or messages are not sent properly through dat is the receiving end is not receiving properly.
How to handle this issue?
Here is my code
public static void main(String[] args)
{
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
configure config=new configure();
config.run();
config.setVisible(true);
}
});
}
protected void run()
{
// TODO Auto-generated method stub
try {
connection.setText("Connected to < NONE >");
socket=new Socket("192.168.1.3",3000);
// System.out.println("Connection Established") ;
connection.setText("CONNECTION ESTABLISHED WITH : " + "< " +
socket.getInetAddress() + " >" + "\n");
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// System.out.println("connection failed");
connection.setText("CONNECTION FAILED");
}
}
public configure()
{
setResizable(false);
setBounds(300,80,800,600);
contentPane=new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(null);
configlabel=new JLabel("CONFIGURE YOUR MODEL");
configlabel.setBounds(210,20,500,40);
configlabel.setFont(new Font("arial",Font.BOLD,28));
contentPane.add(configlabel);
connection=new JLabel();
connection.setBounds(12,80,500,40);
connection.setFont(new Font("arial",Font.BOLD,16));
contentPane.add(connection);
channel1=new JLabel("Channel 1");
channel1.setBounds(80, 140, 80, 30);
channel1.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel1);
channel1Field=new JTextField();
channel1Field.setBounds(55, 200, 120, 30);
channel1Field.setEnabled(true);
contentPane.add(channel1Field);
channel1send=new JButton("Send 1");
channel1send.setBounds(65, 270, 100, 30);
channel1send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
if(!(channel1Field.getText().equals("")))
{
// TODO Auto-generated method stub
if(channel1send.isEnabled())
{
new Thread(new Channel1()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot be
empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel1send);
channel2=new JLabel("Channel 2");
channel2.setBounds(255, 140, 80, 30);
channel2.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel2);
channel2Field=new JTextField();
channel2Field.setBounds(230, 200, 120, 30);
channel2Field.setEnabled(true);
contentPane.add(channel2Field);
channel2send=new JButton("Send 2");
channel2send.setBounds(250, 270, 80, 30);
channel2send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(!(channel2Field.getText().equals("")))
{
if(channel2send.isEnabled())
{
new Thread(new Channel2()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot
be empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel2send);
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 1000);
}
class SayHello extends TimerTask {
public void run() {
try
{
byte[] com=new byte[]{0x01,(byte)0xFE};
socket=new Socket("192.168.1.3",3000);
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
dw.writeInt(com.length);
dw.write(com);
StringBuilder sb=new StringBuilder();
for(byte b:com)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Timer Sent - " + sb.toString() + "\n");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Channel1 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message1=channel1Field.getText();
int msg1=Integer.parseInt(message1);
command=new byte[]{(byte)0xFE,0x01,0x01,(byte)msg1,0x00,0x00,(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
// System.out.println(Arrays.toString(command));
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 1 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
sentmessage.append("channel 1 failed to send");
}
finally
{
if(socket!=null)
{
try
{
socket.close();
socket=new Socket("192.168.1.3",3000);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
class Channel2 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message2=channel2Field.getText();
int msg2=Integer.parseInt(message2);
command=new byte[]{(byte)0xFE,0x01,0x02,(byte)msg2,0x00,0x00(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 2 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
e1.printStackTrace();
sentmessage.append("channel 2 on failed");
}
finally
{
if(socket!=null)
{
try {
socket.close();
socket=new Socket("192.168.1.3",3000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
Related
I'm working on a server-client game in which I need to update client's JFrame from the server in a specific period.this is my game
The problem is that the client's JFrame does not update.to be sure,I have rendered the JFrame Submitted by the server and it's OK,but the client's JFrame does not change at all.Here's my code:
my server:
public class main implements java.io.Serializable{
static ArrayList<Socket> allsockets = new ArrayList<>();
static ArrayList<ObjectOutputStream> oos = new ArrayList<>();
static final MainFrame frame=new MainFrame();
static boolean testfirst=false;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String color;
Color color1 = null;
Socket clientsocket=null;
ServerSocket serversocket=null;
PrintStream os = null;
ObjectInputStream is=null;
try{
serversocket = new ServerSocket(); // don't bind just yet
serversocket.setReuseAddress(true);
serversocket.bind(new InetSocketAddress(5555)); // can bind with reuse= true
}
catch(IOException e){
System.out.println(e);
}
while(true){
try {
clientsocket=serversocket.accept();
allsockets.add(clientsocket);
oos.add(new ObjectOutputStream(clientsocket.getOutputStream()));
is=new ObjectInputStream(clientsocket.getInputStream());
os = new PrintStream(clientsocket.getOutputStream());
try {
name =(String) is.readObject();
color=(String) is.readObject();
try {
java.lang.reflect.Field field = Class.forName("java.awt.Color").getField(color);
color1 = (Color)field.get(null);
} catch (Exception e) {
color = null;
}
player p=new player();
frame.addplayer(name, color1,p);
if(!testfirst){
testfirst=true;
new Thread(){
public void run(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("timer works");
for(ObjectOutputStream os:oos){
try {
os.writeObject(frame);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, 1);
}
}.start();
}
handle h= new handle(is, frame, p);
h.start();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my client:
public class client implements java.io.Serializable {
static private final Lock mutex = new ReentrantLock(true);
private static final long serialVersionUID = 1L;
static double prevx =0;
static double prevy=0;
static Timer timer=new Timer();
static ObjectOutputStream os =null;
public static void main(String[]args) {
MainFrame frame=new MainFrame();
Socket clientSocket=null;
ObjectInputStream is=null;
String name;
String color;
try {
clientSocket = new Socket("localhost", 5555);
os = new ObjectOutputStream(clientSocket.getOutputStream());
is=new ObjectInputStream(clientSocket.getInputStream());
System.out.println("enter your name:");
Scanner in1=new Scanner(System.in);
name=in1.nextLine();
System.out.println("enter your color:");
color=in1.nextLine();
in1.close();
os.writeObject(name);
os.writeObject(color);
refresh ref=new refresh( is, os);
ref.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host");
}
}}
the refresh class(which has the responsibility to update client's JFrame)
public class refresh extends Thread{
MainFrame frame;
ObjectInputStream ois;
ObjectOutputStream oos;
Timer timer=new Timer();
double prevx,prevy;
private Lock mutex = new ReentrantLock(true);
public refresh(ObjectInputStream ois,ObjectOutputStream oos){
frame=new MainFrame();
this.ois=ois;
this.oos=oos;
}
public void run(){
while(true){
try {
frame= (MainFrame) ois.readObject();
frame.repaint();
frame.removeMouseMotionListener(mml);
frame.addMouseMotionListener(mml);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setFocusable(true);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MouseMotionListener mml=new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
mutex.lock();
try {
System.out.println("mouse moved");
oos.writeObject(arg0.getX());
oos.writeObject(arg0.getY());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mutex.unlock();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};}
and if needed the handle class(which receives the mouse coordinates from the client)
public class handle extends Thread{
double prevx,prevy;
MainFrame frame;
player myplayer;
ObjectInputStream ois;
double screenwidth,screenheigth;
boolean first=false;
boolean finished = false;
static private final Lock mutex = new ReentrantLock(true);
Thread movethread = new Thread(){
public void run(){
System.out.println("movethread run");
try {
if(Math.abs(prevx-myplayer.xcenter)>1 || Math.abs(prevy - myplayer.ycenter)>1){
while(Math.abs(prevx-myplayer.xcenter)!=0
|| Math.abs(prevy - myplayer.ycenter)!=0){
if(prevx<0 || prevx>screenwidth || prevy<0 || prevy>screenheigth)break;
myplayer.movem(prevx, prevy,mutex);
frame.repaint();
System.out.println(myplayer.cp.getCenter());
}
finished = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public handle(ObjectInputStream ois,MainFrame frame,player p) {
// TODO Auto-generated constructor stub
this.myplayer=p;
this.ois=ois;
this.frame=frame;
this.screenwidth=frame.getscreenwidth();
this.screenheigth=frame.getscreenheigth();
}
public void run(){
System.out.println("handle thread run");
while(true){
try {
System.out.println("in handle");
System.out.println(first);
prevx= (double) ois.readObject();
prevy=(double) ois.readObject();
if(!first){
System.out.println("movethread started");
movethread.start();
first = true;
}
else if(first && finished){
movethread.run();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void update(double x,double y){
this.prevx=x;
this.prevy=y;
}}
Any help would be appreciated.
I have a problem with listening to my server output. I would like to be able to print something to the console as soon as one of the quoted command. The problem that I face is that it seems to be listening but then not go along with the rest of the program. So when I try to click on a button on my GUI, it get stuck.
public class MainFrame implements Runnable {
//declare Jpanel
private static JFrame frmHome;
// The client socket
private static Socket clientSocket = null;
// The output stream
static ObjectOutputStream os;
// The input stream
static ObjectInputStream is;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) throws IOException{
// The default port.
int portNumber = 3333;
// The default host.
String host = "localhost";
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
os.flush();
System.out
.println("CONNECTED TO SERVER\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
/* Create a thread to read from the server. */
new Thread(new MainFrame()).start();
os.writeObject("Home");
os.flush();
}
}
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
MainFrame window = new MainFrame();
MainFrame.frmHome.setVisible(true);
String responseLine;
try {
while (!closed) {
Here is where I try to create my buffer reader. The 2 commands "Modify,OK" and "AdStudent ok", are coming after other parts of the GUI have successfully performed a task.
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
try {
while((line = br.readLine()) != null){
if (br.readLine().contains("Modify,OK")
|| br.readLine().contains("AddSudent ok")){
System.out.println("did it");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} finally{
try {
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public MainFrame() {
initialize();
}
//function to make window visible
void setVisible() throws IOException {
main(null);
}
private void initialize() {
//Initialise Main window with 3 options.
frmHome = new JFrame();
frmHome.setTitle("Home");
frmHome.setBounds(100, 100, 300, 372);
frmHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHome.getContentPane().setLayout(null);
frmHome.setResizable(false);
JLabel lblWelcomeToSrs = new JLabel("Welcome to SRS");
lblWelcomeToSrs.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblWelcomeToSrs.setBounds(86, 183, 112, 14);
frmHome.getContentPane().add(lblWelcomeToSrs);
//initialise all buttons and labels of window.
JButton btnAdStu = new JButton("Add a student");
btnAdStu.setBounds(10, 207, 126, 23);
btnAdStu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AddStudentFrame adus;
try {
try {
adus = new AddStudentFrame();
adus.setVisible();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frmHome.setVisible(false);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
frmHome.getContentPane().add(btnAdStu);
JButton btnCheckStud = new JButton("Search / Modify");
btnCheckStud.setBounds(146, 207, 127, 23);
btnCheckStud.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
SearchFrame searchFrame;
searchFrame = new SearchFrame();
searchFrame.setVisible();
}
});
frmHome.getContentPane().add(btnCheckStud);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(0, 0, 0, 0);
frmHome.getContentPane().add(lblNewLabel);
JLabel lblCreatedByRmi = new JLabel("Created by R\u00E9mi Tuyaerts");
lblCreatedByRmi.setBounds(147, 318, 184, 14);
frmHome.getContentPane().add(lblCreatedByRmi);
JButton btnNewButton = new JButton("Complete List of Students");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CompleteListFrame studentList = new CompleteListFrame();
studentList.setVisible();
}
});
btnNewButton.setBounds(52, 241, 184, 23);
frmHome.getContentPane().add(btnNewButton);
// wonderful pictures of his excellence design by Yasser
JLabel lblNewLabel_1 = new JLabel("");
Image img = new ImageIcon(frmHome.getClass().getResource("/michaelchung.jpg")).getImage();
lblNewLabel_1.setIcon(new ImageIcon(img));
lblNewLabel_1.setBounds(80, 11, 120, 148);
frmHome.getContentPane().add(lblNewLabel_1);
}
}
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?
I have been trying to work this out by myself these past few days but I just can't seem to be able to get to a solution...... how do I force paint a JFrame and everything inside it? I have a Chat programme (client/server approach), the server class and the client one are identical code-wise? But I just can't seem to make the client one show!
import java.awt.event.ActionEvent;
public class Chat extends JFrame implements Runnable, ActionListener, WindowListener{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField line;
// TCP Components
private Socket channel = null;
private JScrollPane scrollPane;
private String toBeSent="";
private final String END_CHAT_SESSION = new Character((char)0).toString();
private PrintWriter out;
private boolean channelIsStillOpen = true;
private Socket channel;
private static JTextArea chatText;
public Chat(Socket channel) {
this.channel=channel;
addWindowListener(this);
setTitle("Remote Administrator");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
line = new JTextField();
line.setBounds(17, 207, 289, 40);
line.setColumns(10);
JButton send = new JButton("Send");
send.addActionListener(this);
send.setBounds(312, 214, 105, 25);
contentPane.setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(17, 5, 399, 196);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
chatText = new JTextArea();
chatText.setLineWrap(true);
chatText.setEditable(false);
chatText.setEnabled(false);
scrollPane.setViewportView(chatText);
contentPane.add(line);
contentPane.add(send);
}
#Override
public void run() {
try {
channel=new Socket(address, port);
System.out.println("Chat Connection accepted");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out = null;
try {
out = new PrintWriter(channel.getOutputStream(),true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s="";
do {
// Send data
if (toBeSent.length()!= 0) {
out.println(toBeSent);
toBeSent="";
}
// Receive data
try {
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0) && !s.equals(END_CHAT_SESSION)) {
chatText.append("INCOMING: " + s + "\n");
}
if(s.equals(END_CHAT_SESSION)){
chatText.append("Client disconnected.");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while(!s.equals(END_CHAT_SESSION));
channelIsStillOpen=false;
line.setEditable(false);
line.setEnabled(false);
if(channel!=null){
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
channel=null;
}
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
if(channelIsStillOpen){
out.println(END_CHAT_SESSION);
}
dispose();
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
String s = line.getText();
if (!s.equals("")) {
chatText.append("OUTGOING: " + s + "\n");
// Send the string
toBeSent=s;
}
line.setText("");
}
}
edit: I have even edited the code so that the class being used is always the same! Nothing!
I think you are missing this at the end of your constructor:
this.setVisible(true);
also, why don't you set? setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, why do you want to keep the application opened?
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.