Run method never get executed [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently trying to develop a simple local area network chat feature for the company. But I'm stuck at this point where the run method never get executed in client which previously working fine. It started not working after I restructure the constructor to be able to dispose and visible frame on system tray icon double click. Please let me know where I'm go wrong. I send you the code where it was previously working and current now where it's not working. I can also send the server interface source and other code if needed.
Before structuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
public class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JFrame frame;
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_1, area_2;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
ChatClient(String name, String IP, Login login) {
super(name);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
this.name = name;
this.login = login;
frame = new JFrame("Client - " + name);
frame.setIconImage(bd);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
area_1 = new JTextArea(20, 10);
area_1.setFont(login.notify);
area_1.setLineWrap(true);
area_1.setEditable(false);
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
scroll = new JScrollPane(area_1);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
mainPanel.setLayout(new BorderLayout());
listModel = new DefaultListModel();
list = new JList(listModel);
list.setToolTipText("Client available");
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
frame.getContentPane().add(mainPanel);
mainPanel.add(menuBar);
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(list);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(login.notify);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(80, 360, 150, 15);
charCnt.setFont(small);
scroll.setBounds(5, 30, 390, 300);
scroll2.setBounds(5, 335, 450, 35);
list.setBounds(400, 30, 185, 260);
field_2.setBounds(479, 300, 110, 25);
cb1.setBounds(398, 300, 70, 20);
//button
button_1.setBounds(490, 336, 95, 27);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
thr.start();
} catch (IOException e) {
area_1.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
this.frame.dispose();
System.exit(0);
}
area_2.requestFocus();
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {createAndShowUI(); >>this code here executed properly.
} catch (IOException | HeadlessException e) {
JOptionPane.showMessageDialog(null, "Server has Closed!" + lineSeparator + "Sorry, you've to log out");
System.exit(0);
}
}
After restructuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public final class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_2;
JTextPane chatPane;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2, scroll3;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
Font prv = new Font("Helvetica", Font.ITALIC, 14);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
/**
*
* #param name
* #param IP
* #param login
*/
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
public ChatClient(String name, String IP, Login login) {
super(name);
try {
createAndShowUI(name);
createAndShowGUI(name);
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
} catch (IOException e) {
chatPane.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
System.exit(0);
}
}
public ChatClient() {
// defaultItem1.addActionListener(exitListener);
// defaultItem2.addActionListener(restoreListener);
// this.login = login;
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
chatPane = new JTextPane();
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
listModel = new DefaultListModel();
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setToolTipText("Client available");
list.setVisibleRowCount(5);
scroll = new JScrollPane(chatPane);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
scroll2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll3 = new JScrollPane(list);
scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.setLayout(new BorderLayout());
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(scroll3);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(prv);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(380, 358, 120, 15);
charCnt.setFont(small);
scroll.setBounds(5, 25, 390, 300);
//chatPane.setFocusable(false);
chatPane.setEditable(false);
scroll2.setBounds(5, 325, 485, 48);
scroll3.setBounds(400, 30, 185, 260);
field_2.setBounds(477, 300, 112, 25);
cb1.setBounds(398, 300, 70, 20);
button_1.setBounds(490, 326, 100, 30);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
thr.start();
} catch (Exception e) {
}
area_2.requestFocus(true);
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {
createAndShowUI(); >> this code never run to
Login.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
final class Login {
JFrame frame;
JPanel panel;
JLabel label_1, label_2, label_3, label_4;
JTextField field_1, field_2;
JPasswordField pass;
JButton button_1, button_2;
Font Default = new Font("Comic Sans MS", Font.PLAIN, 12);
Font notify = new Font("Comic Sans MS", Font.BOLD, 12);
Font small = new Font("Sans Serif", Font.ITALIC, 3);
//String IP;
Socket client;
InetAddress ipaddr;
String hostname;
PrintStream toServer;
ChatClient clientObj;
public String gethostString(){
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
}
catch (UnknownHostException e) {
}
return hostname;
}
#SuppressWarnings("CallToPrintStackTrace")
Login() {
String IP = "192.168.10.88";
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
clientObj = new ChatClient(gethostString(), IP, this);
// clientObj.createAndShowGUI(hostname);
// clientObj.createAndShowUI();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Image bd = Toolkit.getDefaultToolkit().getImage("Image/login.png");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
}
}
This is my method createAndShowUI.
public void createAndShowUI(String name) {
this.name = name;
JFrame frame;
frame = new JFrame("Client - " + name);
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
frame.setIconImage(bd);
frame.getContentPane().add(new ChatClient().mainPanel); >> I call the constructor here to draw the frame.
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setSize(600, 400);
frame.setResizable(false);
// frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JComponent getComponent() {
return mainPanel;
}
Any help would be very much appreciated. Cheers!

You created a second no-argument constructor, and nobody is invoking that second constructor. However, you moved the code that starts the thread into that second constructor, so now the thread is not being started anymore().
Perhaps you want to call this method public void init() { instead of public ChatClient() {, and then you call init(); at the end of the first constructor that has 3 arguments.

Related

Connection between MySQL workbench Database and java using Intellij

I am a beginner in java coding and was stuck on a problem that I had been receiving while trying to get the text that I put inside of my Jtextfield to save inside of my MySQL database,
This is my current code, it runs fine but inserts a blank row into my database when I try to save my text
This is my main class:
public class Main{
public static void main(String[] args) {
new MyFrame();
}
}
This is my class for my main menu:
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame{
JLabel label;
JMenu Add;
JMenu remove;
JMenu items;
JMenu vendors;
JMenuBar menuBar;
JMenuItem addCustomer;
JMenuItem addVendors;
JMenuItem addProducts;
JMenuItem removeCustomer;
JMenuItem removeProduct;
JMenuItem removeVendor;
MyFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
label = new JLabel("Inventory Software");
label.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
menuBar = new JMenuBar();
Add = new JMenu("Add");
remove = new JMenu("Remove");
items = new JMenu("Items");
vendors = new JMenu("Vendors");
addCustomer = new JMenuItem("Add Customers");
addVendors = new JMenuItem("Add Vendors");
addProducts = new JMenuItem("Add Products");
removeCustomer = new JMenuItem("Remove Customer");
removeProduct = new JMenuItem("Remove Product");
removeVendor = new JMenuItem("Remove Vendor");
remove.add(removeCustomer);
remove.add(removeProduct);
remove.add(removeVendor);
Add.add(addCustomer);
Add.add(addProducts);
Add.add(addVendors);
menuBar.add(Add);
menuBar.add(remove);
menuBar.add(items);
menuBar.add(vendors);
addCustomer.addActionListener(new WindowAC());
addVendors.addActionListener(new WindowAV());
addProducts.addActionListener(new WindowAP());
removeCustomer.addActionListener(new WindowRC());
removeVendor.addActionListener(new WindowRV());
removeProduct.addActionListener(new WindowRP());
this.setPreferredSize(new Dimension(550, 300));
this.setJMenuBar(menuBar);
this.add(label);
this.pack();
this.setVisible(true);
this.getContentPane().setBackground(Color.WHITE);
this.setLocationRelativeTo(null);
this.setTitle("Intact Communications Inventory Software");
}
}
This is my class for my Add customer tab containing the Jtextfield:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class WindowAC implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if("Add Customers".equals(e.getActionCommand())){
JFrame windowAC = new JFrame();
JLabel label = new JLabel("Name:");
JLabel label1 = new JLabel("Address:");
JLabel label2 = new JLabel("Email:");
JLabel label3 = new JLabel("Tel: ");
JLabel label4 = new JLabel("FAX: ");
JLabel label5 = new JLabel(" ");
JTextField textField = new JTextField();
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
JTextField textField3 = new JTextField();
JTextField textField4 = new JTextField();
JButton button = new JButton("Submit");
String s1, s2;
label.setBounds(50, 100, 100, 50);
label1.setBounds(50, 150, 100, 50);
label2.setBounds(50, 200, 100, 50);
label3.setBounds(50, 250, 100, 50);
label4.setBounds(50, 300, 100, 50);
label5.setBounds(50, 350, 100, 50);
textField.setBounds(150, 110, 400, 30);
textField1.setBounds(150, 160, 400, 30);
textField2.setBounds(150, 210, 400, 30);
textField3.setBounds(150, 260, 400, 30);
textField4.setBounds(150, 310, 400, 30);
button.setBounds(300, 450, 100, 70);
windowAC.add(button);
windowAC.add(label);
windowAC.add(textField);
windowAC.add(label1);
windowAC.add(textField1);
windowAC.add(label2);
windowAC.add(textField2);
windowAC.add(label3);
windowAC.add(textField3);
windowAC.add(label4);
windowAC.add(textField4);
windowAC.add(label5);
windowAC.setSize(750,750);
windowAC.getContentPane().setBackground(Color.WHITE);
windowAC.setTitle("Add Customer info");
windowAC.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windowAC.setVisible(true);
windowAC.setLocationRelativeTo(null);
s1 = textField.getText();
s2 = textField1.getText();
Connection conn = null;
Statement stmt = null;
try {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e1) {
System.out.println(e1);
}
conn = DriverManager.getConnection("jdbc:mysql://localhost/inventoryapp", "root", "P#kist#n1");
System.out.println("Connection is created successfully:");
stmt = conn.createStatement();
String query1 = "INSERT INTO names(first_name,last_name) VALUES ('" + s1 + "','" + s2 + "')";
stmt.executeUpdate(query1);
System.out.println("Record is inserted in the table successfully..................");
} catch (SQLException excep) {
excep.printStackTrace();
} catch (Exception excep) {
excep.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Please check it in the MySQL Table...........");
}
}
}
My code tells me that the data from the Jtextfield has saved fine inside if my datatbase but my database only inserts a blank row instead of what I typed into my textfield

Java multiple menu item with an event listener?

I have two menu items here ,one is for the student information and the another one is for the teacher information.i have added the menu for student and teacher both.
I am struck in the event listener how to add the action to the menu and menu1,suppose when the user click on menu 1 then student information should be displayed and for the menu2 the teacher information action should be performed.i am confused where to add the action listenr and perform the operation for the student and teacher.
I am new to the the event and action listner in java.kindly suggest the solution
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Student");
JMenu menu1 = new JMenu("Teacher");
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
setJMenuBar(menuBar);
menuBar.add(menu);
menuBar.add(menu1);
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
Datestri = tfd.getText();//Getting the unable to convert String to Date error
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
PreparedStatement st = con.prepareStatement("select Name,Fathername,State from student_db where roll_number=? and medium=?");
System.out.println(st);
st.setString(1, str);
st.setDate(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
//Teacher information should be retrieved from the db
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}
Thanks for any help in advance.
Hope, This will help
For JMenu you can use MenuListener
class MenuListenerAdapter implements MenuListener {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("Menu Selected");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("Menu Deselected");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("Menu Canceled");
}
}
Then add MenuListener on menu
menu.addMenuListener(new MenuListenerAdapter());
You can use MouseListener,
Find your solution below, check out console when you click on Student and Teacher Menu
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb, lbd, lb1, lb2, lb3, lb5;
JTextField tf1, tf2, tf3, tf5, tfd;
JButton btn;
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Student");
JMenu menu1 = new JMenu("Teacher");
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
setJMenuBar(menuBar);
menuBar.add(menu);
menuBar.add(menu1);
menu.addMouseListener(new MouseListenerForStudentAndTeacher());
menu1.addMouseListener(new MouseListenerForStudentAndTeacher());
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
// removed code, you can add your code later on
}
public static void main(String args[]) {
new Searchdb();
}
private class MouseListenerForStudentAndTeacher extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == menu) {
System.out.println("Student Menu Clicked");
}
if (e.getSource() == menu1) {
System.out.println("Teacher Menu Clicked");
}
}
}
}

How to make int variable visible to other class from GUI JButton

I'm trying to access the int myInt in this GUI form class from another class. The method does pass the input variable to myInt properly but I have not been able to make it visible to the other java file. I have been reading about scope and class declarations and have been able to muddle along up until now, but I am doing something wrong here. Nothing I have tried has worked.
package com.jdividend.platform.allocation;
import com.ib.client.*;
import com.jdividend.platform.model.*;
import com.jdividend.platform.trader.*;
import com.jdividend.platform.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* Dialog to show the account size allowed info.
*/
public class AllocationDialog extends JDialog {
/* inner class to define the "about" model */
public static class AllocationTableModel extends TableDataModel {
private AllocationTableModel() {
String[] aboutSchema = {"Property", "Value"};
setSchema(aboutSchema);
}
}
public AllocationDialog(JFrame parent) {
super(parent);
init();
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
public void init() {
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle("Allocation - JDividend");
JPanel contentPanel = new JPanel();
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(84, 146, 274, 19);
panel.add(panel_1);
JLabel lblNewLabel = new JLabel("Total account cash and margin that");
panel_1.add(lblNewLabel);
JPanel panel_2 = new JPanel();
panel_2.setBounds(84, 163, 274, 19);
panel.add(panel_2);
JLabel lblJdividendIsAllowed = new JLabel("JDividend is allowed to trade with.");
panel_2.add(lblJdividendIsAllowed);
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(172, 189, 100, 20);
panel.add(formattedTextField);
JButton btnOk = new JButton("OK");
btnOk.setBounds(121, 221, 89, 23);
panel.add(btnOk);
btnOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
int myInt = Integer.parseInt(formattedTextField.getText());
System.out.println(myInt);
//do some stuff
}
catch (NumberFormatException ex) {
System.out.println("Not a number");
//do you want
}
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(238, 220, 89, 23);
panel.add(btnCancel);
formattedTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JButton button = new JButton("OK");
}
});
}
});
}
String serverVersion = "Disconnected from server";
Trader trader = Dispatcher.getInstance().getTrader();
if (trader != null) {
int version = trader.getAssistant().getServerVersion();
if (version != 0) {
serverVersion = String.valueOf(version);
}
}
TableDataModel aboutModel = new AllocationTableModel();
getContentPane().setPreferredSize(new Dimension(450, 400));
Properties properties = System.getProperties();
Enumeration<?> propNames = properties.propertyNames();
while (propNames.hasMoreElements()) {
String key = (String) propNames.nextElement();
String value = properties.getProperty(key);
String[] row = {key, value};
aboutModel.addRow(row);
}
}
}
myInt should be declared inside the class, but outside of any method implementations:
public class AllocationDialog extends JDialog {
public int myInt;
// ...
}

Two way communication between GUI and a Server Client

I'm trying to send a certain string when a button is pressed in my GUI. My Client class is currently running to keep taking string commands from the command line and send them to the server where they will be processed and a response will be returned.
How can I now send the data through my GUI and move the results back to my GUI?
E.g. I have a button called "pickup" which, when clicked will send the string "PICKUP" to the server, through the Client class.
Likewise, the response from the server would be either "SUCCESS" or "FAIL" which would be printed through the Thread "serverResponse" in my Client class and this needs to somehow be sent to an arbitrary method in the playerGUI class as a parameter.
Thanks for any help, sorry for not using the conventional class/method/field naming styles!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class playerGUI {
private JFrame frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private static Client newclient;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.frame.setVisible(true);
newclient = new Client(GUI);
}
/**
* Create the application.
*/
public playerGUI() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 500, 630);
frame.setUndecorated(false); // REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 630);
humanGameWindow.setVisible(false);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I WANT TO SEND THE STRING "PICKUP" TO WHERE THE STARS ARE IN Client.class
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
JButton Look = new JButton("Look");
Look.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
Look.setBackground(new Color(100, 149, 237));
Look.setBounds(40, 514, 100, 40);
humanGameWindow.add(Look);
humanGameWindow.add(pickup);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.DARK_GRAY);
mainMenu.setBounds(0, 0, 500, 630);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
JButton mainMenuQuit = new JButton("Quit");
mainMenuQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mainMenuQuit.setBackground(new Color(100, 149, 237));
mainMenuQuit.setBounds(220, 345, 70, 55);
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
frame.getContentPane().add(humanGameWindow);
frame.getContentPane().add(mainMenu);
frame.setVisible(true);
}
}
This is the Client class, the thread is where I want to send the response to the GUI class to process and display a specific output. The asterisks is where I want to send the text from button presses in the GUI class (there are other buttons I have deleted the code for easier reading!).
import java.net.*;
import java.io.*;
public class Client{
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//I WANT TO SEND "response" TO THE GUI CLASS
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
String sending = *************************
//String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}

The java applet appears blank

I've been working at this problem for hours now, with no results. I cannot seem to get the applet to display properly when viewing the HTML page OR when running the applet through Eclipse. It is always blank. I've been searching for a long time now and decided just to ask.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet{
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public JPanel createContentPane(){
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
//posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
topicGUI.add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150,25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
postPanel.add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70,15);
username.setHorizontalAlignment(0);
postPanel.add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40,15);
topic.setHorizontalAlignment(0);
postPanel.add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70,15);
paragraph.setHorizontalAlignment(0);
postPanel.add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
postPanel.add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
postPanel.add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane (paragraphArea);
scrollParagraph.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
postPanel.add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal + "/n" + paragraphArea + "/n";
}
});
postPanel.add(submitButton);
setVisible(true);
return topicGUI;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("");
Topics display = new Topics();
frame.setContentPane(display.createContentPane());
frame.setSize(500, 270);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
In order to run as an applet, you need to override the init method. You don't need a main method. Just add all you components inside the init method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet {
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
// posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane(paragraphArea);
scrollParagraph
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal
+ "/n" + paragraphArea + "/n";
}
});
add(submitButton);
}
}

Categories