java监听按键的正确方法

发布于 2024-12-07 20:06:43 字数 14811 浏览 0 评论 0原文

Java 中处理按键的最佳方法是什么?我试图设置我的 KeyListener 代码,但后来我看到在线 KeyBinding 是应该使用的,但在阅读

http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

并且无法在网上找到任何教程我更加困惑。

这是我一直在尝试的:

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);

但无济于事。非常感谢任何帮助,同时我将继续查看其他人的帖子并拉出更多我的头发。

注意:我的按钮代码工作得很好,我希望在另一个 keypresses.java 文件或其他文件中处理我的按键以保持组织有序

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){}
            }
        }
    }

}

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){}
            }
        }
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迎风吟唱 2024-12-14 20:06:43

并且无法在网上找到任何教程,我更加困惑。

该链接是一个教程。除非您提出具体问题,否则我们不知道您不明白什么。

我的按钮代码工作得很好

看起来您希望 Enter 键执行与单击按钮相同的处理。在这种情况下,简单的解决方案是将 ActionListener 添加到文本字段,而不是使用按键绑定。您甚至不应该考虑为此使用 KeyListener。

当然,这意味着您需要重新设计程序,为每个按钮使用不同的 ActionListener。所以你需要“发送”、“在线”、“技能”和“退出”ActionListener。然后,发送按钮和文本字段都可以使用“发送”ActionListener。

编辑:

例如:用户可以点击(VK_V)或者点击技能按钮来显示技能内部框架

您可以为此使用键绑定。您可以按照教程中的说明手动进行绑定。

或者,更简单的解决方案是使用带有菜单项的 JMenu 来调用操作。然后你可以为菜单项设置一个加速器。阅读 Swing 教程中关于如何使用菜单的部分更多信息。

任何进一步的帮助将需要您发布您的 SSCCE,

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,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文