triggering java events from different classes - java

so i have this JFrame window that has a button that opens a different JFrame, the goal from the second window is upon clicking its ok button a table refresh in the first window, but i'm having a hard time solving the issue and didn't find any answer after about an hour of searching (it's not a lot i know but i'm pressed for time). so this is my code and i hope you guys help me out.
the code for the first window:
// the event that i want to trigger
public void refreshTable() {
try {
ResultSet rs = new dbcon().getResultSet("select * from users", new Vector<Object>());
Vector<Vector<Object>> v = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> element = new Vector<Object>();
element.add(rs.getInt("id"));
element.add(rs.getString("name"));
element.add(rs.getString("uname"));
element.add(rs.getString("pwd"));
element.add(rs.getString("date"));
element.add(rs.getInt("admin"));
v.add(element);
}
DefaultTableModel md = (DefaultTableModel) table.getModel();
md.setRowCount(0);
for(int i=v.size()-1;i>=0;i--) {
md.addRow(v.elementAt(i));
}
}catch(Exception exp) {
exp.getLocalizedMessage();
}
}
//the event where the second window is opened
else if(e.getSource() == mod) {
int id = (int) table.getModel().getValueAt(table.getSelectedRow(),0);
String user = (String) table.getModel().getValueAt(table.getSelectedRow(),2);
String pass = (String) table.getModel().getValueAt(table.getSelectedRow(),3);
new Edits().changeUser(user, pass, id);
this.refreshTable();
}
and this is the code for the second window:
//the frame of the second window
public void changeUser(String user,String pass, int id) {
//init frame
this.setTitle("Change User Login");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JFrame.setDefaultLookAndFeelDecorated(false);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/6-this.getSize().width/2, dim.height/16-this.getSize().height/2);
this.setSize(400, 290);
this.setResizable(false);
this.setVisible(true);
//change sizes
Dimension labels = new Dimension(150,25);
Dimension inputs = new Dimension(200,25);
Dimension btn = new Dimension(80,35);
Dimension btn1 = new Dimension(120,35);
//labels size
currentUser.setSize(labels);
currentUser.setMaximumSize(labels);
currentUser.setMinimumSize(labels);
currentUser.setPreferredSize(labels);
changeUser.setSize(labels);
changeUser.setMaximumSize(labels);
changeUser.setMinimumSize(labels);
changeUser.setPreferredSize(labels);
currentPass.setSize(labels);
currentPass.setMaximumSize(labels);
currentPass.setMinimumSize(labels);
currentPass.setPreferredSize(labels);
changePass.setSize(labels);
changePass.setMaximumSize(labels);
changePass.setMinimumSize(labels);
changePass.setPreferredSize(labels);
//inputs size
oldUser.setSize(inputs);
oldUser.setMaximumSize(inputs);
oldUser.setMinimumSize(inputs);
oldUser.setPreferredSize(inputs);
newUser.setSize(inputs);
newUser.setMaximumSize(inputs);
newUser.setMinimumSize(inputs);
newUser.setPreferredSize(inputs);
oldPass.setSize(inputs);
oldPass.setMaximumSize(inputs);
oldPass.setMinimumSize(inputs);
oldPass.setPreferredSize(inputs);
newPass.setSize(inputs);
newPass.setMaximumSize(inputs);
newPass.setMinimumSize(inputs);
newPass.setPreferredSize(inputs);
//button sizes
okUser.setSize(btn1);
okUser.setMaximumSize(btn1);
okUser.setMinimumSize(btn1);
okUser.setPreferredSize(btn1);
closeUser.setSize(btn);
closeUser.setMaximumSize(btn);
closeUser.setMinimumSize(btn);
closeUser.setPreferredSize(btn);
//set layout
this.setLayout(new FlowLayout(FlowLayout.CENTER,10,15));
//add components
this.add(currentUser);
this.add(oldUser);
this.add(changeUser);
this.add(newUser);
this.add(currentPass);
this.add(oldPass);
this.add(changePass);
this.add(newPass);
this.add(okUser);
this.add(closeUser);
//button & input configuration
oldUser.setEditable(false);
oldUser.setText(user);
oldPass.setEditable(false);
oldPass.setText(pass);
Id.setValue(id);
newUser.setText(user);
newPass.setText(pass);
okUser.addActionListener(this);
closeUser.addActionListener(this);
}
//the action of the second window
else if(e.getSource() == okUser) {
String user = oldUser.getText();
String pass = oldPass.getText();
int id = (int) Id.getValue();
if(!newUser.getText().equals("") && !newPass.getText().equals("")) {
try {
Vector<Object> params = new Vector<Object>();
params.add(newUser.getText());
params.add(newPass.getText());
params.add(id);
new dbcon().setUpdates("update users set uname = ?, pwd = ? where id = ?", params);
JOptionPane.showMessageDialog(null, "User Informations Updated");
this.dispose();
}catch(Exception exp) {
exp.printStackTrace();
}
}else {
JOptionPane.showMessageDialog(null, "Please make sure to fill out all the fields!");
}
}
i hope you guys be able to help me out because it's for a school project due in 5 hours. thank you all for your time :D

Related

Reset JTable depending on content (number of rows)

I have a JTable inside a JPanel which in turn is in a Jframe. The JTable loads users from a table (database in MySQL).
I have a search engine using DNIs in which key-to-key, with a KeyTyped event, is updating the contacts in the table, and show only those that meet the browser pattern (JTextField). If there are only 2-3-4 clients, the table is not resized to the customer size, but fills the rest of the table with a gray background. (see image). How could the lower bound of the table be reset?
Code:
public class Listado_clientes1 extends javax.swing.JFrame{
private TableRowSorter<DefaultTableModel> TRSFiltro;
public Listado_clientes1() {
this.getContentPane().setBackground(Color.orange);
panel_top.setBackground(Color.orange);
tabla_clientes.setPreferredScrollableViewportSize(
new Dimension(tabla_clientes.getPreferredSize().width, tabla_clientes.getRowHeight()*20)
);
try {
DefaultTableModel modelo = new DefaultTableModel();
tabla_clientes.setModel(modelo);
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = Conexiones.conexion_a_BBDD("agenda");
String sql = "SELECT dni, nombre, apellidos, telefono, direccion, ciudad, email FROM clientes";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsMd = (ResultSetMetaData) rs.getMetaData();
int cantidadColumnas = rsMd.getColumnCount();
modelo.addColumn("DNI");
modelo.addColumn("NOMBRE");
modelo.addColumn("APELLIDOS");
modelo.addColumn("TLFONO");
modelo.addColumn("DIRECCION");
modelo.addColumn("CIUDAD");
modelo.addColumn("EMAIL");
while (rs.next()) {
Object[] filas = new Object[cantidadColumnas];
for (int i=0; i<cantidadColumnas; i++) {
filas[i] = rs.getObject(i+1);
}
modelo.addRow(filas);
}
} catch (SQLException ex) {
System.err.println(ex.toString());
}
}
/**
* Filtrar: Buscar por DNI.
*/
public void filtrar_dni() {
int columna = 0; //Es la fila del DNI.
TRSFiltro.setRowFilter(RowFilter.regexFilter(textfield_buscar.getText(), columna));
}
private void textfield_buscarKeyTyped(java.awt.event.KeyEvent evt) {
Character letra = evt.getKeyChar();
evt.setKeyChar(Character.toUpperCase(letra));
textfield_buscar.addKeyListener(new KeyAdapter(){
public void keyReleased(final KeyEvent e){
String texto = (textfield_buscar.getText());
textfield_buscar.setText(texto);
filtrar_dni();
}
});
TRSFiltro = new TableRowSorter<DefaultTableModel>((DefaultTableModel) tabla_clientes.getModel());
tabla_clientes.setRowSorter(TRSFiltro);
}
}
Outline / Scheme:
Any time the number of rows in the view of the table changes you need to recalculate the
preferred scrollable viewport size of the table. Once this size is recalculated you need to invoke the layout manager of the panel containing the table:
A reusable method would be something like:
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
So after setting the row filter you could use:
tabla_clientes.setRowSorter(TRSFiltro);
resetTablePreferredScrollableViewportSize(tabla_clientes, 10);
Now the scroll pane should be sized to display up to 10 rows after which the scrollbar of the scroll pane will appear.
Edit:
I don't know how to put a reproducible example
Then you don't understand what your problem is.
Your question is that you want to:
Reset JTable (size) depending on number of rows
So the data is irrelevant, only the number of rows is relevant.
It is easy to test this because you can create a DefaultTableModel with a specified number of rows.
Below is a simple MRE. To test you:
enter a number in the text field
press enter
The table will be resized to display the specified number of rows. If the number is greater that 10 the table size will be fixed and a scrollbar will appear:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JTextField textField;
JTable table;
public SSCCE()
{
setBackground(Color.YELLOW);
textField = new JTextField(5);
add(textField);
table = new JTable(new DefaultTableModel(0, 4));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
add( new JScrollPane(table) );
textField.addActionListener((e) ->
{
int rows = Integer.parseInt( textField.getText() );
table.setModel( new DefaultTableModel(rows, 4) );
resetTablePreferredScrollableViewportSize(table, 10);
});
}
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// frame.pack();
frame.setSize(500, 250);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

Trouble with listener in Java. I have a drop down box not passing the users selection like I need

I have a project for class due this Wednesday and am having trouble with a few things: I have two if else statements that control the values presented in two different drop down menus. To me, it appears I'm not getting the information of of the previous drop down(there are two drop downs in which affects the values presented in the next).
Here's my code thus far:
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
int number = Integer.parseInt((String) selection);
if(number>2)
{
style=(style2);
}
else
{
style=(style1);
}
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
roomtype_string=(String) room_type.getSelectedItem();
room_type.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Room Style Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection2 = (String) room_type.getSelectedItem();
if(selection2.equals("Cabin"))
{
room_number=(cabin_string);
}
else
{
room_number=(suite_string);
}
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
roomselected = (String) room_list.getSelectedItem();
room_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection3 = (String) room_list.getSelectedItem();
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
dining_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection4 = (String) dining_list.getSelectedItem();
NOTE: I have since rewritten my code, still no dice:
` //Creates subPanel2 with Occupancy, Room Type, Room, and Dining Time request
JPanel subpanel = new JPanel();
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
Occupancy_Listener occupancy = new Occupancy_Listener();
occupancy_list.addActionListener(occupancy);
//updateStyle(occupancy_string[occupancy_list.getSelectedIndex()]);
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
Style_Listener styleListen = new Style_Listener();
room_type.addActionListener(styleListen);
//updateNumber(style[room_type.getSelectedIndex()]);
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
Room_Listener room = new Room_Listener();
room_list.addActionListener(room);
//updateRoom(room_number[room_list.getSelectedIndex()]);
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
Din_Listener dining = new Din_Listener();
dining_list.addActionListener(dining);
//updateDin(dining_string[dining_list.getSelectedIndex()]);
...
...
...
...
...
}
private class Occupancy_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
System.out.println(selection);
System.out.println(style[0]);
System.out.println(room_number[0]);
updateStyle(selection);
}
}
private class Style_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateNumber(selection);
}
}
private class Room_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateRoom(selection);
}
}
private class Din_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateDin(selection);
}
}
protected void updateStyle(String pick)
{
String[] style1 ={"Cabin", "Suite"};
String[] style2 ={"Suite"};
//ocu_string=pick;
number = Integer.parseInt(pick);
if(number>2)
{
style=style2;
}
else
{
style=style1;
}
}
protected void updateNumber(String pick)
{
String[] cabin_string = {"11-1","11-2","11-3","11-4","11-5","11-6","11-7","11-8","11-9","11-10"};
String[] suite_string = {"11-S1","11-S2"};
type=pick;
if(type.equals("cabin"))
{
room_number=cabin_string;
}
else
{
room_number=suite_string;
}
}
protected void updateRoom(String pick)
{
room_num=pick;
}
protected void updateDin(String pick)
{
din_time=pick;
}
//public String getPopulation()
{
//return ocu_string;
}
This might be what your are asking. You select an item from the first combo box and it populates items in a second combo box:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You may be confused by the fact that code inside anonymous classes (or local classes) is not executed at the same time as the code around it.
So in a code that looks like:
A a = new A();
a.setSomething( new B() {
public void bMethod() {
// Run stuff
}
} );
C c = a.getSomething();
The "Run stuff" part is not ran now. An object is created, with a method that can be used later inside it, and that object is passed into a. The method is not going to run until something specifically calls it. When you get to the getSomething(), the "Run stuff" part has not run.
So in your code:
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
You create the occupancy list, you create an action listener for it, and store that action listener inside your occupancy list. But none of the stuff written inside the actionPerformed() method is going to run until the GUI is displayed, the user selects something, and the event is fired.
GUI programming is different than console programming where you call "scan()" and then the program just stops and waits for something to be entered. You first prepare the GUI, and when you display it, the various listeners are called based on what the user does.
So your code jumps straight to the occupancy_list.getSelectedItem() before the list has even been added to the GUI, and of course, nothing is selected, nothing is displayed, yet, so the other drop-down lists are created way before the user even sees the GUI.
This is true for all the action listeners in the code.
The proper way to write an action listener is to think what will be the conditions when the GUI is already running. Your action listeners merely set values in local variables that are going to be discarded. Instead, they should do the things that you want to do when the user makes a selection, right inside the action listener.
This means that the action listener for this combo box will have to create the other lists and add them to the GUI, revalidate and repaint it. Or it may simply modify the other lists which will be created already, depending on what you think is best. But they will have to access those lists, and therefore the lists have to be defined as fields of the surrounding class, and accessed inside the action listener. Note that you can also define a method that does this and call it from inside the action listener.
My suggestion would be to create a simple GUI first with just the first combo box and make it change something simple based on the selection. You can follow the Oracle Tutorial, for example. After you understand how to write an action listener that changes something simple, expand your program to add the other lists and manipulate them from the action listener.

ArrayList , JFrame, JLabel

I am trying to create and simple program that has the user input 4 fields using the JFrame and textfields. Save those into a class. Put that class into an ArrayList (So they have the option to delete / or add more "classes" to it later). Then display all the contents of the ArrayList on one Frame.
I got the four fields to work I believe , but the part where the ArrayList contents are supposed to be displayed is not working ( I get a blank frame ).
this is my add into the arrayList ..
public void newEntryFrame()
{
JFrame entryFrame = new JFrame("Passafe");
entryFrame.setVisible(true);
entryFrame.setSize(500, 500);
entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
entryFrame.setLocationRelativeTo(null);
entryFrame.setLayout(new FlowLayout());
header.setFont(new Font("Serif", Font.BOLD, 16));
entryFrame.add(header);
entryFrame.add(nameLabel);
entryFrame.add(nametf);
entryFrame.add(usernameLabel);
entryFrame.add(usernametf);
entryFrame.add(passwordLabel);
entryFrame.add(passwordtf);
entryFrame.add(descriptionLabel);
entryFrame.add(descriptiontf);
entryFrame.add(enterButton);
enterButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
JOptionPane.showMessageDialog(null, "SAVED");
}
else if(source == okButton)
{
JOptionPane.showMessageDialog(null, "Ok Button Works");
}
}
this is what I have to display the arrayList.
public void viewEntryFrame()
{
JFrame viewFrame = new JFrame("Passafe");
viewFrame.setSize(500, 500);
viewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
viewFrame.setLocationRelativeTo(null);
viewFrame.setLayout(new FlowLayout());
viewFrame.add(listHeader);
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
viewFrame.add(okButton);
okButton.addActionListener(this);
viewFrame.setVisible(true);
}
I might be doing this completely wrong if so could you point me in the right direction.
I don't think you ever called setContentPane() A JFrame has only one component in the main part of it. You have to create a JPanel to which you can add all of the components you want, then add that to your JFrame.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(/**whatever you want in your JFrame**/);
//...
panel.add(/**whatever you want in your JFrame**/);
frame.setContentPane(panel);
You never seem to be adding anything to your entries list...
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
// Nope, nothing here...
JOptionPane.showMessageDialog(null, "SAVED");
}
//...
}
Also, this is very dangrouos...
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Rather the relying on the actual side of the ArrayList, you relying on some other variable, which may or may not equal the actual size, instead you should be using ArrayList#size, for example
for(int i = 0; i < entries.size(); ++i)
{
newEntry tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Or if you're using Java 5+...
for(newEntry tempView : enties)
{
viewFrame.add(tempView.display);
}

How to call a Jmenu screen after successfulley login in java swing

Please see the below codem I am trying to call a Jmenu class after successful log in
Login :
public class Login {
Connection con;
Statement st;
ResultSet rs;
JFrame f = new JFrame ("User Login");
JLabel l = new JLabel ("UserName:");
JLabel l1 = new JLabel ("Password:");
JTextField t = new JTextField (10);
JTextField t1 = new JTextField (10);
JButton b = new JButton ("Login");
public Login ()
{
connect ();
frame ();
}
public void connect ()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:Joy_DB";
con = DriverManager.getConnection(db);
st = con.createStatement ();
}
catch (Exception ex)
{
}
}
public void frame ()
{
f.setSize (600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible (true);
JPanel p = new JPanel ();
p.add (l);
p.add (t);
p.add (l1);
p.add (l);
p.add (t1);
p.add (b);
f.add (p);
b.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e)
{
try
{
String user = t.getText (). trim ();
String pass = t1.getText (). trim ();
String sql = "select User,Password from Table2 where User = '"+user+"' and Password = '"+pass+"'";
rs = st.executeQuery(sql);
int count = 0;
while (rs.next())
{
count = count +1;
}
if (count == 1 )
{
JOptionPane.showMessageDialog(null,"User Found");
//JMenuDemo M = new JMenuDemo ();
}
else if (count > 1)
{
JOptionPane.showMessageDialog(null, "Duplicate User !");
}
else
{
JOptionPane.showMessageDialog (null,"User does not exist");
}
}
catch (Exception ex)
{
}
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Login ();
//JMenuDemo M = new JMenuDemo ();
// TODO code application logic here
}
}
How can I call the J menu frame after successful log in by using above codem
Please help
I will send the other class which is Jmenu ia a while
Define a LoginPanel with all the logic required to collect the user details
Create another panel that contains your application components and logic.
Use a JDialog to display the login panel. It will block the execution of the code until the dialog is closed
Based on the state of the LoginPane, you would either (possibly) exit the application (failed login) or continue running the application.
Add application panel to a JFrame and make it visible
See How to make dialogs for more details.
You may also want to use PreparedStatement to access information from the database

proper way to listen to key presses java

What is the best way to handle key presses in Java? I was trying to set up my KeyListener code but then I saw online KeyBinding is what should be used but after reading
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
and not being able to find any tutorials online I am even more confused.
Here is what i have been trying:
frame = new JFrame("Jay's Game Title");
Container panel = (JPanel)frame.getContentPane();
...
panel.setFocusable(true);
panel.requestFocus();
panel.addKeyListener(this);//TODO:fix me please, this is not working
frame.setSize(1024, 768);
frame.setVisible(true);
frame.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
but to no avail. Any help is much appreciated and in the meantime I will continue to look over others' posts and pull more of my hair out.
note: my code for my buttons work just great, and I would love to have my keypresses handled in another keypresses.java file or something to keep it organized
package com.jayavon.game.client;
/****************************************************************
* Author : ***REMOVED***
* Start Date : 09/04/2011
* Last Update : 10/04/2011
*
* Description
* This is the video game application
* This application is used to sending and receiving the messages
* and all of the game data(soon, hopefully :p).
*
* Remarks
* Before running the client application make sure the server is
* running.
******************************************************************/
import javax.swing.*;
import java.awt.Container;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
public class MyClient extends JFrame implements ActionListener, KeyListener{
JFrame frame;
JTextField chatBoxTxt;
JButton sendButton, exitButton, onlineButton, backpackButton, characterButton, helpButton, optionsButton, questsButton, skillsButton;
JInternalFrame skillsFrame, onlineFrame;
DefaultListModel modelChatList;
JList listForChat;
JScrollPane chatScrollPane;
DefaultListModel modelUserList;
JList listForUsers;
JScrollPane userListScrollPane;
String name, password;
Socket s, s1, s2;
DataInputStream messageIn;
DataOutputStream messageOut;
DataInputStream userNameIn;
DataOutputStream userNameOut;
DataOutputStream userLogOut;
MyClient(String name, String password) throws IOException{
this.name = name;
initGUI();
s = new Socket("localhost",1004); //creates a socket object
s1 = new Socket("localhost",1004);
s2 = new Socket("localhost",1004);
//create input-stream for a particular socket
messageIn = new DataInputStream(s.getInputStream());
//create output-stream
messageOut = new DataOutputStream(s.getOutputStream());
//sending a message for login
messageOut.writeUTF(name + " has joined the game.");
userLogOut = new DataOutputStream(s1.getOutputStream());
userNameOut = new DataOutputStream(s2.getOutputStream());
userNameIn = new DataInputStream(s2.getInputStream());
//creating a thread for maintaining the list of user name
MyUserNameReciever userNameReciever = new MyUserNameReciever(userNameOut, modelUserList, name, userNameIn);
Thread userNameRecieverThread = new Thread(userNameReciever);
userNameRecieverThread.start();
//creating a thread for receiving a messages
MyMessageReciever messageReciever = new MyMessageReciever(messageIn, modelChatList);
Thread messageRecieverThread = new Thread(messageReciever);
messageRecieverThread.start();
}
public void initGUI(){
frame = new JFrame("Jay's Game Title");
Container panel = (JPanel)frame.getContentPane();
chatBoxTxt = new JTextField();
panel.add(chatBoxTxt);
chatBoxTxt.setBounds(5,605,650,30);
chatBoxTxt.setVisible(false);
sendButton = new JButton("Send");
sendButton.addActionListener(this);
panel.add(sendButton);
sendButton.setBounds(260,180,90,30);
modelChatList = new DefaultListModel();
listForChat = new JList(modelChatList);
chatScrollPane = new JScrollPane(listForChat);
panel.add(chatScrollPane);
chatScrollPane.setBounds(5,640,650,80);
modelUserList = new DefaultListModel();
listForUsers = new JList(modelUserList);
userListScrollPane = new JScrollPane(listForUsers);
userListScrollPane.setSize(100,250);
userListScrollPane.setVisible(false);
backpackButton = new JButton(new ImageIcon("images/gui/button_backpack.png"));
backpackButton.addActionListener(this);
backpackButton.setBounds(660,686,33,33);
backpackButton.setBorderPainted(false);backpackButton.setFocusPainted(false);
backpackButton.setToolTipText("Backpack[B]");
panel.add(backpackButton);
characterButton = new JButton(new ImageIcon("images/gui/button_character.png"));
characterButton.addActionListener(this);
characterButton.setBounds(695,686,33,33);
characterButton.setBorderPainted(false);characterButton.setFocusPainted(false);
characterButton.setToolTipText("Character[C]");
panel.add(characterButton);
skillsButton = new JButton(new ImageIcon("images/gui/button_skills.png"));
skillsButton.addActionListener(this);
skillsButton.setBounds(730,686,33,33);
skillsButton.setBorderPainted(false);skillsButton.setFocusPainted(false);
skillsButton.setToolTipText("Skills[V]");
panel.add(skillsButton);
questsButton = new JButton(new ImageIcon("images/gui/button_quests.png"));
questsButton.addActionListener(this);
questsButton.setBounds(765,686,33,33);
questsButton.setBorderPainted(false);questsButton.setFocusPainted(false);
questsButton.setToolTipText("Quests[N]");
panel.add(questsButton);
onlineButton = new JButton(new ImageIcon("images/gui/button_online.png"));
onlineButton.addActionListener(this);
onlineButton.setBounds(800,686,33,33);
onlineButton.setBorderPainted(false);onlineButton.setFocusPainted(false);
onlineButton.setToolTipText("Online List[U]");
panel.add(onlineButton);
helpButton = new JButton(new ImageIcon("images/gui/button_help.png"));
helpButton.addActionListener(this);
helpButton.setBounds(835,686,33,33);
helpButton.setBorderPainted(false);helpButton.setFocusPainted(false);
helpButton.setToolTipText("Help[I]");
panel.add(helpButton);
optionsButton = new JButton(new ImageIcon("images/gui/button_options.png"));
optionsButton.addActionListener(this);
optionsButton.setBounds(870,686,33,33);
optionsButton.setBorderPainted(false);optionsButton.setFocusPainted(false);
optionsButton.setToolTipText("Options[O]");
panel.add(optionsButton);
exitButton = new JButton(new ImageIcon("images/gui/button_exit.png"));
exitButton.addActionListener(this);
exitButton.setBounds(905,686,33,33);
exitButton.setBorderPainted(false);exitButton.setFocusPainted(false);
exitButton.setToolTipText("Exit[none]");
panel.add(exitButton);
skillsFrame = new JInternalFrame("Skills", true, true, false, false);
skillsFrame.setBounds(600, 10, 400, 500);
skillsFrame.setVisible(false);
panel.add(skillsFrame);
onlineFrame = new JInternalFrame("Users", true, true, false, false);
onlineFrame.setContentPane(userListScrollPane);
onlineFrame.setBounds(850, 10, 150, 300);
onlineFrame.setVisible(false);
panel.add(onlineFrame);
panel.setLayout(null);
panel.setFocusable(true);
panel.requestFocus();
panel.addKeyListener(this);//TODO:fix me please, this is not working
frame.setSize(1024, 768);
frame.setVisible(true);
frame.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
// sending the messages
if(e.getSource() == sendButton && chatBoxTxt.isVisible() == false){
chatBoxTxt.setVisible(true);
chatBoxTxt.requestFocus(true);
} else if (e.getSource() == sendButton && chatBoxTxt.isVisible() == true){
String str = "";
str = chatBoxTxt.getText();
if (str != ""){
str = name + ": > " + str;
try{
messageOut.writeUTF(str);
System.out.println(str);
messageOut.flush();
}catch(IOException ae)
{System.out.println(ae);}
}
//and hide chatBoxTxt
chatBoxTxt.setText("");
chatBoxTxt.setVisible(false);
}
// show user list
if (e.getSource() == onlineButton){
if (userListScrollPane.isVisible()){
userListScrollPane.setVisible(false);
} else {
userListScrollPane.setVisible(true);
}
if (onlineFrame.isVisible()){
onlineFrame.setVisible(false);
} else {
onlineFrame.setVisible(true);
}
}
// show skill list
if (e.getSource() == skillsButton){
if (skillsFrame.isVisible()){
skillsFrame.setVisible(false);
} else {
skillsFrame.setVisible(true);
}
}
// client logout
if (e.getSource() == exitButton){
int exit = JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?");
if (exit == JOptionPane.YES_OPTION){
frame.dispose();
try{
//sending the message for logout
messageOut.writeUTF(name + " has logged out.");
userLogOut.writeUTF(name);
userLogOut.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
}
}
public void windowClosing(WindowEvent w){
try{
userLogOut.writeUTF(name + " has logged out.");
userLogOut.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
#Override
public void keyPressed(KeyEvent e) {
int id = e.getID();
//open up chatBoxTxt for typing
if (id == KeyEvent.VK_ENTER && !chatBoxTxt.isVisible()){
chatBoxTxt.setVisible(true);
chatBoxTxt.requestFocus(true);
} //it is open so want to send text
else if (id == KeyEvent.VK_ENTER && chatBoxTxt.isVisible()) {
//send message
String str = "";
str = chatBoxTxt.getText();
//make sure there is a message
if (str.length() > 0){
chatBoxTxt.setText("");
str = name + ": > " + str;
try{
messageOut.writeUTF(str);
System.out.println(str);
messageOut.flush();
}catch(IOException ae)
{System.out.println(ae);}
}
//and hide chatBoxTxt
chatBoxTxt.setVisible(false);
} //press (Map) key without chatBoxTxt being open
else if (id == KeyEvent.VK_M && !chatBoxTxt.isVisible()){
} //press (Character) key without chatBoxTxt being open
else if (id == KeyEvent.VK_C && !chatBoxTxt.isVisible()){
} //press (Backpack) key without chatBoxTxt being open
else if (id == KeyEvent.VK_B && !chatBoxTxt.isVisible()){
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
// class is used to maintain the list of user name
class MyUserNameReciever implements Runnable{
DataOutputStream userNameOut;
DefaultListModel modelUserList;
DataInputStream userNameIn;
String name, lname;
ArrayList alname = new ArrayList(); //stores the list of user names
ObjectInputStream obj; // read the list of user names
int i = 0;
MyUserNameReciever(DataOutputStream userNameOut, DefaultListModel modelUserList, String name, DataInputStream userNameIn){
this.userNameOut = userNameOut;
this.modelUserList = modelUserList;
this.name = name;
this.userNameIn = userNameIn;
}
public void run(){
try{
userNameOut.writeUTF(name); // write the user name in output stream
while(true){
obj = new ObjectInputStream(userNameIn);
//read the list of user names
alname = (ArrayList)obj.readObject();
if(i>0)
modelUserList.clear();
Iterator i1 = alname.iterator();
System.out.println(alname);
while(i1.hasNext()){
lname = (String)i1.next();
i++;
//add the user names in list box
modelUserList.addElement(lname);
}
}
}catch(Exception oe){}
}
}
//class is used to received the messages
class MyMessageReciever implements Runnable{
DataInputStream messageIn;
DefaultListModel modelChatList;
MyMessageReciever(DataInputStream messageIn, DefaultListModel modelChatList){
this.messageIn = messageIn;
this.modelChatList = modelChatList;
}
public void run(){
String incommingMessage = "";
while(true){
try{
incommingMessage = messageIn.readUTF(); // receive the message from server
// add the message in list box
modelChatList.addElement(incommingMessage);
/* forces chat to bottom of screen :TODO but doesn't allow scrolling up
chatScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}});*/
}catch(Exception e){}
}
}
}
}
and not being able to find any tutorials online I am even more confused.
That link is a tutorial. Unless you ask a specific question we don't know what you don't understand.
my code for my buttons work just great
It looks like you want the Enter key to do the same processing as clicking on a button. In this case the simple solution is to add an ActionListener to the text field instead of using Key Bindings. You should NOT even consider using a KeyListener for this.
Of course this means you need to redesign your program to use a different ActionListener for each button. So you need "Send", "Online", "Skills", and "Exit" ActionListeners. Then the "Send" ActionListener can be used by both the send button and the text field.
Edit:
for example: the user can hit (VK_V) or click the skills button to show the skills internal frame
You would use Key Bindings for this. You can do the bindings manually as described in the tutorial.
Or, an easier solution is to use a JMenu with menu items to invoke your Actions. Then you can just set an Accelerator for the menu item. Read the section from the Swing tutorial on How to Use Menus for more information.
Any further help will require you to post your SSCCE,

Categories