我有一个简单的Java程序。程序连接到服务器并发送数字。我想通过按下按钮来重做发送号码的程序。
按钮代码:
/* button */
JButton b1;
b1 = new JButton("Send");
b1.addActionListener(this);
/* ActionListener */
public void actionPerformed(ActionEvent zdarzenie)
{
Object zrodlo = zdarzenie.getSource();
if (zrodlo == b1){
sendNumber(number) <------- THIS METHOD
}
}
这里我需要创建方法sendNumber
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
private Socket socket;
Client()
{
try {
socket = new Socket("localhost", 2020);
System.out.println("Klient dziala");
}
catch(IOException e) {
System.out.println("Uruchom serwer");
System.exit(1);
}
}
void uruchom() throws Exception
{
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
Scanner czytacz = new Scanner(System.in);
String liczba, odSerwera;
while(true) {
System.out.println("Podaj zgadywaną liczbę: ");
liczba = czytacz.nextLine();
out.println(liczba);
odSerwera = in.readLine();
System.out.println(odSerwera);
if(odSerwera.equals("Zgadłeś")) break;
}
socket.close();
}
public static void main(String args[]) throws Exception
{
Client client = new Client();
client.uruchom();
}
}
我试过了:
void sendNumber(String number)
{
out.println(number);
}
不幸的是,这不起作用。有谁知道怎么做?
答案 0 :(得分:0)
尝试添加侦听器,如下所示:
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
sendNumber(number);
}
});