How to hide jLabel based on JOptionpane input - java

Basically, I click a JButton (unipedal) and it pops up with a JOptionPane with a few JTextFields. I want to take the String inputs of these JTextFields and:
Check to make sure the string values are in a HashMap I have of type (posTasks.taskType), which they should be
Then create a new UNIPEDALImpl object with those Strings as parameters
Use the Strings as keys to another HashMap of type (jLabelsHM) to hide the JLabel if the key of this HashMap returns true when used as a key in posTasks.completedTasks.
I am getting several errors and I can't figure out why.
unipedal.addActionListener(new java.awt.event.ActionListener() {
#SuppressWarnings("null")
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String robotName = null;
String firstTask = null;
String secondTask = null;
String thirdTask = null;
String fourthTask = null;
String fifthTask = null;
JPanel inputBox = new JPanel();
inputBox.setLayout(new GridLayout(0, 2, 3, 4));
JTextField name = new JTextField(15);
JTextField task1 = new JTextField(15);
JTextField task2 = new JTextField(15);
JTextField task3 = new JTextField(15);
JTextField task4 = new JTextField(15);
JTextField task5 = new JTextField(15);
inputBox.add(new JLabel("Robot's Name:"));
inputBox.add(name);
inputBox.add(new JLabel("Task 1:"));
inputBox.add(task1);
inputBox.add(new JLabel("Task 2:"));
inputBox.add(task2);
inputBox.add(new JLabel("Task 3:"));
inputBox.add(task3);
inputBox.add(new JLabel("Task 4:"));
inputBox.add(task4);
inputBox.add(new JLabel("Task 5:"));
inputBox.add(task5);
int option = JOptionPane.showConfirmDialog(middle,inputBox,
"Please fill all the fields", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
robotName.equals(name.getText());
firstTask.equals(task1.getText());
secondTask.equals(task2.getText());
thirdTask.equals(task3.getText());
fourthTask.equals(task4.getText());
fifthTask.equals(task5.getText());
if (!posTasks.taskType.containsKey(firstTask)||!posTasks.taskType.containsKey(secondTask)||!posTasks.taskType.containsKey(thirdTask)||!posTasks.taskType.containsKey(fourthTask)||!posTasks.taskType.containsKey(fifthTask)) {
throw new IllegalArgumentException("One or more of the tasks you have requested are invalid. Please choose tasks from the list provided and check your spelling!");
}
try {
UNIPEDALImpl unipedal = new UNIPEDALImpl(firstTask, secondTask, thirdTask, fourthTask,
fifthTask);
LinkedList<String>tasksList = new LinkedList <String>();
tasksList.add(firstTask);
tasksList.add(secondTask);
tasksList.add(thirdTask);
tasksList.add(fourthTask);
tasksList.add(fifthTask);
for (String task : tasksList) {
if (posTasks.completedTasks.get(task) == true) {
throw new IllegalArgumentException(task + "has already been completed. Please choose a different task or use 'refresh' if you want the task to be completed again");
}
unipedal.time += unipedal.taskTimes.get(task);
posTasks.completedTasks.put(task, true);
unipedal.tasksList.remove(task);
unipedal.taskCounter++;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
for (Entry<String, JLabel> entry : jLabelsHM.entrySet()) {
if(posTasks.completedTasks.get(entry.getKey()) == true) {
jLabelsHM.get(entry.getKey()).setVisible(false);
}
}
}
}
});

First of all we don't have UNIPEDALImpl class here, so with a black-box view, I can not tell you if there is an error within that part.
About the problems in your code. first it seems that you want to fill your variable with equals method which is wrong, you need to use = sign.
equals methos is for comparing two objects not assigning variables.
robotName = name.getText();
firstTask = task1.getText();
secondTask = task2.getText();
thirdTask = task3.getText();
fourthTask = task4.getText();
fifthTask = task5.getText();
then you move from there.

Related

two textfield update each other

I try to convert data but without clicking on a button,
When I enter the data in the 1st textfield nothing happens
JTextField textC = new JTextField() ;
JTextField textF = new JTextField() ;
labelC.setText("Celsius");
labelF.setText("Fahrenheit");
ActionListener textFieldCListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = textC.getText();
try {
float valC = new Float(value);
float valF = valC * 1.8f + 32;
textF.setText(Float.toString(valF));
} catch (Exception exp) {
textF.setText("");
textC.setText("");
}
}};
You should add ActionListener to your JTextField object.
textC.addActionListener(textFieldCListener);
See this: What addActionListener does?
Try:
textC.addActionListener(textFieldCListener);

Java RandomAccessFile , Only finds the first entry

When my program reads from the randomaccessfile it will only find the first file or the file with the lowest account number ( this is a banking program )
After that I get the IO exception with a read error
private RandomAccessFile input; // Random Aecess File input Stream
private Record data;
public static JFrame frame = new JFrame();
public CredRead() // Constructor CredRead created
{
// open the file
try {
// declare the output stream object and associate it to file
// file.dat
input = new RandomAccessFile("UnionDB.dat", "rw");
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("File not opened properly\n " + e.toString());
// the program terminates due to error
System.exit(1);
}
data = new Record();
setPreferredSize(new Dimension(650, 400));
frame.setSize(getPreferredSize()); // Frame Size
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(7, 2)); // Grid Layout set
/* GUI Components */
frame.add(new Label("Enter Account Number and click Enter"));
account_num = new TextField();
frame.add(account_num);
account_num.addActionListener(this);
frame.add(new Label("First Name"));
first_name = new TextField(20);
first_name.setEditable(false);
frame.add(first_name);
frame.add(new Label("Last Name"));
last_name = new TextField(20);
last_name.setEditable(false);
frame.add(last_name);
frame.add(new Label("Available Funds"));
balance = new TextField(20);
balance.setEditable(false);
frame.add(balance);
frame.add(new Label("Overdraft Limit"));
overdraft = new TextField(20);
overdraft.setEditable(false);
frame.add(overdraft);
enter = new Button("Enter");
enter.addActionListener(this);
frame.add(enter);
done = new Button("Click to Exit");
done.addActionListener(this);
frame.add(done);
setVisible(true); // GUI components set as visible to the program
}
public void readRecord() {
DecimalFormat twoDigits = new DecimalFormat("0.00");
try {
do {
data.read(input);
} while (data.getAccount() == 0);
input.seek(
(long) ( data.getAccount()-1 ) * Record.size());
data.write( input );
account_num.setText(String.valueOf(data.getAccount()));
first_name.setText(data.getFirstName());
last_name.setText(data.getLastName());
balance.setText(String.valueOf(twoDigits.format(data.getBalance())));
overdraft.setText(String.valueOf(twoDigits.format(data.getOverdraft())));
}// end try
catch (EOFException eof) {
closeFile();
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error during read from file\n " + e.toString());
// the program terminates due to error
// System.exit(1);
}
}
private void closeFile() {
try {
input.close();
// System.exit(1);
} catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error closing file\n " + e.toString());
// System.exit(1);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enter)
readRecord();
else if (e.getSource() == done)
frame.dispose();
else
frame.add(new TextField(" Account Not Found on Database "));
closeFile();
}
public static void main(String args[]) {
new CredRead();
}
}
My guess is that
data.getAccount() != 0
and so your loop only executes once, because you did it in a do ... while();
Try adding some debugging into your code and make sure what data.getAccount() is equal to.

Overwriting pre-defined array

I have an array named columnsArray[] it is pre-defined to contain 6 Strings. When i run my method columns() it should overwrite the columnsArray[] with a new array of Strings that the user selects by checking boxes.
The way i have tried to implement this adds each box checked to an arrayList and then convert the arrayList to array[]. However when the code is run, columnsArray is not overwritten.
Here is my code so far:
public class EditView {
private JFrame frame;
JCheckBox appNo, name, program, date, pName, country, fileLoc, email, uni,
countryUni, degree, classification, funding, supervisor,
rejectedBy, misc;
public ArrayList<String> columnArrLst;
public String[] columnsArray = { "Application Number", "Name", "Program",
"Date", "Project Name", "Country of Uni" };
public EditView() {
}
public void makeFrame() {
frame = new JFrame("Edit View");
frame.setPreferredSize(new Dimension(300, 350));
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 2, 20, 20));
appNo = new JCheckBox("appNo");
name = new JCheckBox("Name");
program = new JCheckBox("Program");
date = new JCheckBox("Date");
pName = new JCheckBox("Project Title");
country = new JCheckBox("Country of Origin");
fileLoc = new JCheckBox("Current File Location");
// countryRef = new JCheckBox("");
email = new JCheckBox("Email address");
uni = new JCheckBox("Last University");
countryUni = new JCheckBox("Country of last Uni");
degree = new JCheckBox("Degree");
classification = new JCheckBox("Degree Classification");
funding = new JCheckBox("funding");
supervisor = new JCheckBox("Supervisor");
rejectedBy = new JCheckBox("Rejected By");
misc = new JCheckBox("Miscelaneous");
contentPane.add(appNo);
contentPane.add(name);
contentPane.add(program);
contentPane.add(date);
contentPane.add(pName);
contentPane.add(country);
contentPane.add(fileLoc);
contentPane.add(email);
contentPane.add(uni);
contentPane.add(countryUni);
contentPane.add(degree);
contentPane.add(classification);
contentPane.add(supervisor);
contentPane.add(rejectedBy);
contentPane.add(misc);
JButton changeView = new JButton("Change View");
changeView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
columns();
frame.dispose();
}
});
contentPane.add(changeView);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public String[] columns() {
columnArrLst = new ArrayList<String>();
if (appNo.isSelected()) {
columnArrLst.add("AppNo");
}
if (name.isSelected()) {
columnArrLst.add("Name");
}
if (date.isSelected()) {
columnArrLst.add("Date");
}
if (fileLoc.isSelected()) {
columnArrLst.add("file Location");
}
if (country.isSelected()) {
columnArrLst.add("Country");
}
if (email.isSelected()) {
columnArrLst.add("Email");
}
if (uni.isSelected()) {
columnArrLst.add("University");
}
if (countryUni.isSelected()) {
columnArrLst.add("Country of Uni");
}
if (degree.isSelected()) {
columnArrLst.add("Degree");
}
if (classification.isSelected()) {
columnArrLst.add("Degree Classification");
}
if (pName.isSelected()) {
columnArrLst.add("ProjectName");
}
if (funding.isSelected()) {
columnArrLst.add("Funding");
}
if (supervisor.isSelected()) {
columnArrLst.add("Supervisor");
}
if (rejectedBy.isSelected()) {
columnArrLst.add("rejected By");
}
if (misc.isSelected()) {
columnArrLst.add("Miscelaneous");
}
columnsArray = new String[columnArrLst.size()];
columnArrLst.toArray(columnsArray);
return columnsArray;
}
}
Any ideas why it isn't overwriting? Thanks for any help.
Try this one
columnsArray = columnArrLst.toArray(new String[columnArrLst.size()]);
Hope it helps.
replace 2nd last line [columnArrLst.toArray(columnsArray);] with following.
columnsArray = columnArrLst.toArray(columnsArray);
There is nothing wrong with your code, array contents are actually changing when you use it as
EditView e = new EditView();
e.makeFrame();
and insert a print loop after
columnArrLst.toArray(columnsArray);
Note that your JFrame is displayed in a different Thread. If you want to check the values, you need to explicitly wait until the button is pressed to see them changed. If you are doing something like:
EditView e = new EditView();
e.makeFrame();
for (String s : e.columnsArray) { System.out.println(s);}
This will print the old values, since the printing thread is actually a different one and prints the values immediately.

Generic Dialog Ok not triggered the second time

i have created a static instance of a generic dialog in my program
static GenericDialog SaveDialog = null;
and below is the code to display the dialog
public boolean DispSaveDialog()
{
//gd.addStringField("Identity : ", "annot");
if(SaveDialog == null)
{
SaveDialog = new GenericDialog("Save");
Panel idnPanel = new Panel();
idnPanel.add(new Label("Identity"));
idnTextComp = new TextField("annot");
csPrefix = idnTextComp.getText();
TextListener tl = new TextListener() {
#Override
public void textValueChanged(TextEvent e) {
// TODO Auto-generated method stub
csPrefix = idnTextComp.getText();
}
};
idnTextComp.addTextListener(tl);
idnPanel.add(idnTextComp);
SaveDialog.addPanel(idnPanel);
final TextComponent textComponent = new TextField();
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String label = e.getActionCommand();
//csPrefix = gd.getNextString();
if (label=="Browse")
{
String csFilename = imp.getTitle();
csTextFileName = FileNameProcess( csFilename );
}
textComponent.setText(csTextFileName);
}
};
Button btBrowse = new Button("Browse");
btBrowse.addActionListener(al);
Panel panel = new Panel();
panel.add(new Label("Folder : "));
//textComponent.setBounds(gd.getBounds());
panel.add(textComponent);
panel.add( btBrowse );
SaveDialog.addPanel(panel);
}
SaveDialog.showDialog();
return true;
}
the issue i am facing is, when i open the dialog the second time, the OK and Cancel events are not triggered.
i have a feeling that the issue is silly, sorry and thanks in advance.
The above code was so that when the generic dialog was displayed the second time the old values would be retained..
i did a workaround for the same where i save the strings entered the first time in static string variables and load them after checking for null values.
this is not the solution, just a workaround so i could close the issue on time. :(

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