cant create a JTextField - java

import org.jsoup.Jsoup;
#SuppressWarnings({ "unused", "serial" })
public class SimpleWebCrawler extends JFrame {
JTextField yourInputField = new JTextField(20);
static JTextArea _resultArea = new JTextArea(200, 200);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
String word2;
public SimpleWebCrawler() throws MalformedURLException {
yourInputField.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
word2 = yourInputField.getText();
}
});
_resultArea.setEditable(false);
try {
URL my_url = new URL("http://" + word2 + "/");
BufferedReader br = new BufferedReader(new InputStreamReader(
my_url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
_resultArea.append(strTemp + newline);
}
} catch (Exception ex) {
ex.printStackTrace();
}
_resultArea.append("\n");
_resultArea.append("\n");
_resultArea.append("\n");
String url = "http://" + word2 + "/";
print("Fetching %s...", url);
try{
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
System.out.println("\n");
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt"));
_resultArea.append("\n");
for (Element link : links) {
print(" %s ", link.attr("abs:href"), trim(link.text(), 35));
bw.write(link.attr("abs:href"));
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e1) {
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
content.add(yourInputField,BorderLayout.SOUTH);
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
private static void print(String msg, Object... args) {
_resultArea.append(String.format(msg, args) +newline);
}
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
//.. Get the content pane, set layout, add to center
public static void main(String[] args) throws IOException {
JFrame win = new SimpleWebCrawler();
win.setVisible(true);
}
}
I am trying to create a JTextField to accept the user input. The input will go to this line of code to process the code.
URL my_url = new URL("http://" + word2 + "/");
String url = "http://" + word2 + "/";
However, the code is run without asking the user for input. The JTextField does not appear and i straight get an error on because i din enter the input.
I am trying to get the JTextField to accept input from the user. However, it does not appear and the code straight proceed with the processing end up with empty my_url and rmpty url variable.
How do i create a JTextField according to my code that i post ? It seems that the Jtextfield i created clashed with my codes.

Java swing does not follow the imperative approach but is event driven. Your constructor method is executed in total and does not wait for your input.
You must not include the business logic (i.e. all this read/write stuff) into this method but into a separate one and invoke it from the action listener your registered with your input field. (see e.g. http://download.oracle.com/javase/tutorial/uiswing/events/index.html)
Note A: If your logic is quite heavy you should spawn a background thread and not do it directly in your action listener (see Swingworker).
Note B: There is lot's of strange code within your class.
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
As mentioned before this will be run immediately and thus your panel content is never shown at all because it will be overwritten by content2.

Related

How to make a String available in other classes

I've managed to make the input into a string which is available within the same class but I want to make it so the input string can be available in different classes. Current class is OpenDetails and I want the string selectedFile to be available in a different class called OpenFileInfo. How would I set it so the result from selectedFile can be stored in either selectedRequirement or make it available in other classes?
I'm new to Java so if someone could help thank you.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class OpenFile
{
String selectedRequirement = "";
public static void main(String a[])
{
JFrame parent = new JFrame();
String selectedFile;
selectedFile = JOptionPane.showInputDialog(parent, "Add a new module");
if(selectedFile.equalsIgnoreCase(selectedFile)){
//Makes the user input case insensitive
}
final JTextArea edit = new JTextArea(60,100);
JButton read = new JButton("Open "+ selectedFile +".txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader(selectedFile + ".txt");
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Save "+ selectedFile + ".txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter(selectedFile + ".txt");
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
System.out.println("Module: " + selectedFile);
JFrame frame = new JFrame("Requirements");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
As you are running from a static context, you need to define selectedRequirement as static:
private static String selectedRequirement = "";
To make selectedRequirement equal to selectedFile, simply say selectedRequirement = selectedFile; towards the end of the main function (maybe where you print it already).
To make selectedRequirement available to other classes, you need to create a "getter function" in the OpenFIle class (outside of the main function) like:
public String getSelectedRequirement(){
return selectedRequirement;
}
As pointed out in the comments, it would be a good idea for you (or anyone who finds this in the future) to look at some tutorials on getters, setters, and general encapsulation.

Download Files From a Website with java

I am very new to Java and I'm currently trying to create a Java application to download files from a website. To enter the website you need a password and username. I use NativeSwing to enter and get the path of the files, but I do not know how to download them.
public class Test {
public JFrame frame;
private static JWebBrowser browser;
private static JPanel configurationButtonPanel;
public Test() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createContent(), BorderLayout.CENTER);
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComponent createContent() {
JPanel contentPane = new JPanel(new BorderLayout());
JPanel configurationPanel = new JPanel(new BorderLayout());
configurationButtonPanel = new JPanel(new FlowLayout(
FlowLayout.CENTER, 0, 0));
JButton beginButton = new JButton("Download");
beginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ArrayList<String> ligas = new ArrayList<String>();
int a=0;
Document doc = Jsoup.parse(browser.getHTMLContent());
Element ele = doc.getElementById("ctl00_MainContent_PnlResultados");
System.setProperty("java.net.useSystemProxies", "true");
try{
Elements img_2 = ele.getElementsByClass("BtnDescarga");
for (Element el : img_2) {
for( Attribute attribute : el.attributes() )
{
if( attribute.getKey().equalsIgnoreCase("onclick") )
{
ligas.add("https://portalcfdi.facturaelectronica.sat.gob.mx/"+attribute.getValue().substring(19,535));
}
}
}
}
catch(NullPointerException nulo){
}
for( int i = 0 ; i < ligas.size() ; i++ ){
System.out.println( ligas.get( i ) );
}
}
});
browser = new JWebBrowser();
browser.navigate("https://portalcfdi.facturaelectronica.sat.gob.mx/");
configurationButtonPanel.add(beginButton);
configurationButtonPanel.setVisible(true);
configurationPanel.add(configurationButtonPanel, BorderLayout.NORTH);
contentPane.add(configurationPanel, BorderLayout.SOUTH);
contentPane.add(browser, BorderLayout.CENTER);
return contentPane;
}
/**
* #param args
*/
public static void main(String[] args) {
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
NativeInterface.runEventPump();
}
}
When it run this part:
for( int i = 0 ; i < ligas.size() ; i++ ) {
System.out.println( ligas.get( i ) );
}
I get the following URL:
https://portalcfdi.facturaelectronica.sat.gob.mx/RecuperaCfdi.aspx?Datos=huswUYX1eXMlGkDiItMUBgaWREHHqhXOWtYxqyUh0oUZnCKLYE/gx6ENJ+0TwW5auWw8d/AiCJyuFSDNVY+5l0vkiELroo/fEmF+x5w+DQDDTfMX9qIINS1NgP9C1bFhirjcVXpZI1ed4ycpLPczkYMEGEKvqWemni8LWcbqC0BuZskOJnCQCaWRh1Kt7AL5GdBVKqkm3T5mvzhtkmE5dn0vcWbCFFO3d3G8hu7rlcc0XM+7+6iR52SZYYaHa/TOhcl2DjuzztADpa9tPxZ9VO6EzMVkYKTfDOqHwZO8m2U9BZ7UhFjqsyoAwsQneqhIqGwN21yEpGEcptsTb9uZ1t0Fc/1Ggd6SuK9NeGdBpiawn6cv6QM1uc4QQHMNpAgG89Rq5tOd4YAoRQHBe/vO8ppq60JwvJgQ4BN76EtZF0UtEWK+k57P01vatuvTHIdMBncbXyU+TrtE5AlhdGKkY2a8HwSxHw3nfoQ+SLBrjyg=
I use the following code to read images from url, i think you can use the same techniques here
try{
URL url = new URL("YOUR_URL_TO_READ");
InputStream is = url.openStream();
OutputStream os = new FileOutputStream("YOUR_FILE_TO_SAVE");
byte[] b = new byte[4096];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}catch(Exception exp){
exp.printStackTrace();
}
The best answer right now is the Apache Http Client. Java has HttpURLConnection built-in, but it is difficult to use, and has some other usage issues that can burn you (e.g. keep-alive and errors). If you absolutely cannot include a third party, use HttpURLConnection, otherwise go with the Apache Library.
There is a new Java standard Http library coming in JDK 9 here, but that's not here yet.
You might have to try code on similar lines..it might work... Two issues maybe there...first is you need to find the proxy name and port set on your machine...if there is a proxy.. Next, possible the site needs authentication,so you would need to set the right username and password.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("Your Proxy", ProxyPort));
String username = "YourUserName";
String password = "Password";
String userPassword = username + ":" + password;
byte[] encodedAuthorization = BASE64EncoderStream.encode(userPassword.getBytes());
HttpURLConnection connection =(HttpURLConnection)new URL("Your URL set here").openConnection(proxy);
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization.toString());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/zip");
//connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream("d:\\PathToFile" + "Chec.zip");

Action Listener doesn't change set variable to other value

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

Why my JTextArea is not displaying properly from the while loop?

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

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