在运行时添加jbutton

时间:2014-04-04 18:01:54

标签: java swing sockets client-server jbutton

我正在构建一个关于Socket编程的应用程序,其中服务器侦听客户端,如果客户端已连接,我想要

  • 如果在服务器屏幕上连接,则应为每个客户端添加一个按钮

  • 在每个按钮上添加一个监听器。例如,为每个客户端添加发送消息功能

我在服务器中创建了一个侦听客户端连接但我无法在运行时添加jbutton的线程。

请回复。

5 个答案:

答案 0 :(得分:1)

这就是你需要的吗? :

import javax.swing.*;

import java.awt.event.*;

public class NewButtonOnRunTime {
static JPanel panel;

static JFrame frame;

public static void main(String[] args){
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            frame = new JFrame("Add Buttons");

            JButton button = new JButton("Simulate new Client");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    JButton jb = new JButton("A new Client");
                    jb.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            JOptionPane.showMessageDialog(null, "This is an button action");

                        }
                    });
                    panel.add(jb);
                    frame.revalidate();
                }
            });
            panel = new JPanel();
            panel.add(button);
            frame.add(panel);
            frame.setSize(400, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    });
}   

}

答案 1 :(得分:0)

假设你已经有某种isConnected bool,

if(isConnected){

JButton runTimeButton = new JButton();

runTimeButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {

        //do all the things you need to do in here,
        //alternatively, define this inner class somewhere else and pass in
        // an instance of it

        }
    });


frame.add(runTimeButton);


}

答案 2 :(得分:0)

基于java(即TCP)中的ServerSocket通信,如果客户端连接到具有特定端口5555的服务器,则其他客户端将无法同时连接到具有相同端口的服务器,因为该端口已在使用中。因此,如果您希望与客户端同时进行通信,则每个客户端应使用不同的端口。

查看此示例代码,在连接新客户端时,它会在运行时添加JButton: (在连接在一起的单独机器中运行客户端代码和服务器代码)

服务器代码

package com.test.socket;

import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class ServerFrame extends JFrame {

    private Map<Integer, SocketVO> serverSocketMap;
    private int startingPort = 5555;

    public ServerFrame() {
    }

    public ServerFrame(String title) {
        super(title);
        setSize(Toolkit.getDefaultToolkit().getScreenSize());
        setLayout(new FlowLayout());
        initComponents();
        serverSocketMap = new HashMap<Integer, SocketVO>();
        keepStartServerSocket();
        setVisible(true);
    }

    private JTextArea area = null;

    private void initComponents() {

        area = new JTextArea(20, 20);
        add(area);
        // addDynamicButton();
    }

    private void addDynamicButton(final int port) {
        JButton button = new JButton("Client on " + port + " port");
        add(button);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {
                Socket socket = serverSocketMap.get(port).getSocket();
                try {
                    String content = area.getText();
                    socket.getOutputStream().write(content.getBytes());

                    System.out.println("seding text area content to " + port);
                    System.out.println(content);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    class SocketVO {
        private ServerSocket serverSocket;
        private Socket socket;

        public ServerSocket getServerSocket() {
            return serverSocket;
        }

        public void setServerSocket(ServerSocket serverSocket) {
            this.serverSocket = serverSocket;
        }

        public Socket getSocket() {
            return socket;
        }

        public void setSocket(Socket socket) {
            this.socket = socket;
        }

    }

    private void keepStartServerSocket() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    System.out.println("waiting for a client at port "
                            + startingPort);
                    openServerSocket(startingPort);
                    startingPort++;
                }
            }
        }).start();

    }

    private void openServerSocket(final int port) {

        ServerSocket serverSocket = null;

        try {

            serverSocket = new ServerSocket(port);
            final Socket socket = serverSocket.accept();
            SocketVO socketVO = new SocketVO();
            socketVO.setServerSocket(serverSocket);
            socketVO.setSocket(socket);
            serverSocketMap.put(port, socketVO);
            addDynamicButton(port);

            checkForCosing(port, socket);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void checkForCosing(final int port, final Socket socket) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                InputStream inputStream = null;
                try {
                    inputStream = socket.getInputStream();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                byte[] b = new byte[1024];
                int read = 0;
                try {
                    StringBuilder builder = new StringBuilder();
                    while ((read = inputStream.read(b)) != -1) {
                        builder.append(new String(b));
                    }
                    if (builder.toString().equals("close")) {
                        closeServerSocket(port);
                        System.out.println("server port " + port + " closed");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * the method to close corresponding sockets
     * 
     * @param port
     */
    private void closeServerSocket(int port) {

        Socket socket = serverSocketMap.get(port).getSocket();
        ServerSocket serverSocket = serverSocketMap.get(port).getServerSocket();
        try {
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new ServerFrame("Server Socket Frame");
    }

}

客户端代码:

package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    private int startingPort = 5550;


    private void bindToServer() {
        while(true) {
            try {
                Socket socket = new Socket("127.0.0.1", startingPort);
                InputStream inputStream = null;
                try {
                    inputStream = socket.getInputStream();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                byte[] b = new byte[1024];
                int read = 0;
                try {
                    StringBuilder builder = new StringBuilder();
                    while((read = inputStream.read(b)) != -1) {
                        builder.append(new String(b));
                    }
                    System.out.println("message from server : "+builder);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                startingPort++;
            }

            if (startingPort == 5580) {

            }
        }


    }

    public static void main(String[] args) {
        new Client().bindToServer();
    }
}

答案 3 :(得分:0)

根据你上次的评论:

我已经用两个客户端测试了该程序。服务器已成功连接到两个客户端。但是在运行时没有为每个客户端添加按钮。

您可以连接多个客户端,但您也添加了一个按钮,但它在服务器上不可见。

  

validate()上再次致电JFrame将在添加新JButton后解决您的问题。

答案 4 :(得分:-1)

public class Test extends JFrame {

private JButton field[];

public JButton[] getField() {
    return field;
}

public void test(int n) {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(0, 1));
    field = new JButton[n];
    for (int i = 0; i < field.length; i++) {
        field[i] = new JButton("" + i + "");
        field[i].addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("clicked button");
            }
        });
        panel.add(field[i]);
    }
    add(panel);
}

public static void main(String[] args) {
    Test test = new Test();
    test.setSize(300, 300);
    test.setVisible(true);
    test.setLocationRelativeTo(null);
    test.test(5);
}

}