So, I have two classes.
main class:
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 String movie;
public static String line;
public static void main(String args[]) throws IOException {
BufferedReader rd;
OutputStreamWriter wr;
//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()));
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());
}
}
}
}
gui class:
package guiprojj;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JPanel pangui = new JPanel();
JButton enter = new JButton("Enter");
JLabel movieinfo = new JLabel(Test.line);
final JTextField movietext = new JTextField(16);
maingui.add(pangui);
pangui.add(movietext);
pangui.add(enter);
pangui.add (movieinfo);
maingui.setVisible(true);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Test.movie = movietext.getText();
System.out.println(Test.movie);
}
});
}
}
What I am writing is a program that outputs the movie data from imbd after you enter it in the box, and I am running into an issue.
When I type in the movie, and press enter, it still shows as null and doesn't seem to be outputting the data from the api I am using.
public class Test {
public static String getMovieInfo(String movie) {
BufferedReader rd;
OutputStreamWriter wr;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
if (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 = rd.readLine();
if (line != null) {
return line;
} else {
return "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());
}
}
else
{
return "passed parameter is null!";
}
return "an error occured, see console!";
}
}
I've rewritten your Test-class. Renamed main-method, added return-statements (String) and removed the while-loop. Try to avoid multiple main(String[] args)-methods in one project, else your IDE could launch the "wrong" one, if your context switches.
I did not test it, but now you should be able to call Test.getMovieInfo("movie-name") from your gui-class to get the info.
(nethertheless this code should be refactored ;))
Related
I am trying to programm a little chat console, because I've recently learned to work with ServerSocket and Sockets. But I have a problem, I am not receiving / sending any messages what am I doing wrong?
Class:Chatting (Main)
package chatting;
import java.util.Scanner;
public class Chatting {
public static Client client;
public static Server server;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Your username: ");
String name = sc.nextLine();
System.out.print("connect to: ");
String ip = sc.nextLine();
client = new Client(ip.split(":")[0], Integer.parseInt(ip.split(":")[1]), name);
while (true){
String chat = sc.nextLine();
client.send(chat);
}
}
}
Class:Client
package chatting;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Client {
Socket s;
public Client(String ip, int port, String name){
if (ip.equalsIgnoreCase("localhost")){
Chatting.server = new Server();
}
new Thread(new Runnable(){
#Override
public void run(){
try{
s = new Socket(ip, port);
System.out.println("CONNECTION >> Waiting for conformation with name "+name+"!");
send("#reg"+name);
WaitForMessage("#confirmed");
System.out.println("CONNECTION >> You have been registered to server!");
while (true){
List<String> recieve = recieve();
if (!recieve.isEmpty()){
for (String str : recieve){
System.out.println(str);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
public void send(String msg){
try{
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os), true);
pw.write(msg);
pw.flush();
}catch(Exception e){
e.printStackTrace();
}
}
public List<String> recieve(){
List<String> r = new ArrayList<String>();
try{
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine())!=null){
System.out.println("CRECIEVE >> "+line);
r.add(line);
}
}catch(Exception e){
e.printStackTrace();
}
return r;
}
public void WaitForMessage(String msg){
while (true){
if (recieve().contains(msg)) break;
}
}
}
Class:Server
package chatting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Server {
ServerSocket ss;
List<Socket> s;
HashMap<String, String> registered;
public Server(){
s = new ArrayList<Socket>();
registered = new HashMap<String, String>();
try {
ss = new ServerSocket(1234);
System.out.println("SERVER >> created server on port 1234!");
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new Runnable(){
#Override
public void run(){
while (true){
try{
Socket socket = ss.accept();
if (socket != null){
System.out.println("SERVER >> client connected "+socket.getLocalAddress().toString());
s.add(socket);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable(){
#Override
public void run(){
while (true){
for (Socket s : s){
List<String> result = translate(recieve(s));
if (!result.isEmpty()){
for (String str : result){
if (str.startsWith("#reg")){
str = str.replaceAll("#reg", "");
registered.put(s.getInetAddress().toString(), str);
System.out.println("SERVER >> user "+str+" on "+s.getLocalAddress().toString()+" registered!");
send(s, "#confirmed");
}else{
sendToAll(registered.get(s.getLocalAddress().toString())+" >> "+str);
}
}
}
}
}
}
}).start();
}
public void send(Socket s, String str){
try{
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os), true);
pw.write(str);
pw.flush();
}catch(Exception e){
e.printStackTrace();
}
}
public List<String> translate(String[] str){
List<String> r = new ArrayList<String>();
for (String s : str){
r.add(s);
}
return r;
}
public String[] recieve(Socket s){
String[] r = null;
try{
ArrayList<String> lines = new ArrayList<String>();
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println("SRECIEVE >> "+line);
lines.add(line);
}
r = new String[lines.size()];
for (int i = 0; i < lines.size(); i++){
r[i] = lines.get(i);
}
}catch(Exception e){
e.printStackTrace();
}
return r;
}
public void sendToAll(String str){
for (Socket soc : s){
send(soc, str);
}
}
My problem is simply no messages get received / sent.
When I start the server it starts the client and connects perfectly, but when I get to
try{
s = new Socket(ip, port);
System.out.println("CONNECTION >> Waiting for conformation with name "+name+"!");
send("#reg"+name);
WaitForMessage("#confirmed");
System.out.println("CONNECTION >> You have been registered to server!");
while (true){
List<String> recieve = recieve();
if (!recieve.isEmpty()){
for (String str : recieve){
System.out.println(str);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
Nothing happens anymore.
You're reading lines but you aren't writing lines. Use println() instead of write(). And fix everything that #PeterLawrey mentioned too. And if readLine() returns null, close the socket and stop reading.
I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same.one clint to server is running good but teo client to server is not running properly one clint communication good but second one client not giving response.
Client Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Clientchatform extends JFrame implements ActionListener {
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
String line;
BufferedReader br;
String response;
BufferedReader is ;
PrintWriter os;
public Clientchatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
Send.addActionListener(this);
conn = new Socket(InetAddress.getLocalHost(), 2000);
ChatHistory.setText("Connected to Server");
this.setTitle("Client");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
br= new BufferedReader(new InputStreamReader(System.in));
String line = is.readLine();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Server:"
+ line);
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "Me:"
+ NewMsg.getText());
try {
br= new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
ChatHistory.append(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
Clientchatform chatForm = new Clientchatform();
}
}
Server Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class serverChatform extends JFrame implements ActionListener {
static ServerSocket server;
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
//DataInputStream dis;
//DataOutputStream dos;
String line;
BufferedReader is ;
public serverChatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
this.setTitle("Server");
Send.addActionListener(this);
server = new ServerSocket(2000, 1, InetAddress.getLocalHost());
ChatHistory.setText("Waiting for Client");
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter os=new PrintWriter(conn.getOutputStream());
line=is.readLine();
ChatHistory.append(ChatHistory.getText() + 'n' + "Client:"
+ line);
} catch (Exception e1)
{
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "ME:"
+ NewMsg.getText());
try {
PrintWriter os =new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
}
You're definitely on the right track, but I've got a question for you to ask yourself.
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
How often is this code executed? Consider that of course the main(),
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
is only called once, and therefore only one serverChatform will ever be created.
As you seem to have written quite a bit of code yourself, and it therefore seems like you're ready to learn more, I'm not going to give a full solution, but merely a direction.
Once you accept a client, with conn = server.accept();, you will have to create another new serverChatform();. This has to happen in a different Thread though. How to do this, I leave as an exercise for you.
Each connected client has to be served in its own thread. Additionally you need a Thread that continiously listens for new clients to connect. That would look like this.
List<Socket> clients; // Save the socket for each client
[...]
new Thread(new Runnable(){
#Override
public void run() {
// Thread that runs forever listening for new clients
while(true){
Socket conn = server.accept();
// new client has connected, store its socket
clients.add(conn);
// and start new thread that interacts with this new client
new Thread(new Runnable(){
#Override
public void run() {
// SERVE CLIENT HERE!
}
}).start();
}
}
}).start();
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 have a problem with readLine() in Java. I have a server and a client. From client I want to send a message to the server. The problem is that first, the client has to insert a text into a JTextField and when presses send then server to read the input from client, but server doesn't wait the input from client but instead reads null. But I read that readLine() is blocked until it has something to read, why it's not happening in this case?
Here I connect to the server and create the JFrame
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class StartingPoint {
private static PrintWriter out;
private static BufferedReader in;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
connectToServer();
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void createAndShowGui() throws IOException {
View frame = new View(out, in);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void connectToServer() throws IOException {
String serverAddress = "127.0.0.1";
int PORT = 8100;
Socket clientSocket = null;
out = null;
in = null;
try {
clientSocket = new Socket(serverAddress, PORT);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Could not connect to the server \n" + e);
System.exit(1);
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
if (clientSocket != null)
clientSocket.close();
}
}
}
Here is JFrame implementation:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class View extends JFrame {
private JButton button;
private JTextField field;
private JPanel gui;
public View(final PrintWriter out, final BufferedReader in) throws IOException {
button = new JButton("Send");
field = new JTextField();
gui = new JPanel(new GridLayout(1, 0, 10, 10));
gui.add(button);
gui.add(field);
add(gui);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println(field.getText());
try {
System.out.println(in.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer extends Thread {
public static final int PORT = 8100;
private static ServerSocket serverSocket = null;
private Socket clientSocket = null;
public void run() {
String receive, answer;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
receive = in.readLine();
System.out.println("[server]" + receive);
answer = "hello " + receive;
out.println(answer);
out.flush();
} catch (IOException e) {
System.err.println("IO error \n" + e);
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.err.println("Close socket error \n" + e);
}
}
}
public SimpleServer() throws IOException {
while (true) {
serverSocket = new ServerSocket(PORT);
try {
clientSocket = serverSocket.accept();
new Thread(this).start();
} finally {
serverSocket.close();
}
}
}
public static void main(String[] args) throws IOException {
SimpleServer server = new SimpleServer();
}
}
Your connectToServer() method opens a connection, creates streams and ... then closes them before returning. So of course, the server sees the close straight away, and returns null on the first readLine() call.
I suspect that you may have copied the "close in a finally block" pattern without understanding what it means. So I shall explain:
This is the normal pattern:
InputStream is = null;
try {
is = new FileInputStream(someFile);
// read the stream
} finally {
if (is != null) {
is.close();
}
}
The purpose of the code above is to ensure that the InputStream is always closed. Or more precisely, that it is always closed before the try/finally exits.
This is generally a good thing. But if the purpose of your code is to open some streams that is going to be used after this bit of code completes, then closing the stream here is self defeating.
InputStream is = null;
try {
is = new FileInputStream(someFile);
} finally {
if (is != null) {
is.close();
}
}
// read the stream ... OOOPS! We've already closed it!!
So to take this back to your original code, you need to move the try/finally/close stuff to the run method, something along these lines:
public void run() {
try {
connectToServer();
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
if (clientSocket != null)
clientSocket.close();
}
}
You should also catch and (probably) ignore IOException that might be thrown by each close() call.
Javadoc for BufferedReader.readLine()
doesn't say anything like that:
Returns:
A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has been reached
In your code you are opening a connection in connectToServer() and closing it, so server sees the end of stream
I'm having an issue using a JTextArea within a scrollpane. I can read from a textfile, but the contents are all showing up on one line. I have tried various methods using append and trying to break the line, but with no success.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SplashScreen extends JFrame implements ActionListener
{
JButton mobile;
JButton browser;
JLabel welc;
JPanel home;
File file = new File("C:\\Users\\Jimbob\\Desktop\\DisWorkspace\\TrustWizard\\welcometwo.txt");
BufferedReader reader = null;
int lines = 10;
public String read()
{
String savetext = "";
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null)
{
savetext += text;
}
}
catch(IOException jim)
{
jim.printStackTrace();
}
return savetext;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(mobile))
{
MobileHome openB = new MobileHome();
this.dispose();
}
if(e.getSource().equals(browser))
{
BrowserHome openB = new BrowserHome();
this.dispose();
}
}
public SplashScreen()
{
super("Trust Wizard");
JTextArea homeText = new JTextArea(25, 30);
homeText.setText(read());
JScrollPane homeScroll = new JScrollPane(homeText);
welc = new JLabel("Welcome To The Trust Wizard");
home = new JPanel();
mobile = new JButton("Mobile Wizard");
browser = new JButton("Browser Wizard");
home.add(welc);
home.add(homeScroll);
home.add(mobile);
home.add(browser);
ImageIcon img = new ImageIcon("hand.jpg");
setIconImage(img.getImage());
mobile.addActionListener(this);
browser.addActionListener(this);
getContentPane().add(home);
home.repaint();
setSize(450, 530);
setVisible(true);
}
public static void main(String args[])
{
SplashScreen test = new SplashScreen();
}
}
Don't write your own method to load data into a JTextArea.
//homeText.setText(read());
Instead, just use the read() method provided by the JTextArea API:
FileReader reader = new FileReader( your file name here );
BufferedReader br = new BufferedReader(reader);
homeText.read( br, null );
br.close();
Instead of appending just text, try appending text + "\n"
public String read() {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String text = null;
while((text = reader.readLine()) != null) {
builder.append(text + "\n");
}
} catch(IOException jim) {
jim.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return builder.toString();
}
Also added a finally block to close the BufferedReader (and with it the rest of the stream)
homeText.setLineWrap(true); should do the trick for you.
Put that line right after the where you create the homeText variable and then your text will wrap to the size of your JTextArea.
Also put a StringBuilder in your while loop instead of using String concatenation which has a lot of overhead.