Related
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");
}
}
}
}
I need to build a GUI that will allow users to enter basic details about themselves for a new patient form and have that information saved to a .txt file. This data should then be viewable at a later time, but I can't get the save button to work.
//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
//Main class
public class PatientDetailsWindow{
//Declare variables
public JFrame frame1;
public JPanel panel;
public JButton btnSave, btnExit;
public JLabel lblFirstName, lblSurname, lblGender, lblDOB, lblSmoker, lblMedHistory, lblFSlash1, lblFSlash2, lblImage;
public JTextField txtFirstName, txtSurname, txtGender, txtSmoker, txtMedHistory, txtDOB1, txtDOB2, txtDOB3;
public Insets insets;
public JTextArea textArea = new JTextArea();
public static void main (String args[]){
new PatientDetailsWindow();
}
public PatientDetailsWindow(){
createFrame();
createLabels();
createTextFields();
createButtons();
}
//Create the frame
public void createFrame(){
frame1 = new JFrame ("Personal details");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize (600,600);
panel = new JPanel();
panel.setBackground(Color.gray);
panel.setBounds(0, 0, 600, 600);
panel.setLayout(null);
frame1.add(panel);
frame1.setVisible(true);
}
//Creating Labels
public void createLabels(){
lblFirstName = new JLabel ("First Name: ");
lblFirstName.setBounds(50, 50, 500, 20);
lblFirstName.setForeground(Color.blue);
panel.add (lblFirstName);
lblSurname = new JLabel ("Surname: ");
lblSurname.setBounds(50, 100, 500, 20);
lblSurname.setForeground(Color.blue);
panel.add (lblSurname);
lblGender = new JLabel ("Gender: ");
lblGender.setBounds(50, 150, 500, 20);
lblGender.setForeground(Color.blue);
panel.add (lblGender);
lblDOB = new JLabel ("Date of Birth: ");
lblDOB.setBounds(50, 200, 500, 20);
lblDOB.setForeground(Color.blue);
panel.add (lblDOB);
lblFSlash1 = new JLabel ("/");
lblFSlash1.setBounds(440, 200, 20, 20);
lblFSlash1.setForeground(Color.blue);
panel.add (lblFSlash1);
lblFSlash2 = new JLabel ("/");
lblFSlash2.setBounds(490, 200, 40, 20);
lblFSlash2.setForeground(Color.blue);
panel.add (lblFSlash2);
lblSmoker = new JLabel ("Are you a smoker? ");
lblSmoker.setBounds(50, 250, 500, 20);
lblSmoker.setForeground(Color.blue);
panel.add (lblSmoker);
lblMedHistory = new JLabel ("Any other previous medical history? ");
lblMedHistory.setBounds(50, 300, 500, 20);
lblMedHistory.setForeground(Color.blue);
panel.add (lblMedHistory);
/*ImageIcon image= new ImageIcon("heartandstethoscope.jpg");
JLabel lblImage = new JLabel(image);
panel.add(lblImage);
*/
}
//Creating Text Fields
public void createTextFields(){
txtFirstName = new JTextField (10);
txtFirstName.setBounds(400, 50, 100, 20);
txtFirstName.setForeground(Color.blue);
panel.add (txtFirstName);
txtSurname = new JTextField (10);
txtSurname.setBounds(400, 100, 100, 20);
txtSurname.setForeground(Color.blue);
panel.add (txtSurname);
txtGender = new JTextField (10);
txtGender.setBounds(400, 150, 100, 20);
txtGender.setForeground(Color.blue);
panel.add (txtGender);
txtDOB1 = new JTextField (2);
txtDOB1.setBounds(400, 200, 40, 20);
txtDOB1.setForeground(Color.blue);
panel.add (txtDOB1);
txtDOB2 = new JTextField (2);
txtDOB2.setBounds(450, 200, 40, 20);
txtDOB2.setForeground(Color.blue);
panel.add (txtDOB2);
txtDOB3 = new JTextField (4);
txtDOB3.setBounds(500, 200, 80, 20);
txtDOB3.setForeground(Color.blue);
panel.add (txtDOB3);
txtSmoker = new JTextField (3);
txtSmoker.setBounds(400, 250, 100, 20);
txtSmoker.setForeground(Color.blue);
panel.add (txtSmoker);
txtMedHistory = new JTextField (300);
txtMedHistory.setBounds(400, 300, 100, 60);
txtMedHistory.setForeground(Color.blue);
panel.add (txtMedHistory);
JScrollPane areaScrollPane = new JScrollPane(txtMedHistory);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textArea.setBounds(400, 300, 100, 80);
JScrollPane scroll = new JScrollPane (textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
panel.add(textArea);
}
//Creating buttons
public void createButtons(){
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
btnExit = new JButton ("Exit");
btnExit.setBounds(240, 350, 100, 20);
btnExit.setForeground(Color.blue);
btnExit.addActionListener(new ExitHandler());
panel.add (btnExit);
btnExit.setVisible(true);
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
class SaveHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
try( PrintWriter out = new PrintWriter( "DetailsofPatient.txt" )){
out.println(txtFirstName.getText());
out.println(txtGender.getText());
out.println(txtDOB1.getText());
out.println(txtDOB2.getText());
out.println(txtDOB3.getText());
out.println(txtSmoker.getText());
out.println(txtMedHistory.getText());
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Save successful");
}
}
}
Alright for starters, you didn't add an ActionListener to your save button, so you need to add it like this.
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
Also, in your SaveHandler, your PrintWriter isn't actually printing anything.
Your Code: out.println( ); would not write anything.
Let's say you wanted to write the contents of txtFirstName, you would need to do
out.println(txtFirstName.getText());
Edit: You also need another closing braces at the end of your ExitHandler class
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
You will also then need to remove a closing brace at the end of the program.
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.
I use the following code to retrieve data from msysql database to a JComboBox. It was working properly. My problem is when I execute this code, if I click jCombobox, only one item is shown and it displays the related data from database.. it is not getting all the ids from database to Combobox, so that i can select a particular id and display related data.
package Swings;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.*;
import javax.swing.*;
class Frame3 extends JFrame implements ActionListener,ItemListener
{
private JFrame frame;
JPanel panel=new JPanel();
JButton btn1,btn2,btn3;
JLabel l1, l2, l3, l4, l5, l6, l7;
private JComboBox SummonIdbox;
private JTextField txtcarLicenceNo;
private JTextField txtamount;
private JTextField txtdateFined;
private JTextField txtlocation;
private JTextField txtofficerInCharge;
String dbURL = "jdbc:mysql://localhost:3306/cpss";
String username ="root";
String password = "root";
Connection c = null;
Statement st = null;
ResultSet rs = null;
Frame3()
{
setVisible(true);
setSize(700, 700);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("CPSS Application");
l1 = new JLabel("Update Summon Details");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("SummonId");
l3 = new JLabel("Car LicenceNo:");
l4 = new JLabel("Amount");
l5 = new JLabel("DateFined");
l6 = new JLabel("Location");
l7 = new JLabel("Officer Incharge");
SummonIdbox = new JComboBox();
txtcarLicenceNo = new JTextField();
txtamount = new JTextField();
txtdateFined = new JTextField();
txtlocation = new JTextField();
txtofficerInCharge=new JTextField();
btn1 = new JButton("Update");
btn2 = new JButton("Clear");
btn3= new JButton("Home");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
SummonIdbox.addItemListener(this);
l1.setBounds(500, 30, 400, 30);
l2.setBounds(400, 70, 200, 30);
l3.setBounds(400, 110, 200, 30);
l4.setBounds(400, 150, 200, 30);
l5.setBounds(400, 190, 200, 30);
l6.setBounds(400, 230, 200, 30);
l7.setBounds(400, 270, 200, 30);
SummonIdbox.setBounds(500, 70, 200, 30);
txtcarLicenceNo.setBounds(500, 110, 200, 30);
txtamount.setBounds(500, 150, 200, 30);
txtdateFined.setBounds(500, 190, 200, 30);
txtlocation.setBounds(500, 230, 200, 30);
txtofficerInCharge.setBounds(500, 270, 200, 30);
btn1.setBounds(450, 350, 100, 30);
btn2.setBounds(600, 350, 100, 30);
btn3.setBounds(750, 350, 100, 30);
add(l1);
add(l2);
add(SummonIdbox);
add(l3);
add(txtcarLicenceNo);
add(l4);
add(txtamount);
add(l5);
add(txtdateFined);
add(l6);
add(txtlocation);
add(l7);
add(txtofficerInCharge);
add(btn1);
add(btn2);
add(btn3);
add_summonid(SummonIdbox);
}
#Override
public void actionPerformed(ActionEvent ae ) {
if(ae.getSource() == btn2)
{
txtcarLicenceNo.setText("");
txtamount.setText("");
txtdateFined.setText("");
txtlocation.setText("");
txtofficerInCharge.setText("");
}
else if (ae.getSource() == btn3)
{
SwingMenu s=new SwingMenu();
s.setSize(800,800);
s.setVisible(true);
}
}
void add_summonid(JComboBox SummonIdbox)
{
try
{
//Class.forName("com.mysql.jdbc.Driver");
//System.out.println("Driver is loaded");
c = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connection created");
st=c.createStatement();
rs=st.executeQuery("select Summonid from summon");
while(rs.next())
SummonIdbox.addItem(rs.getInt(1));
// c.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
#Override
public void itemStateChanged(ItemEvent ie) {
int item= (Integer) SummonIdbox.getSelectedItem();
System.out.println(item);
String sql="select carLicenceNo,amount,dateFined,location,officerIncharge from summon where summonId='"+item+"'";
try {
PreparedStatement pst = c.prepareStatement(sql);
//pst.setInt(1,item);
rs=pst.executeQuery();
while(rs.next())
{
txtcarLicenceNo.setText(rs.getString(1));
txtamount.setText(String.valueOf((rs.getDouble(2))));
txtdateFined.setText(rs.getString(3));
txtlocation.setText(rs.getString(4));
txtofficerInCharge.setText(rs.getString(5));
/*System.out.println(rs.getString(1));
System.out.println(rs.getDouble(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));*/
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
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);
}
}