I am trying to send frames to java app from python app. Firstly I create a blank image on python side with numpy array and then wanna send it to java app and display it on the java side. But the bufferedimage on java side is null here is python code;
import socket
import sys
import cv2
import numpy as np
import base64
import json
from lib2to3.pytree import Leaf
from lib2to3.fixer_util import String
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "localhost"
PORT = 5555
try:
socket.connect((HOST, PORT))
except:
print "We cannot find the server !!!!"
print "Terminating the program . . ."
#exit(0)
img = np.zeros((300, 300, 3), np.uint8)
obj = NumpyEncoder()
outjson = {}
outjson['img'] = base64.b64encode(img)
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)
socket.sendall(json_data
socket.close()
and here is java side;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Base64;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.javafx.iio.ImageFormatDescription;
import com.sun.prism.Image;
import java.awt.Color;
import java.awt.Dimension;
public class ServerFrame extends JFrame {
private JPanel contentPane;
public static BufferedImage bufferedImage;
/**
* Launch the application.
* #throws IOException
* #throws JSONException
*/
public static void main(String[] args) throws IOException, JSONException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerFrame frame = new ServerFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(5555);
} catch(IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
System.out.println("Server Socket Has Been Started . . .");
try {
clientSocket = serverSocket.accept();
System.out.println("User Connected :" + clientSocket.getLocalAddress().toString());
} catch(IOException e) {
System.out.println(e.getMessage());
}
StringBuilder sb = new StringBuilder();
InputStream in = clientSocket.getInputStream();
if(in == null) System.exit(1);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
//System.out.println(sb.toString());
JSONObject json = new JSONObject(sb.toString());
String leaf_name = json.getString("leaf");
String mat_string = json.getString("img");
byte[] raw_data = Base64.getDecoder().decode(mat_string);
bufferedImage = ImageIO.read(new ByteArrayInputStream(raw_data));
if(bufferedImage == null) System.out.println("warning");
System.out.println(raw_data.length);
FileOutputStream fos = new FileOutputStream("image.jpg");
try {
fos.write(raw_data);
}
finally {
fos.close();
}
/*JPanel panel = new JPanel();
panel.setBackground(Color.RED);
Dimension dim = new Dimension(50,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
label.setSize(label.getPreferredSize());
panel.add(label);
panel.setVisible(true);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bufferedImage)));*/
br.close();
clientSocket.close();
}
/**
* Create the frame.
*/
public ServerFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
Can you see the problem, Why is it null ?
change to :
outjson['img'] = base64.b64encode(img.tobytes())
Related
hi everyone i have problems with sending 2 strings via socket in java.
i have UI that get Username and password from client and send it to server . my problem make 2 part :1-i can not get the string username in my server 2- when the client send the username the socket is close before send the password here is my code please help me .
the main purpose is getting 2 string username and password from UI (client)and send them by socket to server.
Server:
package finalproject;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
ServerSocket listener;
Socket socket;
OutputStream out ;
InputStream in;;
InputStreamReader reader;
OutputStreamWriter writer;
String massage;
public void connectserver() throws IOException
{
listener = new ServerSocket(9097);
System.out.println("Server is running on port 9097 ...");
}
public void waitforclient() throws IOException
{
socket = listener.accept();
System.out.println("A new client connected to the server");
}
public void startstreamsserver() throws IOException
{
in = socket.getInputStream();
out = socket.getOutputStream();
writer = new OutputStreamWriter(out);
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
}
public void closestreamsserver() throws IOException
{
writer.close();
reader.close();
}
public void getinfoserver() throws IOException
{
try
{
reader.read();
System.out.println(reader);
System.out.println("input is : " + reader.toString());
}
catch(IOException IOE)
{
IOE.printStackTrace();//if there is an error, print it out
}
}
}
Client:
package finalproject;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Client
{
Socket socket;
OutputStream out1;
InputStream in1;
OutputStreamWriter writer;
InputStreamReader reader;
String massage;
JFrame frame;
BorderLayout blayout;
JButton center;
JButton south;
FlowLayout fLoyout;
JLabel jb1;
JTextField name;
JLabel jb2;
JTextField pass;
JLabel jb7;
JPanel cpanel;
JPanel spanel;
public void connectclient() throws IOException
{
socket = new Socket("localhost", 9097);
System.out.println("connect to server on port 9097");
}
public void startstreamsclient() throws IOException
{
in1 = socket.getInputStream();
out1 = socket.getOutputStream();
writer = new OutputStreamWriter(out1);
reader = new InputStreamReader(in1);
System.out.println("Client streams are ready");
}
public void closestreamsclient() throws IOException
{
writer.close();
reader.close();
}
public void loginformclient()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
blayout = new BorderLayout();
center = new JButton();
south = new JButton();
frame.setLayout(blayout);
fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
jb1 = new JLabel("Username :");
name = new JTextField(20);
center.add(jb1);
center.add(name);
jb2 = new JLabel("Password :");
pass = new JTextField(30);
center.add(jb2);
center.add(pass);
jb7 = new JLabel("Save");
south.add(jb7);
cpanel = new JPanel();
cpanel.add(center);
spanel = new JPanel();
south.addActionListener((ActionEvent ae) -> {
try
{
writer.write(name.getText());
writer.flush();
writer.write(pass.getText());
writer.flush();
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
});
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
and my main class :
package finalproject;
import java.io.IOException;
import javax.swing.JFrame;
public class Finalproject
{
public static void main(String[] args) throws IOException
{
//build Server & Client
Server server = new Server();
Client client = new Client();
//Start Server & Client
server.connectserver();
client.connectclient();
//Server wait for new connection
server.waitforclient();
//start the Streams
client.startstreamsclient();
server.startstreamsserver();
//Client send login information to Server
client.loginformclient();
//Server get information
server.getinfoserver();
}
}
but the my inputs in my server are:
java.io.InputStreamReader#171fc7e
input is : java.io.InputStreamReader#171fc7e
Edited Based on EJP correct remark:
Add new line delimiter:
writer.write(name.getText() + System.lineSeparator());
writer.write(pass.getText());
writer.flush();
replace this:
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
with:
BufferedReader in = new BufferedReader(reader);
String username= in.readLine();
String password = in.readLine();
I'm trying to make a very simple chat program that can accommodate multiple clients. I have a multi-threaded server and can connect multiple clients to it, but the server only communicates with a single client (as it should, each client is on its own thread) I need help getting the server to send all messages from all connected clients to each client. I think I'd need to share a single object between threads? Here's the code:
server:
import java.net.ServerSocket;
import java.net.Socket;
public class ThreadedCommandServer {
public static void main(String[] args) throws Exception {
System.out.println("Starting server....");
int port = 8989;
ServerSocket ss = new ServerSocket(port);
while(true) {
System.out.println("Waiting for connection from client...");
Socket socket = ss.accept();
ServerThread st = new ServerThread(socket);
st.start();
}
}
}
server thread:
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket socket = null;
private String s;
public ServerThread(Socket s) {
socket = s;
}
public void run() {
try {
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
s = (String) ois.readObject();
System.out.println("received string: " + s);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(s);
System.out.println("sent object back to client...");
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
client:
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Controller {
private ClientFrame cf;
private String message;
private Socket socket;
private String response;
public Controller(ClientFrame cf) {
this.cf = cf;
}
public void sendChat(String s) {
message = s;
System.out.println("FROM CONTROLLER: received: " + message);
try {
InetAddress i = InetAddress.getByName("localhost");
socket= new Socket(i, 8989);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
System.out.println("FROM CONTROLLER: sending message to the server...");
oos.writeObject(message);
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
System.out.println("getting string back from server....");
response = (String) ois.readObject();
cf.updateGUI(response);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
GUI:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientFrame extends JFrame {
private JTextArea chatArea;
private JTextField type;
private JButton submit;
private JPanel upper;
private JPanel lower;
private BorderLayout bl;
JScrollPane jsp;
Controller c;
public ClientFrame() {
bl = new BorderLayout();
upper = new JPanel();
lower = new JPanel();
chatArea = new JTextArea("chat goes here", 20, 30);
c = new Controller(this);
chatArea.setEditable(false);
chatArea.setLineWrap(true);
type = new JTextField("type here", 20);
jsp = new JScrollPane(chatArea);
new SmartScroller(jsp);
lower.add(type);
submit = new JButton("send");
submit.addActionListener(new Submit());
type.addActionListener(new Submit());
lower.add(submit);
upper.add(jsp);
this.setSize(400, 600);
this.setLayout(bl);
this.setTitle("MattChatt");
this.add(upper, BorderLayout.NORTH);
this.add(lower, BorderLayout.SOUTH);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void updateGUI(String s) {
chatArea.append("\n" + s);
}
private class Submit implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (type.getText().equals("")) {
System.out.println("no text entered");
} else {
System.out.println("submitted");
c.sendChat(type.getText());
type.setText("");
}
}
}
}
You have no way of accessing all of the ServerThreads you create.
What you need to do is group them all together in a collection, such as an ArrayList.
Or even better, a HashMap, if you would ever want to expand your application to allow private messaging, you would need to access a specific ServerThread, and with a HashMap you can do so easily.
Anyways... when it is time to send out the message, you should loop your collection through and send the message to the OutputStreams associated with each ServerThread.
I'm writing a simple-ish program to look up movie information, and I'm having a bit of an issue making the GUI appear.
I appreciate any help anyone might be able to offer.
package guiprojj;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import guiprojj.gui;
import javax.swing.JFrame;
#SuppressWarnings("unused")
public class Test {
public static void main(String args[]) throws IOException {
BufferedReader rd;
OutputStreamWriter wr;
String movie = null;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
while (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
line = rd.readLine();
if (line != null) {
System.out.println(line);
} else {
System.out.println("Sorry! That's not a valid URL.");
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
}
}
and
package guiprojj;
import javax.swing.*;
public class gui {
public static void main()
{
JFrame maingui = new JFrame("Gui");
JPanel pangui = new JPanel();
JTextField movie = new JTextField(16);
maingui.add(pangui);
pangui.add(movie);
maingui.setVisible(true);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
are my two classes!
Add a String array argument to the main method of gui so that the application has a valid entry point
public static void main(String[] args)
I am at this with ages and the problem i am having is simple i am not able to print out the data from the server to client everything else is working just that when the server sends a message to the client the phone it never gets or prints it out any insight or help would be great and i am getting no errors
client
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
new Incomingdata().execute();
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{ System.out.println("Test123");
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
System.out.println("Test1234");
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
System.out.println("Test1235");
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Server
package handy_server.simple_gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//imports for server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Pandaboy
*/
class ServerGUI extends JFrame implements ActionListener
{
private Socket connection;
private InetAddress ip;
private JTextField t1 = new JTextField(null);
private JTextField t2 = new JTextField(null);
private JTextField t3 = new JTextField(null);
private JButton b2 = new JButton("Send");
private JButton b1 = new JButton("Working");
private JPanel p1 = new JPanel();
private ServerSocket listeningSocket;
private int port= 0;
private ArrayList<Contact> myContacts = new ArrayList<Contact>();
//-------------------------serverGui------------------------------------------------------------
public ServerGUI(int port){
this.port = port;
init();
}
public void init()
{
Container content = getContentPane();
content.setLayout(new FlowLayout());
Font f = new Font("TimesRoman", Font.BOLD, 20);
p1.setLayout(new GridLayout(2, 2));
content.add(p1);
p1.add(t1);
p1.add(b1);
p1.add(t2);
p1.add(t3);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(210, 300);
setVisible(true);
System.out.println("Just about to start the server...");
startServer();
}
public void actionPerformed(ActionEvent e)
{
Object target = e.getSource();
if (target == b1)
{
t1.setText("Button working");
MyHelpers.buildConversations(this, myContacts);
}
if(target == b2)
{
t1.setText("button working2");
String number = t2.getText();
int phone_length = number.length();
if (phone_length <= 20)
{
for(int a=1; a <=(20 - phone_length); a++ )
{
number += " ";
}
}
String msg = t3.getText();
String text = "7"+number+msg;
System.out.print(""+text);
OutputStream o = null;
try
{
o = connection.getOutputStream();
}
catch (IOException ex)
{
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------startServer------------------------------------------------------------
private void startServer()
{
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground()
{
System.out.println("in startserver...");
try
{
listeningSocket = new ServerSocket(port);
try
{
ip = InetAddress.getLocalHost();
System.out.println("Please enter this in your phone " + ip.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
while (true)
{
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
InputStream in = connection.getInputStream();
Scanner r = new Scanner(in);
OutputStream o = connection.getOutputStream();
PrintWriter p = new PrintWriter(o);
String message = r.nextLine();
System.out.println("" + message);
t1.setText(message);
// get the message type
// 0 sms 1 contact 2 incoming call
System.out.println(message);
if(message.startsWith("0"))
{
System.out.println(message);
String type = message.substring(1,2);
int theType = Integer.parseInt( type );
String number = message.substring(7, 21).trim();
String theText = message.substring(21);
String theName = MyHelpers.getName(number, myContacts);
System.out.println("Number = "+number);
System.out.println("Sender = "+theName);
System.out.println("Text = "+theText);
Contact cRef = MyHelpers.getContactReference(number, myContacts);
if (cRef != null)
{
cRef.addsms(theType, theName, theText);
}
}
if(message.startsWith("1"))
{
System.out.println(message);
String name = message.substring(1, 31).trim();
String pnumber = message.substring(31, 51).trim();
String email = message.substring(51, 91).trim();
myContacts.add(new Contact(name, pnumber, email));
System.out.println( name + pnumber + email);
}
if(message.startsWith("2"))
{
String unkown = message.substring(0, 1).trim();
String number = message.substring(1, 14).trim();
String theName = MyHelpers.getName(number, myContacts);
System.out.println(""+unkown+""+theName+" Is calling you");
}
if(message.startsWith("5"))
{
System.exit(0);
}
Any Help would be great i am stumped by this
In your server append '\n' to the end of the response so change this
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
to this:
PrintWriter p = new PrintWriter(o);
p.println(text + "\n");
p.flush();
System.out.print("text sent"+text);
i think the reason it hangs is because readLine() is looking for '\n' and it never recieves it
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
I have an arraylist in my metod receiveArrayLists which i want to add to a JList. How can i do this?
import java.awt.Dimension;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUI implements Runnable {
private Server server;
private JFrame frame = new JFrame();
private JTextField jtf = new JTextField();
private JList jl = new JList();
private JTextArea jl1 = new JTextArea();
private JScrollPane pane = new JScrollPane(jl);
private Socket socket;
private DataInputStream dis;
private ObjectInputStream ois = null;
private DataOutputStream dos;
public GUI() {
socket = new Socket();
InetSocketAddress ipPort = new InetSocketAddress("127.0.0.1", 4444);
try {
socket.connect(ipPort);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (Exception e) {
}
new Thread(this).start();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 300, 420, 400);
frame.setResizable(false);
frame.setVisible(true);
pane.add(jl);
pane.add(jl1);
jl1.setEditable(false);
jtf.setBounds(50, 40, 150, 40);
jl.setBounds(50, 90, 150, 200);
jl1.setBounds(210, 90, 150, 200);
jtf.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (dos != null) {
if(jtf.getText().length() >0){
try {
dos.writeUTF(jtf.getText());
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
jl1.setText("");
}
}
}
});
frame.add(jtf);
frame.add(jl);
frame.add(jl1);
frame.add(pane);
}
public void run() {
String fromServer;
try {
while ((fromServer = dis.readUTF()) != null) {
if (fromServer.equals("read")) {
receiveArrayList();
}
}
} catch (Exception e) {
}
}
Here is my metod, as you can see, i try to use append which obviously wont work to add an arraylist to a JList
public void receiveArrayList() {
try {
jl1.setText("");
ois = new ObjectInputStream(socket.getInputStream());
#SuppressWarnings("unchecked")
ArrayList<String> a = (ArrayList<String>) (ois.readObject());
for (int i = 0; i < a.size(); i++) {
jl.append(a.get(i) + " \n");
}
dis = new DataInputStream(socket.getInputStream());
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
GUI g = new GUI();
}
}
The simplest is to create a DefaultListModel object, iterate through the ArrayList in a for or foreach loop and add the items to the model via its addElement(...) method. Then set the JList's model to your model.
More involved but satisfying is to create your own ListModel by extending AbstractListModel using your ArrayList as the model's nucleus.
You need to make use the JList's list model. The simplest solution is to use DefaultListModel, but you could investigate implementation your own (based on the AbstractListModel)
If you don't want to keep any previous content when you receive the array list you could do the following:
public void receiveArrayList() {
try {
DefaultListModel model = new DefaultListModel();
jl1.setText("");
ois = new ObjectInputStream(socket.getInputStream());
#SuppressWarnings("unchecked")
ArrayList<String> a = (ArrayList<String>) (ois.readObject());
for (int i = 0; i < a.size(); i++) {
model.addElement(a.get(i)); // <-- Add item to model
}
dis = new DataInputStream(socket.getInputStream());
jl.setModel(model); // <-- Set the model to make it visible
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
}
If you want to keep the previous list, then you need to ensure that the original model is a DefaultListModel (in this example) or is compatible with the ListModel you are using.
Basically, then you want to cast the model:
You may want to check out this tutorial for more info.
DefaultListModel model = jl.getModel();
Obviously, you won't need to reapply it at the end ;)