JAVA GUI based Server - java

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);
}
}

Related

Socket Listener - I almost have it

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);
}
}
});

is the method to create simple login wrong

I am a newbie in Java GUI development and I am stuck in the following code.
I am open to suggestions. I am actually trying to create a simple login that gives OK if the password is matched to the number 3124, and otherwise shows the error message. Please help me.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testing window = new testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public testing() {
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_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
final int num;
num=Integer.parseInt(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(num==3124)
{JOptionPane.showMessageDialog(null, "correct");}
else
{JOptionPane.showMessageDialog(null, "wrong");}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}
You were checking the password even before the user has had the chance to enter anything into the text box. You need to get and check the value of num in the event listener code i.e. in actionPerformed. Also, don't convert the password to int (someone may enter some non-numeric string).
This code below works better.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class Testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Testing() {
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_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String num;
num = (password.getText());
if (num.equalsIgnoreCase("3124")) {
JOptionPane.showMessageDialog(null, "correct");
} else {
JOptionPane.showMessageDialog(null, "wrong");
}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
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);
}
}

Cannot create JAR file-Main method not found

I'm trying to create a JAR of the given class.
I am using a tool called JARBuilder as Eclipse was of no help in creating JAR files.
When I try to create the JAR, it says that main method could be found, despite the fact that the main method is clearly defined.
Can someone please advise?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField textField_1;
private JTextField textField_2;
private String name;
private String address;
private int port;
private JTextField textField;
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 348);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(158, 44, 72, 16);
contentPane.add(lblUsername);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setBounds(135, 111, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblServerIp = new JLabel("Server IP");
lblServerIp.setBounds(158, 96, 56, 16);
contentPane.add(lblServerIp);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_1.setText("122.15.200.115");
textField_2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
}
});
textField_2.setBounds(135, 162, 116, 22);
textField_2.setText("8000");
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblPort = new JLabel("Port");
lblPort.setBounds(174, 146, 56, 16);
contentPane.add(lblPort);
JButton btnLogin = new JButton("Login");
btnLogin.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
newWindow();
}
});
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
newWindow();
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogin.setBounds(145, 197, 97, 43);
contentPane.add(btnLogin);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
if(key.getKeyCode()==KeyEvent.VK_ENTER)
{
if(!(textField.getText().equals("")))
{
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
dispose();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
textField.setColumns(10);
textField.setBounds(135, 60, 116, 22);
contentPane.add(textField);
JLabel lblAuthorprashantPandey = new JLabel("Author:Prashant Pandey");
lblAuthorprashantPandey.setBounds(125, 253, 186, 16);
contentPane.add(lblAuthorprashantPandey);
}
public void newWindow(){
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dispose();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

Eclipse Jasper report in Java Swing Application

Good Day, I have created a Java GUI with Eclipse(Java JDK 1.8.0_31 & Eclipse 4.4.1). So then I have installed Jasper report v6 in my same project and created jasper report inside my project.
It is generating report and opening Jasper Viewer window.
See the code below;
DB.java
package jasper1;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DB {
Connection conn = null;
public static class database {
public static String host;
public static String db;
public static String user;
public static String pwd;
}
public static Connection Connector(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://"+database.host+":3306/" +database.db ,database.user,database.pwd);
return conn;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Login Failed.\n" + e);
return null;
}
}
}
form1.java
package jasper1;
import jasper1.DB.database;
import java.awt.EventQueue;
import java.sql.Connection;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class form1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
form1 window = new form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null;
private JTextField text_Host;
private JTextField text_DB;
private JTextField text_User;
private JTextField text_Pwd;
/**
* Create the application.
*/
public form1() {
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("Connect");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
btnNewButton.setText("Please wait...");
}
#Override
public void mouseReleased(MouseEvent e) {
btnNewButton.setText("Connect");
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
database.host = text_Host.getText();
database.db = text_DB.getText();
database.user = text_User.getText();
database.pwd = text_Pwd.getText();
conn = DB.Connector();
if(conn != null){
//JOptionPane.showMessageDialog(null, "Successfully Connected");
String reportPath = "reports/report.jrxml";
try {
JasperReport jr = JasperCompileManager.compileReport(reportPath);
//JOptionPane.showMessageDialog(null, conn);
JasperPrint jp = JasperFillManager.fillReport(jr, null, conn);
JasperViewer.viewReport(jp);
conn.close();
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
return;
}
}
});
btnNewButton.setBounds(73, 167, 130, 23);
frame.getContentPane().add(btnNewButton);
text_Host = new JTextField();
text_Host.setText("localhost");
text_Host.setBounds(93, 32, 110, 20);
frame.getContentPane().add(text_Host);
text_Host.setColumns(10);
text_DB = new JTextField();
text_DB.setText("qatarclean");
text_DB.setBounds(93, 63, 110, 20);
frame.getContentPane().add(text_DB);
text_DB.setColumns(10);
text_User = new JTextField();
text_User.setText("root");
text_User.setBounds(93, 94, 110, 20);
frame.getContentPane().add(text_User);
text_User.setColumns(10);
text_Pwd = new JTextField();
text_Pwd.setText("supun123");
text_Pwd.setBounds(93, 125, 110, 20);
frame.getContentPane().add(text_Pwd);
text_Pwd.setColumns(10);
JLabel lblHost = new JLabel("Host");
lblHost.setBounds(38, 31, 46, 23);
frame.getContentPane().add(lblHost);
JLabel lblDatabase = new JLabel("Database");
lblDatabase.setBounds(38, 63, 56, 20);
frame.getContentPane().add(lblDatabase);
JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(38, 94, 67, 23);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(38, 125, 56, 20);
frame.getContentPane().add(lblPassword);
}
}
The questions are:
Is there any way to view this report inside my form object?.
How can I compile this to one file to work in cross platform? I tried to export it to .Jar(Executable Jar) file. But it doesn't include report.jrxml. It is not secure to keep jrxml file outside because it's user readable. How can I compile the project more secure?
What are the exact Jasper Library jar files to add in the project? I have added all jars in jasperreports-6.0.0\dist and jasperreports-6.0.0\lib. When I export it to Executable Jar, file size will be more than 50MB.
If anyone has alternate solution like BIRT Reports, Kindly answer these questions instead of Jasper Reports.

Categories