Authenticator getPasswordAuthentication not called [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 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.

Related

JAVA GUI: Can someone help me check why my button doesn't respond to it being clicked?

i'm new to JAVA GUI and I have just started to learn, I started writing this simple authentication box and i am not sure why my "fogotpassword" button doesn't respond in line "else if (event.getSource()==forgotpassword)" in the method thehandler. Nothing happens when i click it. The System.out.println("s") under it doesn't print.
Help would be very appreciated :). Have a good day.
public class miniProject extends JFrame
{
private JTextField UsernameBox;
private JPasswordField passwordField;
private JButton forgotpassword;
private JButton buttonLogin;
public miniProject()
{
super("Login Page");
setLayout(new GridLayout(3, 2,5,10));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
JLabel username = new JLabel(" Username:");
//username.setEditable(false);
add(username);
UsernameBox = new JTextField(10);
add(UsernameBox);
//item3.setEditable(false);
JLabel passowrd = new JLabel(" Password:");
add(passowrd);
passwordField = new JPasswordField(10);
add(passwordField);
buttonLogin = new JButton("Login");
add(buttonLogin);
forgotpassword = new JButton("Forgot My Password");
add(forgotpassword);
thehandler handler = new thehandler();
UsernameBox.addActionListener(handler);
passwordField.addActionListener(handler);
buttonLogin.addActionListener(handler);
forgotpassword.addActionListener(handler);
}
private class thehandler implements ActionListener
{
int i =5;
public void actionPerformed(ActionEvent event)
{
String string = "";
if (event.getSource()== passwordField || event.getSource()== UsernameBox ||event.getSource()==buttonLogin)
{
String password="";
if(passwordField.getPassword().length != 0 && UsernameBox.getText().length()!=0 )
{
for (char a :passwordField.getPassword())
{
password +=a;
}
password = password.trim();
if (password.equals("kyle") && UsernameBox.getText().equals("marcus"))
{
string = String.format("Welcome Back!", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
else
{
string = String.format("Incorrect Password\n "+i+" more attempts remaining until your account is locked", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
i--;
}
}
else if (event.getSource()==forgotpassword)
{
System.out.println("s");
String input = JOptionPane.showInputDialog("Enter your email");
if (input.length()!=0)
{
JOptionPane.showInternalMessageDialog(null, "Check your email to reset password!", "Password Reset",JOptionPane.PLAIN_MESSAGE);
}
}
else if (passwordField.getPassword().length == 0)
{
string = String.format("You didn't enter your password!",event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
else if (UsernameBox.getText().length()==0)
{
string = String.format("You didn't enter your username!",event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
}
}
}
The code seems not to work as intended, because the if in the second line of your actionPerformed Method does not contain a condition for checking, if the forgotpassword Button is the event source. You have to either add this check to the outer if or move the else if (event.getSource()==forgotpassword) outside of this outer if.

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

Action Listener doesn't change set variable to other value

I am writing GUI for a chat, and I have problem I can't seem to find a solution.
When button Send is clicked variable OKpressed should change to true and in function getUserInput it should recognize it changed but it doesn't..
It's acting like it still says false..
I tried printing out in Send that works, so problem is only that functiong getUserInput doesn't recognize variable as changed
Any help is appreciated..Here's the code
I can't attach all other classes so you can start it, but everything is working except the problem mentioned above
public class Chat extends Process {
public static class myFrame extends JFrame{
/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JTextField User=new JTextField(20);
private String ServerName;
private String UserName;
boolean OKPressed = false;
String poruka;
public myFrame() {
setResizable(false);
setTitle("Client");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Chat History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(User);
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
poruka=(String)UserText.getText();
OKPressed = true;
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
static myFrame t=new myFrame();
public Chat(Linker initComm) {
super(initComm);
}
public synchronized void handleMsg(Msg m, int src, String tag){
if (tag.equals("chat")) {
System.out.println("Message from " + src +":");
System.out.println(m.getMessage());
t.ChatBox.append(src + ":" + m.getMessage() + "\n");
}
}
public String getUserInput() throws Exception {
while (t.OKPressed == false){}
String chatMsg=t.poruka;
return chatMsg;
}
public IntLinkedList getDest(BufferedReader din) throws Exception {
System.out.println("Type in destination pids with -1 at end:");
System.out.println("Only one pid for synch order:");
IntLinkedList destIds = new IntLinkedList(); //dest for msg
StringTokenizer st = new StringTokenizer(din.readLine());
// StringTokenizer st = new StringTokenizer(t.poruka);
while (st.hasMoreTokens()) {
int pid = Integer.parseInt(st.nextToken());
if (pid == -1) break;
else destIds.add(pid);
}
return destIds;
}
public static void main(String[] args) throws Exception {
String baseName = "Chat";
int myId = Integer.parseInt(args[0]);
int numProc = Integer.parseInt(args[1]);
Linker comm = null;
comm = new CausalLinker(baseName, myId, numProc);
Chat c = new Chat(comm);
for (int i = 0; i < numProc; i++)
if (i != myId) (new ListenerThread(i, c)).start();
BufferedReader din = new BufferedReader(
new InputStreamReader(System.in));
while (true){
System.out.println(c.getUserInput());
String chatMsg = c.getUserInput();
if (chatMsg.equals("quit")) break;
t.ChatBox.append(myId + ": " + chatMsg +"\n");
IntLinkedList destIds = c.getDest(din);
comm.multicast(destIds, "chat", chatMsg);
}
}
}
As you wrote, I cannot run you code, so it is kind of guess, however I think the problem is in empty infinite loop:
while (t.OKPressed == false){}
if you add anything inside, even:
while(t.OKPressed == false){
System.out.println();
}
It should work. It is connected with problem better described for example here: Threads: Busy Waiting - Empty While-Loop, and in post which duplicate it is.

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

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

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