I am trying to write this
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
onto my scores.txt file.
This is what I want the output in the scores.txt file to look like:
Write save here and then skip line
Write save here and then skip line (repeat again and again)
My Problem
Every time I press the save score button, it runs this code
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
which is good. But whenever I press the save score button again, the original line gets overwritten which I don't want to happen.
What I've Tried
I have tried \r\n and BufferedWriter and it doesn't match what I want the outcome to be.
My Code
HackerGUI.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class HackerGUI extends JFrame
{
//jframe components
private JPanel rootPanel;
private JButton hack;
private JLabel time;
private JButton reset;
private JLabel description;
private JLabel title;
private JLabel gif;
private JTextField textField1;
private JButton saveScoresButton;
private JButton settingsButton;
private JButton placeholder;
//timer stuff
private final Timer timer; //create timer
private final long duration = 10000; //duration of time
private long startTime = -1; //start of the time
private int delay = 300; //delay of when the time starts
//hacker levels
private int count = 0;
public HackerGUI()
{
add(rootPanel); //add intellij windows builder form
setTitle("Hacker UI v8.4"); //set the title of the frame
try {
File myObj = new File("scores.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Scores file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
try {
File myObj = new File("settings.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Settings file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
timer = new Timer(20, new ActionListener() { //timer module
#Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) { //if time reaches 0, stop time so it doesn't go to negative int
startTime = System.currentTimeMillis(); //use system time
}
long now = System.currentTimeMillis(); //use system time
long clockTime = now - startTime;
if (clockTime >= duration) { //whenever clock reaches 0, run command under:
clockTime = duration;
timer.stop(); //stop the timer from going to the negatives
hack.setEnabled(false); //disables hack button as timer went to 0
reset.setEnabled(true); //enable reset button to play again
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS"); //format of time shown
time.setText(df.format(duration - clockTime)); //set time component to destination
}
});
timer.setInitialDelay(delay); //set the delay
hack.addActionListener(new ActionListener() { //play action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
count++; //count in positives and add
hack.setText("Hacker Level: " + count); //change int and label
if (!timer.isRunning()) { //when button pressed, start timer
startTime = -1; //int to when start
timer.start(); //start
}
}
});
reset.addActionListener(new ActionListener() { //reset action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
hack.setEnabled(true); //enable hack button to start a new game
reset.setEnabled(false); //disable reset button as it has been used
//old command line save score
String name = textField1.getText(); //get name string
System.out.println(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds."); //print other info
System.out.println(""); //print spacer
//old command line save score
count = count + -count; //count in positive integers
hack.setText("Hacker Level: " + -count); //reset level score
time.setText("00:10.000"); //reset time label
}
});
saveScoresButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
FileWriter myWriter = new FileWriter("scores.txt");
String name = textField1.getText(); //get name string
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.");
myWriter.close();
System.out.println("Successfully wrote to the score file.");
} catch (IOException b) {
System.out.println("An error occurred.");
b.printStackTrace();
}
}
});
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO: put stuff here
}
});
//please don't delete! as this shows credits and help info
JOptionPane.showMessageDialog(rootPanel,
"Hacker UI v8.4 is created by _._#3324, thank you for downloading! What is Hacker UI v8.4? It is a clicker game! To know more, read the documentation! https://github.com/udu3324/Hacker-UI-v8.4");
System.out.println("Hacker UI v8.4: has successfully loaded.");
System.out.println("=====================================================");
System.out.println("");
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
public void setData(HackerGUI data) {
}
public void getData(HackerGUI data) {
}
public boolean isModified(HackerGUI data) {
return false;
}
}
Main.java
import javax.swing.*;
import java.net.URL;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, javax.swing.UnsupportedLookAndFeelException
{
System.out.println("Hello, World!"); //Hello, World!
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hacker UI v8.4: is loading..."); //print status of loading
URL iconURL = getClass().getResource("/images/Hacker UI.png"); //load icon resource
ImageIcon icon = new ImageIcon(iconURL); //set icon to icon
HackerGUI hackergui = new HackerGUI(); //make a hacker gui
hackergui.setIconImage(icon.getImage()); //get icon resource and set as
hackergui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminate when asked on close
hackergui.setResizable(false); //no resizing
hackergui.pack(); //wrap it into a pack and set jframe size depending on jframe component size
hackergui.setLocationRelativeTo(null); //set location to middle of screen
hackergui.setVisible(true); //set the frame visible
}
});
}
}
If you do not want to overwrite the text each time you need to append. You can do this by initializing your FileEriter as follows:
FileWriter myWriter = new FileWriter("scores.txt", true);
This constructor takes 2 parameters, one is the file you are writing to and the second is a boolean expression that determines will you append to the file or overwrite it.
If you want to know more about it you can check it out here:
https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/
I've created a mini quiz game in java and wanted to convert it to an exe..It has photos and sounds attached to it but they are in their respective folders and with the correct paths. When i click on "Insert a new question" the exe works fine, the same thing happens for the "exit" option. But when i click "Play" no window pops up but i don't get an error either..
I tried placing the photos and sounds in the same folder as the class that uses them but it didn't fix the problem. I also tried inserting ".." at the beginning of the URL paths but it didn't fix it either. I've attached the code for the not showing frame.
ArrayList<Question> questions;
int selectedQuestion = 0;
int remainingLife = 3;
Random random = new Random();
int fillAnswer = 0;
String [] answerArray = new String[4];
Clip clipSuccess;
Clip clipFailure;
Clip clipGameOver;
public static Mixer mixer;
public static Clip clip;
javax.swing.Timer timer = new javax.swing.Timer(1000, new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
timer.stop();
jLabel5.setIcon(null);
playRound();
}
});
public PlayGame() {
initComponents();
questions = new ArrayList<Question>();
populateArrayList();
clipSuccess = setSound("../Sounds/success.wav");
clipFailure = setSound("../Sounds/failure.wav");
clipGameOver = setSound("../Sounds/gameOver.wav");
playRound();
}
public void populateArrayList(){
try{
FileInputStream file = new FileInputStream("Questions.dat");
ObjectInputStream inputFile = new ObjectInputStream(file);
boolean endOfFile = false;
while(!endOfFile){
try{
questions.add((Question) inputFile.readObject());
}
catch(EOFException e){
endOfFile = true;
}
catch(Exception f){
JOptionPane.showMessageDialog(null, f.getMessage());
}
}
inputFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public Clip setSound(String soundPath){
Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
/*for(Mixer.Info info: mixInfos){
System.out.println(info.getName() + "----" + info.getDescription());
}*/
mixer = AudioSystem.getMixer(mixInfos[3]);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try {
clip = (Clip)mixer.getLine(dataInfo);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
try{
URL soundURL = PlayGame.class.getResource(soundPath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundURL);
clip.open(audioStream);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
catch(UnsupportedAudioFileException uofe){
uofe.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
return clip;
}
public void successAnswer(){
JOptionPane.showMessageDialog(null, "Απάντησες σωστά!");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon(PlayGame.class.getResource("../Images/Fireworks-animated.gif")));
clipSuccess.setFramePosition(0);
clipSuccess.start();
timer.start();
}
public void wrongAnswer(){
remainingLife--;
JOptionPane.showMessageDialog(null, "Απάντησες λάθος..");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon (PlayGame.class.getResource("../Images/failure.gif")));
if (remainingLife == 0){
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
JOptionPane.showMessageDialog(null, "Δυστυχώς έχασες..");
clipGameOver.setFramePosition(0);
clipGameOver.start();
do{
try{
Thread.sleep(50);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
}while(clipGameOver.isActive());
System.exit(0);
}
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
}
public void playRound(){
selectedQuestion = random.nextInt(questions.size());
jTextField3.setText(Integer.toString(remainingLife));
jTextArea2.setText(questions.get(selectedQuestion).getQuestionName());
for (int i=0; i<4; i++){
fillAnswer = random.nextInt(questions.size());
answerArray[i] = questions.get(fillAnswer).getQuestionAnswer();
if (i==2){
answerArray[i] = questions.get(selectedQuestion).getQuestionAnswer();
continue;
}
}
Collections.shuffle(Arrays.asList(answerArray));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(answerArray));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int selectedAnswer = jComboBox1.getSelectedIndex();
jLabel5.setIcon(null);
if (questions.get(selectedQuestion).getQuestionAnswer().trim().equals(answerArray[selectedAnswer].trim())){
successAnswer();
}
else{
wrongAnswer();
}
timer.start();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
In the IDE the output is a jframe with a question, a combo box of 4 answers, the player's life points and two buttons (one for locking the answer and one for exiting the program). But in the exe form it doesn't even pop up.
EDIT - This is the error the wrapper program shows:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/netbeans/lib/awtextra/AbsoluteLayout
at quiz.PlayGame.initComponents(PlayGame.java:277)
at quiz.PlayGame.(PlayGame.java:62)
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,
I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours..
So my first step is to make an window image icon and tray icon for the application`s window.
The thing is, this code below is based on extended FrameView instead of JWindow.
My idea is to wrap the extended FrameView up into a Window.
Can someone help me with that?
Thanks much I would appreciate that.
CODE:
public class DesktopApplication1View extends FrameView implements IProgressDialogObserver
{
//============================================================
// Fields
// ===========================================================
private Connection connection = new Connection();
private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance();
private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>();
private Vector<School> schoolList = new Vector<School>();
private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>();
private int cardReaderRefreshHelper = 0;
private Student student = null;
JLabel jLabelBilkaImage = null;
final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png";
final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png";
private JLabel getJLabelBilkaImage() {
if (jLabelBilkaImage == null) {
Icon image = new ImageIcon(PIC);
jLabelBilkaImage = new JLabel(image);
jLabelBilkaImage.setName("jLabelBilkaImage");
}
return jLabelBilkaImage;
}
//============================================================
// Constructors
// ===========================================================
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
initComponents();
refreshConnectionState();
readFilesFromLocalHDD();
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++)
{
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName))
{
if (!busyIconTimer.isRunning())
{
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
}
else if ("done".equals(propertyName))
{
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
}
else if ("message".equals(propertyName))
{
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
}
else if ("progress".equals(propertyName))
{
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
.........
SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted.
There's a tutorial on using the Swing Application Framework, which might provide more help.