I'm creating a program in Java(GUI) that when you fill out the TextFields and click enter; the name,age,email,nationality and cell number will be saved in a textfile named StoredInfo.txt . The program I created didn't delete the data you entered if you fill out the textfields again.
What I want want to do is to use the Clear Data button I created and it will delete all the data stored in the text file (StoredInfo.txt).
Here's my program:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SignUp extends JFrame implements ActionListener
{
//Variables
private JButton enter,clear;
private JLabel header,name,age,email,nationality,cellno;
private JTextField nameTF,ageTF,emailTF,nationalityTF,cellnoTF;
private Container container;
private PrintWriter pwriter;
//Constructor
public SignUp()
{
setTitle("Form");
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
container = this.getContentPane();
container.setBackground(Color.GRAY);
enter = new JButton("Enter");
clear = new JButton("Clear Data");
header = new JLabel("Form");
name = new JLabel("Name: ");
age = new JLabel("Age: ");
email = new JLabel("Email Address: ");
nationality = new JLabel("Nationality: ");
cellno = new JLabel("Cellphone #: ");
nameTF = new JTextField(20);
ageTF = new JTextField(20);
emailTF = new JTextField(20);
nationalityTF = new JTextField(20);
cellnoTF = new JTextField(20);
nameTF.addActionListener(this);
ageTF.addActionListener(this);
emailTF.addActionListener(this);
nationalityTF.addActionListener(this);
cellnoTF.addActionListener(this);
enter.addActionListener(this);
clear.addActionListener(this);
//Add section
this.add(header);
this.add(name);
this.add(age);
this.add(email);
this.add(nationality);
this.add(cellno);
this.add(header);
this.add(nameTF);
this.add(ageTF);
this.add(emailTF);
this.add(nationalityTF);
this.add(cellnoTF);
this.add(clear);
this.add(enter);
//SetBounds
enter.setBounds(180,270,80,40);
clear.setBounds(270,270,100,40);
header.setBounds(230,30,80,50);
header.setFont(new Font("Arial",Font.BOLD,25));
header.setForeground(Color.WHITE);
name.setBounds(80,90,40,40);
age.setBounds(80,120,40,40);
email.setBounds(80,150,110,40);
nationality.setBounds(80,180,100,40);
cellno.setBounds(80,210,100,40);
nameTF.setBounds(180,95,190,25);
ageTF.setBounds(180,125,190,25);
emailTF.setBounds(180,155,190,25);
nationalityTF.setBounds(180,185,190,25);
cellnoTF.setBounds(180,215,190,25);
name.setForeground(Color.WHITE);
age.setForeground(Color.WHITE);
email.setForeground(Color.WHITE);
nationality.setForeground(Color.WHITE);
cellno.setForeground(Color.WHITE);
//Setting Up Text File
try
{
File data = new File("StoredInfo.txt");
pwriter = new PrintWriter(new FileWriter(data,false));
if(data.exists())
{
}else
{
data.createNewFile();
}
}catch(Exception e)
{
e.printStackTrace();
}
setVisible(true);
}
//Actions
public void actionPerformed(ActionEvent e)
{
Object action = e.getSource();
if(action.equals(enter))
{
pwriter.println("Name: " + nameTF.getText());
pwriter.println("Age: " + ageTF.getText());
pwriter.println("Email: " + emailTF.getText());
pwriter.println("Nationality: " + nationalityTF.getText());
pwriter.println("CellNo #: " + cellnoTF.getText());
pwriter.println("---------------------------");
pwriter.flush();
pwriter.close();
}else if(action.equals(clear))
{
}
}
///Main
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SignUp();
}
});
}
}
Generally speaking new FileWriter(file); will overwrite the file leaving it empty.
In your case,
else if (action.equals(clear)) {
// Need to close this first to avoid resource leak
pw.close();
File data = new File("StoredInfo.txt");
// I believe you will need pw later
pw = new PrintWriter(new FileWriter(data, false));
}
Hope that helped.
Related
Hi I am new to swing and I need some help. I have build a file processing project where I read an input file and some other existing files in the project, do many checks and parsing and produce a csv and an xlsx file. Until now I used for these inputs
JTextField csvpath = new JTextField();
JTextField csvfile = new JTextField();
JTextField xmlpath = new JTextField();
JTextField xmlfile = new JTextField();
JTextField excpath = new JTextField();
JTextField excfile = new JTextField();
Object[] message = {
"Enter the path of the CSV file to be created:", csvpath,
"Enter the CSV file name:", csvfile,
"Now enter the XML path to be read:", xmlpath,
"Also enter the XML file name:", xmlfile,
"Please enter the Excel file path to be created:", excpath,
"Finally enter the Excel file name:", excfile
};
int option = JOptionPane.showConfirmDialog(null, message, "Convert XML File to CSV File", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String csvPath = csvpath.getText();
String csvFileName = csvfile.getText();
String xmlPath = xmlpath.getText();
String xmlFileName = xmlfile.getText();
String excPath = excpath.getText();
String excFileName = excfile.getText();
String FullcsvPath = csvPath + "\\" + csvFileName + ".csv";
String FullxmlPath = xmlPath + "\\" + xmlFileName + ".xml";
String excelPath = excPath + "\\" + excFileName + ".xlsx";
.
.
parsing/creating starts...
Because in the future this project will be used by others I wanted to create file chooser and get the file/folder paths as strings in order to read the input and create etc...
I have created a class and public strings for paths and when I call it the program does not stop like before, continues to run while the Frame is open without getting the paths I want. My new class is:
public static void SelectFiles() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
final JFrame window = new JFrame("Parse for manufacturers - Developed by Aris M");
JPanel topPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel botPanel = new JPanel();
final JButton openFolderChooser = new JButton("Select Folder to save csv - xlsx results");
final JButton openFileChooser = new JButton("Select the File to be parsed");
final JButton closeButton = new JButton("OK");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JFileChooser fc = new JFileChooser();
openFolderChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(openFolderChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
csv = fc.getSelectedFile().getAbsolutePath();
xlsx = csv;
System.out.println(csv);
}
}
});
openFileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(openFileChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
xml = fc.getSelectedFile().getAbsolutePath();
System.out.println(xml);
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
window.add(BorderLayout.NORTH, topPanel);
window.add(BorderLayout.CENTER, midPanel);
window.add(BorderLayout.SOUTH, botPanel);
topPanel.add(openFolderChooser);
midPanel.add(openFileChooser);
botPanel.add(closeButton);
window.setSize(500, 150);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
Swing code runs in separate thread known as the event dispatch thread. Just make your main thread busy while frame is visible. Add following code to the end of SelectFiles() method:
while (window.isVisible()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I have a small GUI project with a text-box and submit button. What I want to do is for user to type into the text-box and submit an input that would move them through the program (ex. 1 to go to next menu). The program did not use to have a GUI and used console to enter input (as seen in the first code) and so I want to move the program away from console.
Right now my main is:
public static void main(String[] args) {
//Initialize menu variable
Menu menu = MainMenu.getInstance();
new Console();
while (true){
//Display current menu
menu.displayMenu();
while (menu.moreInputNeeded()){
menu.displayPrompt();
try {
// Process user input.
menu.parseInput(new BufferedReader(new InputStreamReader(System.in)).readLine());
} catch (IOException e) {
// printStackTrace();
System.out.println(Prompt.INVALID_INPUT);
}
}
menu = menu.getNextMenu();
}
}
and I use a text/submit button as followed:
//Create the Text Box
JTextField textField = new JTextField(20);
//Submit Button
JButton submit = new JButton("Submit");
//Submit Function
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuinput = textField.getText();
textField.setText("");
//
System.out.println(menuinput);
}
});
So is it possible to process user input from the GUI instead of the console?
I was able to figure out my own question. I implemented:
//Variables
JTextField tfIn;
JLabel lblOut;
private final PipedInputStream inPipe = new PipedInputStream();
private final PipedInputStream outPipe = new PipedInputStream();
PrintWriter inWriter;
String input = null;
Scanner inputReader = new Scanner(System.in);
//Variables
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
}
catch(IOException e) {
System.out.println("Error: " + e);
return;
}
tfIn = new JTextField();
tfIn.addActionListener(this);
frame.add(tfIn, BorderLayout.SOUTH);
With Method:
public synchronized void actionPerformed(ActionEvent evt)
{
textArea.setText("");
String text = tfIn.getText();
tfIn.setText("");
inWriter.println(text);
}
There might be some other little aspects I missed but that's the most important parts.
I have 2 forms. In the first form, I create an object suggestion. Then I have to do something with it and submit it to the second form. How can I open a second window after filling out the first form?
This is my first form:
public class FormNum1 extends JFrame {
JButton clearConfermation, conferm;
JLabel dateofDeparture, dateofArrival, cityFrom, cityTo;
JTextField dateofDepartureTextField, dateofArrivalTextField, cityFromTextField, cityToTextField;
static Suggestion suggestion;
Boolean n = false;
JFrame form1 = new JFrame("form1");
ActionListener actionPerformed;
public FormNum1(){
form1.setVisible(true);
form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form1.setSize(1200,250);
//setResizable(false);
form1.setLocationRelativeTo(null);
form1.setLayout(new FlowLayout());
clearConfermation = new JButton("Make clear");
conferm = new JButton("Confirm information ");
dateofDeparture = new JLabel("Date of Departure");
dateofArrival = new JLabel("Date of Arrival");
cityFrom = new JLabel("City From");
cityTo = new JLabel("City to");
dateofDepartureTextField = new JTextField(10);
dateofArrivalTextField = new JTextField(10);
cityFromTextField = new JTextField(10);
cityToTextField = new JTextField(10);
form1.add(clearConfermation);
form1.add(conferm);
form1.add(dateofDeparture);
form1. add(dateofDepartureTextField);
form1.add(dateofArrival);
form1.add(dateofArrivalTextField);
form1.add(cityFrom);
form1.add(cityFromTextField);
form1.add(cityTo);
form1.add(cityToTextField);
actionPerformed = new InformationFromFormOne();
conferm.addActionListener(actionPerformed);
clearConfermation.addActionListener(actionPerformed);
}
class InformationFromFormOne implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == conferm){
String dateOfDeparture = (dateofDepartureTextField.getText());
String dateOfArrival = (dateofArrivalTextField.getText());
String cityFrom = (cityFromTextField.getText());
String cityTo = (cityToTextField.getText());
suggestion = new Suggestion(dateOfDeparture, dateOfArrival, true, cityFrom, cityTo);
setVisible(false);
form1.dispose();
}
if (e.getSource() == clearConfermation){
dateofArrivalTextField.setText(null);
dateofDepartureTextField.setText(null);
cityFromTextField.setText(null);
cityToTextField.setText(null);
}
}
}
}
My second form is
public class FormNum2 extends JFrame{
static JFrame form2 = new JFrame("form2");
public FormNum2() {
form2.setSize(1200,600);
//frame.setResizable(false);
form2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form2.setLocationRelativeTo(null);
form2.setVisible(true);
}
}
Main class
public class Main extends Thread{
public static void main(String[] args) {
FormNum1 form1 = new FormNum1();
FormNum2 form2 = new FormNum2();
}
}
After the first frame processing set the second frame to visible, put FormNum2 .setVisible(true); to show the second form.
If you want to open the second window after the filling of the object in the first then you should call FormNum2 form2 = new FormNum2() after the object is filled. It seems like you would want to add this line after form1.dispose().
My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?
Please note the code below has been altered to the correct working version provided all the helpful contributors below.
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(textArea, BorderLayout.SOUTH);
}
Scanner s = null;
File af = null;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(truea);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
}
Driver class:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class TestMyFileLister {
public static void main(String [] args)
{
MyFileLister thePanel = new MyFileLister();
JFrame firstFrame = new JFrame("My File Lister");
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
firstFrame.setSize(500, 500);
firstFrame.add(thePanel);
}
}
Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.
I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
if(af == null)
{
System.out.println("Error");
}
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).
// These lines below are causing only last file shown.
for(String path: paths)
{
textArea.setText(path);
}
Here is your modified version for MyFileLister class :
public class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(scrollpane, BorderLayout.SOUTH);
}
Scanner s = null;
File af ;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNext())
{
String as = s.next();
textArea.setText(as);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath="";
for(String path: paths)
{
tempPath+=path+"\n";
}
textArea.setText(tempPath);
}
}
}
Output :
Code:
public void actionPerformed(ActionEvent ae) {
try (Scanner s = new Scanner(new File(userInput.getText()))) {
while (s.hasNextLine()) {
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this,
"File not found",
"No File Error",
JOptionPane.ERROR_MESSAGE);
}
}
Notes:
Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
Use setLineWrap method and set it to true
read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)
use append method in order to add text to end of your JTextArea
read here
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
Use JOptionPane to show error message to an user
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,