How to access a variable from a different class [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to access the value stored in "tf" from another class, once the user has typed in his message.
It's being a while since I have worked with Java, so, I am just doing this project for fun (not my code, I am just editing it from a tutorial).
I have tried so many things and researched a lot to do with methods and objects, I feel like I have being so close. The value I am trying to access is in "tf" on line:
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText()));
tf.setText("");
return;
My goal is just to print the string from "tf" in another class.
public class ClientGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
// will first hold "Username:", later on "Enter message"
private JLabel label;
// to hold the Username and later on the messages
private JTextField tf;
// to hold the server address an the port number
private JTextField tfServer, tfPort;
// to Logout and get the list of the users
private JButton login, logout, whoIsIn;
// for the chat room
private JTextArea ta;
// if it is for connection
private boolean connected;
// the Client object
private Client client;
// the default port number
private int defaultPort;
public String userMessage;
private String defaultHost;
// Constructor connection receiving a socket number
ClientGUI(String host, int port) {
super("Chat Client");
defaultPort = port;
defaultHost = host;
// The NorthPanel with:
JPanel northPanel = new JPanel(new GridLayout(3,1));
// the server name and the port number
JPanel serverAndPort = new JPanel(new GridLayout(1,5, 1, 3));
// the two JTextField with default value for server address and port number
tfServer = new JTextField(host);
tfPort = new JTextField("" + port);
tfPort.setHorizontalAlignment(SwingConstants.RIGHT);
serverAndPort.add(new JLabel("Server Address: "));
serverAndPort.add(tfServer);
serverAndPort.add(new JLabel("Port Number: "));
serverAndPort.add(tfPort);
serverAndPort.add(new JLabel(""));
// adds the Server an port field to the GUI
northPanel.add(serverAndPort);
// the Label and the TextField
label = new JLabel("Enter your username below", SwingConstants.CENTER);
northPanel.add(label);
tf = new JTextField("Scooby Doo");
tf.setBackground(Color.WHITE);
northPanel.add(tf);
add(northPanel, BorderLayout.NORTH);
// The CenterPanel which is the chat room
ta = new JTextArea("Welcome to the Chat room\n", 80, 80);
JPanel centerPanel = new JPanel(new GridLayout(1,1));
centerPanel.add(new JScrollPane(ta));
ta.setEditable(false);
add(centerPanel, BorderLayout.CENTER);
// the 3 buttons
login = new JButton("Login");
login.addActionListener(this);
logout = new JButton("Logout");
logout.addActionListener(this);
logout.setEnabled(false); // you have to login before being able to logout
whoIsIn = new JButton("Who is in");
whoIsIn.addActionListener(this);
whoIsIn.setEnabled(false); // you have to login before being able to Who is in
JPanel southPanel = new JPanel();
southPanel.add(login);
southPanel.add(logout);
southPanel.add(whoIsIn);
add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
tf.requestFocus();
}
// called by the Client to append text in the TextArea
void append(String str) {
ta.append(str);
ta.setCaretPosition(ta.getText().length() - 1);
}
// called by the GUI is the connection failed
// we reset our buttons, label, textfield
void connectionFailed() {
login.setEnabled(true);
logout.setEnabled(false);
whoIsIn.setEnabled(false);
label.setText("Enter your username below");
tf.setText("Anonymous");
// reset port number and host name as a construction time
tfPort.setText("" + defaultPort);
tfServer.setText(defaultHost);
// let the user change them
tfServer.setEditable(false);
tfPort.setEditable(false);
// don't react to a <CR> after the username
tf.removeActionListener(this);
connected = false;
}
/*
* Button or JTextField clicked
*/
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
// if it is the Logout button
if(o == logout) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
return;
}
// if it the who is in button
if(o == whoIsIn) {
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
return;
}
// ok it is coming from the JTextField
if(connected) {
// just have to send the message
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText()));
tf.setText("");
return;
}
if(o == login) {
// ok it is a connection request
String username = tf.getText().trim();
// empty username ignore it
if(username.length() == 0)
return;
// empty serverAddress ignore it
String server = tfServer.getText().trim();
if(server.length() == 0)
return;
// empty or invalid port numer, ignore it
String portNumber = tfPort.getText().trim();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
return; // nothing I can do if port number is not valid
}
// try creating a new Client with GUI
client = new Client(server, port, username, this);
// test if we can start the Client
if(!client.start())
return;
tf.setText("");
label.setText("Enter your message below");
connected = true;
// disable login button
login.setEnabled(false);
// enable the 2 buttons
logout.setEnabled(true);
whoIsIn.setEnabled(true);
// disable the Server and Port JTextField
tfServer.setEditable(false);
tfPort.setEditable(false);
// Action listener for when the user enter a message
tf.addActionListener(this);
}
}
// to start the whole thing the server
public static void main(String[] args) {
new ClientGUI("124.178.99.83", 25565);
}
}

you have to pass the object by reference through constructor. You can either pass the entire JFrame and making your tf public -
public static void main(String[] args){
ClientGUI x = new ClientGUI("0.0.0.0", 1234);
OtherClass y = new OtherClass(x);
}
public class otherClass {
private ClientGUI x;
public otherClass(ClientGUI x){
this.x = x;
}
public void print(){
System.out.println(x.tf.getText());
}
}
or you can just pass the tf value when you create the other class

Related

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:
public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton;
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}
This is the JFrame I wrote for the sign-up button:
public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```
I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.
Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.
Try this site. It gives a good rundown with example images
First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:
MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

JFrame actionlistener is activating before an identical/linked JPanel actionlistener

I'm new to programming and am trying my hand at swing.
I have a JFrame that serves as as the default menu, and I have a JPanel that appears in it to handle logins. After a successful login the JPanel is supposed to send the login information to JFrame so it knows who is currently logged in.
The problem is that the JButton, when clicked, is activating the send portion(whose code is the JFrame) before the JPanel has the chance to check the credentials. They are both using the same actionlistener so I don't know how to control the order.
public class GUIFrame extends JFrame {
private DetailsPanel detailsPanel;
private String curUsername;
public GUIFrame(String title){
super(title);
detailsPanel = new DetailsPanel();
setLayout(new BorderLayout());
Container c = getContentPane();
c.add(detailsPanel, BorderLayout.EAST);
detailsPanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!(detailsPanel.getCurUsername() == "")){
randomToBeImplementedFunctionThatWillLogIn();
//TODO:
// The check here happens BEFORE the detailsPanel processes everything
// so the first time they create an account it won't log them in
// and every subsequent time the PREVIOUS login creds will be used.
}
}
});
public class DetailsPanel extends JPanel {
private HashMap<String, String> logInMap = new HashMap<String, String>();
private String curUsername = "";//the current logged in username
public String getCurUsername(){
return curUsername;
}
JTextField nameField;
JTextField passField;
public DetailsPanel(){
nameField = new JTextField(0);
passField = new JTextField(0);
logIn.addActionListener( (e) -> {//login attempted
if (logInMap.containsKey(nameField.getText())){
if (passField.getText().equals(logInMap.get(nameField.getText()))){
//logged in
curUsername = nameField.getText();
}
else{
//wrong password, logged out
curUsername = "";
}
}
else {
logInMap.put(nameField.getText(), passField.getText());
curUsername = nameField.getText();
//create new account
}
} );
GridBagConstraints gCons = new GridBagConstraints();
gCons.gridy = 0;
gCons.gridx = 0;
add(nameField, gCons);
gCons.gridy = 1;
add(passField, gCons);
}
public void addActionListener(ActionListener al)
{
logIn.addActionListener(al);
}
}
on a successful login, DetailsPanel is supposed to send information to GUIFrame, and then GUIFrame logs in.
Instead, when actionlistener occurs, the GUIFrame attemps to login before DetailsPanel gets to check the credentials and send it to GUIFrame.
Is there a way to get the DetailsPanel.addActionListener() to come AFTER the logIn.addActionListener()?
The order of events is generally not guaranteed. Observationally, they tend to be trigged in FILO (first in, last out) order.
A better solution would be to decouple the process, so any interested parties are not reliant on the button action, but instead on the component telling them when the validation has occurred.
A "simple" solution is to use the existing API functionality
public class DetailsPanel extends JPanel {
private HashMap<String, String> logInMap = new HashMap<String, String>();
private String curUsername = "";//the current logged in username
public String getCurUsername() {
return curUsername;
}
JTextField nameField;
JTextField passField;
JButton logIn;
public DetailsPanel() {
nameField = new JTextField(0);
passField = new JTextField(0);
logIn.addActionListener((e) -> {//login attempted
if (logInMap.containsKey(nameField.getText())) {
if (passField.getText().equals(logInMap.get(nameField.getText()))) {
//logged in
curUsername = nameField.getText();
fireActionPerformed();
} else {
//wrong password, logged out
curUsername = "";
}
} else {
logInMap.put(nameField.getText(), passField.getText());
curUsername = nameField.getText();
//create new account
}
});
GridBagConstraints gCons = new GridBagConstraints();
gCons.gridy = 0;
gCons.gridx = 0;
add(nameField, gCons);
gCons.gridy = 1;
add(passField, gCons);
}
public void addActionListener(ActionListener al) {
listenerList.add(ActionListener.class, al);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners.length == 0) {
return;
}
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "validated");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
So, basically, or this does, is stores the "registered" ActionListeners in the available listenerList. This is API provided by Swing available to all Swing components.
When the button is clicked and the identity verified, all registered parties are notified, via the fireActionPerformed method.
A more complete solution would probably involve your own event listener interface which could include validationSuccess and validationUnsuccessful and could pass back the user credentials as part of the event object

Authenticator getPasswordAuthentication not called [closed]

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 8 years ago.
Improve this question
I am new to Network Programming.
Here is my Code:
public class ComputerNetworks extends Authenticator {
private JDialog passwordDialog;
private JLabel mainLabel= new JLabel("Please enter username and password: ");
private JLabel userLabel = new JLabel("Username: ");
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField usernameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public ComputerNetworks( ) {
this("", new JFrame());
}
public ComputerNetworks(String username) {
this(username, new JFrame());
}
public ComputerNetworks(JFrame parent) {
this("", parent);
}
public ComputerNetworks(String username, JFrame parent) {
this.passwordDialog = new JDialog(parent, true);
Container pane = passwordDialog.getContentPane( );
pane.setLayout(new GridLayout(4, 1));
pane.add(mainLabel);
JPanel p2 = new JPanel( );
p2.add(userLabel);
p2.add(usernameField);
usernameField.setText(username);
pane.add(p2);
JPanel p3 = new JPanel( );
p3.add(passwordLabel);
p3.add(passwordField);
pane.add(p3);
JPanel p4 = new JPanel( );
p4.add(okButton);
p4.add(cancelButton);
pane.add(p4);
ActionListener al = new OKResponse( );
okButton.addActionListener(al);
usernameField.addActionListener(al);
passwordField.addActionListener(al);
cancelButton.addActionListener(new CancelResponse( ));
passwordDialog.pack( );
passwordDialog.setVisible(true);
}
private void show( ) {
String prompt = this.getRequestingPrompt( );
if (prompt == null) {
String site = this.getRequestingSite().getHostName( );
String protocol = this.getRequestingProtocol( );
int port = this.getRequestingPort();
if (site != null & protocol != null) {
prompt = protocol + "://" + site;
if (port > 0)
prompt += ":" + port;
} else {
prompt = "";
}
}
mainLabel.setText("Please enter username and password for "
+ prompt + ": ");
passwordDialog.pack();
passwordDialog.setVisible(true);
}
PasswordAuthentication response = null;
class OKResponse implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK clicked");
passwordDialog.setVisible(false);
// The password is returned as an array of
// chars for security reasons.
char[] password = passwordField.getPassword( );
String username = usernameField.getText( );
// Erase the password in case this is used again.
passwordField.setText("");
response = new PasswordAuthentication(username, password);
}
}
class CancelResponse implements ActionListener {
public void actionPerformed(ActionEvent e) {
passwordDialog.hide( );
// Erase the password in case this is used again.
passwordField.setText("");
response = null;
}
}
public PasswordAuthentication getPasswordAuthentication( ) {
this.show();
return this.response;
}
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new ComputerNetworks());
URL u = new URL("http://www.google.co.in");
InputStream in = u.openStream();
}
}
I am running this code from IDE. The problem is getPasswordAuthentication() method of Authenticator is not getting called though I have opened a stream with a URL.
Please help.
Thanks in advance
From the JavaDoc:
getPasswordAuthentication()
protected PasswordAuthentication getPasswordAuthentication()
Called when password authorization is needed. Subclasses should override the default implementation, which returns null.
Returns:
The PasswordAuthentication collected from the user, or null if none is provided.
google.co.in, to the best of my knowledge, does not require password authorization. Therefore, the Authenticator is not used. Try entering a URL that does require authentication, and see if that helps.

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