Socket Listener - I almost have it - java

I've been fighting with this and my own poor coding skills apparently.
I'm trying to create a small desktop app that will act essentially as a "Socket Listener" where I can display any information sent to the localhost IP and any port I designate. I have the program working without a UI, but I wanted to make it an actual desktop app (part of my learning journey).
I've searched around and borrowed some ideas from others and almost have it working.
When I launch the app, enter a port number and then try to connect to it using PUTTY I don't see anything displaying in my JTextArea. What should appear is a "Waiting for client" message and then when connected a "Client connected" message, then, of course, any text I type into PUTTY.
If I try connecting using PUTTY, type some text, then exit putty, all of that text and the messages above will appear in the JTextArea (JTextArea is at the bottom of the code).
What on earth am I doing wrong here?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
public class Server extends JFrame {
private JPanel contentPane;
private JTextField portInput;
static int sessionNum = 1;
static String IPNum = "127.0.0.1";
public JButton btnListen;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Server frame = new Server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Server() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 570, 503);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblAddress = new JLabel("IP Address:");
lblAddress.setHorizontalAlignment(SwingConstants.RIGHT);
lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblAddress.setBounds(10, 29, 81, 27);
contentPane.add(lblAddress);
JLabel lblDisplayAddress = new JLabel("127.0.0.1");
lblDisplayAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblDisplayAddress.setBounds(101, 29, 81, 27);
contentPane.add(lblDisplayAddress);
JLabel lblPort = new JLabel("Port: ");
lblPort.setHorizontalAlignment(SwingConstants.RIGHT);
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPort.setBounds(210, 33, 90, 19);
contentPane.add(lblPort);
portInput = new JTextField();
portInput.setFont(new Font("Tahoma", Font.PLAIN, 16));
portInput.setBounds(297, 31, 111, 22);
contentPane.add(portInput);
portInput.setColumns(10);
btnListen = new JButton("LISTEN");
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try{
ServerSocket ss=new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
Socket s=ss.accept();//establishes connection
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8)); {
while (true){
String cmd = in.readLine();
if (cmd == null) break; //client is hung up
if (cmd.isEmpty()) continue; //empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
}catch(IOException i){System.out.println(i);}
}
});
btnListen.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnListen.setBounds(450, 31, 89, 23);
contentPane.add(btnListen);
JTextArea output = new JTextArea();
output.setBounds(10, 77, 536, 382);
contentPane.add(output);
PrintStream out = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
output.append(""+(char)(b & 0xFF));
}
});
System.setOut(out);
}
}
UPDATED
Thank you so much for the input. I've incorporated your changes and it is so unbelievably close.
One question. When I run the current code (below), Why doesn't the JTextArea show the "Waiting for client..." message right away? It shows up once PUTTY connects, but not before.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
public class Server extends JFrame {
private JPanel contentPane;
private JTextField portInput;
static int sessionNum = 1;
static String IPNum = "127.0.0.1";
public JButton btnListen;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Server frame = new Server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Server() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 570, 503);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblAddress = new JLabel("IP Address:");
lblAddress.setHorizontalAlignment(SwingConstants.RIGHT);
lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblAddress.setBounds(10, 29, 81, 27);
contentPane.add(lblAddress);
JLabel lblDisplayAddress = new JLabel("127.0.0.1");
lblDisplayAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblDisplayAddress.setBounds(101, 29, 81, 27);
contentPane.add(lblDisplayAddress);
JLabel lblPort = new JLabel("Port: ");
lblPort.setHorizontalAlignment(SwingConstants.RIGHT);
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPort.setBounds(210, 33, 90, 19);
contentPane.add(lblPort);
portInput = new JTextField();
portInput.setFont(new Font("Tahoma", Font.PLAIN, 16));
portInput.setBounds(297, 31, 111, 22);
contentPane.add(portInput);
portInput.setColumns(10);
btnListen = new JButton("LISTEN");
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try {
ServerSocket ss = new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
Socket s = ss.accept();// establishes connection
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8));
{
while (true) { // Don't do this on the EDT.
String cmd = in.readLine();
if (cmd == null)
break; // client is hung up
if (cmd.isEmpty())
continue; // empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
} catch (IOException i) {
System.out.println(i);
}
}
});
btnListen.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnListen.setBounds(450, 31, 89, 23);
contentPane.add(btnListen);
JTextArea output = new JTextArea();
output.setBounds(10, 77, 536, 382);
contentPane.add(output);
PrintStream out = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
output.append(""+(char)(b & 0xFF));
}
});
System.setOut(out);
}
}

You have a ServerSocket blocking to read the client connection on the Event Dispatch Thread. Spawn a new thread when you accept a connection. Something like,
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try {
ServerSocket ss = new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
final Socket s = ss.accept();// establishes connection
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8));
{
while (true) { // Don't do this on the EDT.
String cmd = in.readLine();
if (cmd == null)
break; // client is hung up
if (cmd.isEmpty())
continue; // empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
} catch (IOException i) {
System.out.println(i);
}
}
});

Related

How do you select CSV file to perform calculations on based on user input?

I'm currently making a user-input based program on Java Eclipse that is supposed perform calculations on data from a local csv file the user selects. The GUI code below is the source code that I have been using to make the GUI for the program. While I have managed to create the GUI, I am having trouble with "combining" the code listed under "CSVReader," which is a class I created, with the code for the GUI so that the user can select the CSV file. The user is supposed to select this CSV file by typing its path name into the text field box on the GUI.
Any help would be appreciated
GUI CODE
//GUI CODE
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField txtCountryChosen;
/**
* #wbp.nonvisual location=71,14
*/
private final JTextField Program = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Program.setText("Statistics Manager");
Program.setColumns(10);
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Submit file path");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String textFieldValue = textField.getText();
}
});
btnNewButton.setBounds(145, 48, 150, 25);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(116, 13, 200, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(42, 104, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.setBounds(270, 103, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
}
}
CSVReader
//CSVREADER
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class CSVReader {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter file path name");
String file_path_name = scan.nextLine();
System.out.println(file_path_name);
String path= file_path_name;
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while((line = br.readLine()) !=null){
String[] values = line.split(",");
System.out.println("Country: " + values[0] + ", Year: " + values[2] + ", GDP: " + values[6] + ", GDP_per_capita: " + values[12] + ", Population: " + values[10]);
/*PrintStream myconsole= new PrintStream(new File("E://java.txt"));
System.setOut(myconsole);
myconsole.print(path);*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Calling another JFrame after veryfing user identity

any help would be greatly appreciated.
I've created 2 JFrames, one is a login window which verifies user credentials and I've linked it with my website's mySQL(This works and was hard since I'm very new to Java), and the other one is my main window which contains the main user interface where the user will work from.
I am trying to find a way that when user credentials are verified, the login window closes and opens the Main window. The more I dig into this, the more I think I've built this whole thing wrong, because both JFrames are built in main methods (I though this was how you did it, every tutorial begins with a main method).
to the actionPerform I've created on the JButton or textField_Password, but that does not work at all.Any idea how to open another class from actionPerform?
I would like to open the main window once user credentials are verified. Any ideas on how to proceed. This is all new to me and any help would be greaty appreciated.
Thanks in advance to anyone who helps me with this one, because I'm kind of stuck!
I was trying to add the following:
Main window = new Main();
window.frame.setVisible();
to my Jbutton actionPerform
here is the main code, any help would be greatly appreciated as I am a little loss
import javax.swing.JFrame;
import java.awt.SystemColor;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.PreparedStatement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JSeparator;
import javax.swing.JPasswordField;
import javax.swing.JCheckBox;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.sql.SQLException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Login {
private JFrame frame;
private JTextField txtUsername;
private JPasswordField txtPassword;
final String signUp = ("https://www.google.com");
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setBounds(100, 100, 547, 382);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
// frame.setUndecorated(true);
txtUsername = new JTextField();
txtUsername.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtUsername.setText(null);
}
});
JLabel labelResponse = new JLabel("");
labelResponse.setHorizontalAlignment(SwingConstants.CENTER);
labelResponse.setFont(new Font("Dialog", Font.BOLD, 12));
labelResponse.setForeground(Color.ORANGE);
labelResponse.setBounds(122, 280, 277, 30);
frame.getContentPane().add(labelResponse);
txtUsername.setBorder(null);
txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
txtUsername.setFont(new Font("Meiryo", Font.BOLD, 18));
txtUsername.setForeground(new Color(0, 128, 0));
txtUsername.setOpaque(false);
txtUsername.setText("Username");
txtUsername.setBackground(SystemColor.inactiveCaption);
txtUsername.setBounds(82, 62, 353, 53);
frame.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
/*
* JLabel labelClose = new JLabel("X");
*
labelClose.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelClose.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent e) {
System.exit(0); } });
* labelClose.setFont(new Font("Tahoma", Font.BOLD, 20));
* labelClose.setForeground(new Color(102, 205, 170));
labelClose.setBounds(493,
* 11, 22, 22); frame.getContentPane().add(labelClose);
*
* JLabel labelMin = new JLabel("-");
*
labelMin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelMin.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent arg0) {
* frame.setState(Frame.ICONIFIED); } });
labelMin.setForeground(new Color(102,
* 205, 170)); labelMin.setFont(new Font("Tahoma", Font.BOLD,
20));
* labelMin.setBounds(470, 11, 22, 22);
frame.getContentPane().add(labelMin);
*/
JLabel lblGt = new JLabel("Log In");
lblGt.setForeground(new Color(0, 128, 0));
lblGt.setFont(new Font("Meiryo", Font.BOLD, 20));
lblGt.setBounds(10, 5, 88, 38);
frame.getContentPane().add(lblGt);
JSeparator separator = new JSeparator();
separator.setBounds(82, 113, 353, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(82, 190, 353, 2);
frame.getContentPane().add(separator_1);
JCheckBox chckbxShowPass = new JCheckBox("Show Pass");
chckbxShowPass.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
chckbxShowPass.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (chckbxShowPass.isSelected()) {
txtPassword.setEchoChar((char) 0);
} else {
txtPassword.setEchoChar('*');
}
}
});
chckbxShowPass.setBorder(null);
chckbxShowPass.setOpaque(false);
chckbxShowPass.setForeground(new Color(0, 128, 0));
chckbxShowPass.setFont(new Font("Meiryo", Font.BOLD, 14));
chckbxShowPass.setBackground(new Color(0, 128, 0));
chckbxShowPass.setBounds(409, 281, 106, 23);
frame.getContentPane().add(chckbxShowPass);
JLabel labelRegister = new JLabel("Register");
labelRegister.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
labelRegister.setForeground(new Color(0, 128, 0));
labelRegister.setFont(new Font("Meiryo", Font.BOLD, 14));
labelRegister.setBounds(10, 285, 76, 16);
frame.getContentPane().add(labelRegister);
JButton buttonLogin = new JButton("Login");
buttonLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "password"); // not the actual
String query = "select EmailAddress,
Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword = new
String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You
must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evt) {
evt.printStackTrace();
labelResponse.setText("Exception
occurred while searching in the users table");
}
}
});
txtPassword = new JPasswordField();
txtPassword.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root",
"password");
String query = "select
EmailAddress, Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword
= new String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evte) {
evte.printStackTrace();
labelResponse.setText("Exception occurred while searching in the users
table");
}
}
});
txtPassword.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtPassword.setText(null);
}
});
txtPassword.setText("Password");
txtPassword.setBorder(null);
txtPassword.setHorizontalAlignment(SwingConstants.CENTER);
txtPassword.setForeground(new Color(0, 128, 0));
txtPassword.setFont(new Font("Meiryo", Font.BOLD, 18));
txtPassword.setOpaque(false);
txtPassword.setBackground(SystemColor.inactiveCaption);
txtPassword.setBounds(82, 139, 353, 53);
frame.getContentPane().add(txtPassword);
buttonLogin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonLogin.setBorderPainted(false);
buttonLogin.setBackground(new Color(0, 128, 0));
buttonLogin.setFont(new Font("Tahoma", Font.PLAIN, 18));
buttonLogin.setBounds(82, 216, 353, 53);
frame.getContentPane().add(buttonLogin);
labelRegister.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
Desktop.getDesktop().browse(new
URI("insertURL"));
} catch (Exception ex) {
// System.out.println(ex);
}
}
});
}
}
I found a solution and I will post it here. Hopefully it helps other new coders out there.
My main problem was that I was trying to link two application windows. Instead of selecting New/Other/Jframe, I used New/Other/Application Window which makes it tough to call the second window.

JAVA GUI based Server

I am developing a simple client-server application.
I have previously written a working console application, but when I added GUI and try to start the server, the application hangs.
I have implemented a "console" using JTextPane, and want to print all output messages to this console. Please improve or correct my code, and tell me where I have gone wrong.
package com.module.server;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.net.UnknownHostException;
import java.util.Date;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
public class Entry {
private JFrame frame;
private JTextField textIP;
private JTextField textPort;
private JButton btnNewButton;
/**
* Launch the application.
* #throws
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Entry window = new Entry();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws UnknownHostException
*/
public Entry() throws UnknownHostException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws UnknownHostException
*/
private void initialize() throws UnknownHostException {
frame = new JFrame();
frame.setBounds(100, 100, 704, 493);
frame.setTitle("Server Control Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textIP = new JTextField();
textIP.setBounds(80, 39, 496, 27);
frame.getContentPane().add(textIP);
textIP.setColumns(10);
JLabel lblIpAddress = new JLabel("IP Address");
lblIpAddress.setBounds(10, 45, 77, 14);
frame.getContentPane().add(lblIpAddress);
textPort = new JTextField();
textPort.setBounds(80, 77, 86, 27);
frame.getContentPane().add(textPort);
textPort.setColumns(10);
JLabel lblPort = new JLabel("Port");
lblPort.setBounds(10, 83, 46, 14);
frame.getContentPane().add(lblPort);
JTextPane ConsolePane = new JTextPane();
ConsolePane.setBounds(10, 152, 668, 291);
frame.getContentPane().add(ConsolePane);
JLabel lblConsole = new JLabel("Console:-");
lblConsole.setBounds(10, 127, 92, 26);
frame.getContentPane().add(lblConsole);
JButton btnStart = new JButton("Start Service");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ServerSocket server = null;
try {
server = new ServerSocket(2000);
while(true)
{
ConsolePane.setText("Waiting for Clients.......!");
Socket Client = server.accept();
ConsolePane.setText("Client connected from
"+Client.getRemoteSocketAddress());
OutputStream os = Client.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Welcome to Time Server ......");
dos.writeUTF(new Date().toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnStart.setBounds(422, 77, 116, 27);
frame.getContentPane().add(btnStart);
btnNewButton = new JButton("GET IP & Port");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
InetAddress localhost;
try {
localhost = InetAddress.getLocalHost();
textIP.setText(localhost.getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton.setBounds(260, 79, 152, 23);
frame.getContentPane().add(btnNewButton);
}
}

Write my ComboBox value to file

I've got a problem with this, I've got text from comboBox saved into text variable but now I can't make it to be saved to the file like 'num1' and 'num2' after I click a buttom. I know I am missing something simple - or everything is wrong anyways please help! Thank!
package windowbuilded.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class WiewWindow {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WiewWindow window = new WiewWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WiewWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1, num2, ans2, combo;
num1=Integer.parseInt(textField.getText());
num2=Integer.parseInt(textField_1.getText());
ans2 = num1 + num2;
textField_2.setText(Integer.toString(ans2));
try{
File dir = new File("C:\\test");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileWriter writer = new FileWriter(child, true);
PrintWriter out = new PrintWriter(writer);
out.println(num1);
out.println(num2);
out.close();
}
}
} catch (IOException e) {
// do something
}
}
});
btnNewButton.setBounds(124, 206, 89, 23);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 34, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(124, 34, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(124, 101, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No", "Blah!"}));
String text = (String)comboBox.getSelectedItem();
System.out.println(text);
comboBox.setBounds(265, 101, 121, 20);
frame.getContentPane().add(comboBox);
}
}

Access JLabel from other class , Swingworker

I have 2 classes. One class is for gui and the other class doing some staff.
The second class includes Swingworker. It searches some log files and take some sentence from there. Also in the gui there is a label which writes in Searching.. Please wait.. and when the second class finish the work, it should be changed to Searching is finished.. .
This label name is searchLabeland define in first class. It is private variable.
My purpose is : In the second class there is done method. Inside in this method, I want to do searchLabel.setText("blabla");
How can I do this ? I cannot access. Also doing public JLabel is not a solution I think.
You can easily find that part in the code with searcing /* PROBLEM IS IN HERE */ this string.
Here is the code
This is my gui class :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
public class mainGui extends JFrame {
private JPanel contentPane;
private JTextField userNametextField;
public static JLabel searchLabel,userNameWarningLabel,pathWarningLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainGui frame = new mainGui();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/4;
int y = (dim.height-h)/2;
frame.setLocation(x, y);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 455);
contentPane = new JPanel();
getContentPane().setLayout(null);
setTitle("Role Finding Script");
// Border border;
JLabel lblUsername = new JLabel(" Username :");
lblUsername.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblUsername.setBounds(10, 53, 113, 30);
//Border border = BorderFactory.createRaisedSoftBevelBorder();
// border = BorderFactory.createEtchedBorder();
// lblUsername.setBorder(border);
getContentPane().add(lblUsername);
userNametextField = new JTextField();
userNametextField.setBounds(146, 53, 250, 30);
userNametextField.setFont(new Font("LucidaSans", Font.PLAIN, 13));
getContentPane().add(userNametextField);
userNametextField.setColumns(20);
JLabel lblRole = new JLabel(" Roles :");
lblRole.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblRole.setBounds(10, 124, 113, 30);
// border = BorderFactory.createEtchedBorder();
// lblRole.setBorder(border);
getContentPane().add(lblRole);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setBounds(146, 124, 250, 30);
comboBox.addItem("VR_ANALYST1");
comboBox.addItem("VR_ANALYST2");
comboBox.addItem("VR_ANALYST3");
comboBox.addItem("VR_ANALYST4");
comboBox.addItem("VR_ANALYST5");
comboBox.addItem("VR_ANALYST6");
comboBox.addItem("VR_ANALYST7");
comboBox.addItem("VR_ANALYST8");
comboBox.addItem("VR_ANALYST9");
comboBox.addItem("VR_ANALYST10");
comboBox.addItem("VR_ANALYST11");
comboBox.addItem("VR_ANALYST12");
comboBox.setMaximumRowCount(6);
getContentPane().add(comboBox);
this.searchLabel = new JLabel("Searching.. Please wait..");
searchLabel.setFont(new Font("LucidaSans", Font.BOLD, 13));
searchLabel.setBounds(169, 325, 195, 30);
searchLabel.setVisible(false);
getContentPane().add(searchLabel);
JButton btnNewButton = new JButton("Show Me ");
btnNewButton.setFont(new Font("LucidaSans", Font.BOLD, 13));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(userNametextField.getText() == null || userNametextField.getText().equals("")){
userNameWarningLabel.setText("Please filled in the Username part.");
}else{
searchLabel.setVisible(true);
VolvoMain task = new VolvoMain();
task.execute();
}
}
});
btnNewButton.setBounds(188, 271, 126, 30);
getContentPane().add(btnNewButton);
JLabel lblPath = new JLabel(" Path :");
lblPath.setFont(new Font("Dialog", Font.BOLD, 13));
lblPath.setBounds(10, 195, 113, 30);
getContentPane().add(lblPath);
userNameWarningLabel = new JLabel("");
userNameWarningLabel.setBounds(156, 89, 227, 14);
userNameWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
userNameWarningLabel.setForeground(Color.red);
getContentPane().add(userNameWarningLabel);
JButton btnNewButton_1 = new JButton("...");
btnNewButton_1.setBounds(412, 195, 30, 30);
getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("+");
btnNewButton_2.setBounds(460, 195, 44, 30);
getContentPane().add(btnNewButton_2);
JLabel headerLabel = new JLabel("Find the Role");
headerLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
headerLabel.setHorizontalAlignment(SwingConstants.CENTER);
headerLabel.setBounds(94, 11, 358, 30);
headerLabel.setForeground(Color.red);
getContentPane().add(headerLabel);
pathWarningLabel = new JLabel("");
pathWarningLabel.setForeground(Color.RED);
pathWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
pathWarningLabel.setBounds(156, 236, 227, 14);
getContentPane().add(pathWarningLabel);
}
}
And this is the other class :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.SwingWorker;
public class VolvoMain extends SwingWorker{
private FileInputStream fstream;
private BufferedReader br;
private String username = "HALAA";
private String role = "VR_ANALYST";
private String firstLine = "";
private Pattern regex;
private List<String> stringList = new ArrayList<String>();
private File dir;
private mainGui mg = new mainGui();
//String reg = "\\t'AUR +(" + username + ") .*? /ROLE=\"(" + role + ")\".*$";
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground() throws Exception {
String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String reg = String.format(fmt, username, role);
regex = Pattern.compile(reg);
dir = new File(
"C:"+File.separator+"Documents and Settings"+File.separator+"sbx1807"+File.separator+"Desktop"+File.separator
+"Batu"+File.separator+"Deneme"+File.separator
);
File[] dirs = dir.listFiles();
String[] txtArray = new String[dirs.length];
int z=0;
for (File file : dirs) {
if (file.isDirectory()) {
}else {
if(file.getAbsolutePath().endsWith(".log")){
txtArray[z] = file.getAbsolutePath();
System.out.println(file.getAbsolutePath());
z++;
}
}
int j = 0;
for(int i=0; i<txtArray.length; i++){
if(txtArray[i] != null && !txtArray[i].equals("")){
try{
fstream = new FileInputStream(txtArray[i]);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
/* parse strLine to obtain what you want */
if((j%2)== 0){
firstLine = strLine;
}
if(((j%2) != 0) && regex.matcher(strLine).matches()){
stringList.add(firstLine);
stringList.add(strLine);
}
publish(stringList.size());
j++;
}
publish(stringList.size());
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
for(int k=0; k<stringList.size(); k++){
System.out.println(stringList.get(k));
}
}
return null;
}
#Override
public void done() {
System.out.println("bitti");
// getSearchJLabel().setText("Searching is done..");
// mainGui m = new mainGui();
// m.searchLabel.setText("done");
}
}
Adjust your VolvoMain class so it takes a reference to the JLabel in its constructor. Store this in a private final field and you can use this in the done() method.
public class VolvoMain extends SwingWorker{
// ...
private final JLabel labelToUpdate;
public VolvoMain(JLabel labelToUpdate) {
this.labelToUpdate = labelToUpdate;
}
// ...
#Override
public void done() {
// Update labelToUpdate here
}
The done() method will be invoked on the Event Dispatch Thread, so it will be safe to adjust the label text directly.

Categories