我想爲我的Java客戶端添加一個GUI,但我再次撞牆對着牆。我試圖做的是當我點擊一個JButton(Shift按鈕)時發送一個命令到我的MySQL服務器,但是我得到了一個異常(「未知的命令!」),我創建了與數字0,1-4不同的任何東西已發送。不使用GUI,它使用鍵盤輸入(掃描儀等)。現在我試圖傳遞靜態參數,但似乎無法正確讀取它們。如果有人能幫忙,我會很高興。下面的代碼搖擺動作監聽器不會聽我
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AirlinesClient extends JFrame implements Runnable {
JPanel Shifts;
JButton shButt;
JPanel AirplanesFood;
JButton afButt;
JPanel Pilots;
JButton pButt;
JPanel Schedule;
JButton sButt;
public static String contact;
public AirlinesClient(){
setTitle("Airlines");
setSize(300,290);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void Schedule(){
this.Schedule = new JPanel();
Schedule.setLayout(null);
this.getContentPane().add(Schedule);
}
private void ScheduleButton(JPanel SchedulePanel){
this.sButt = new JButton("Check schedules");
this.sButt.setBounds(75, 10, 150, 50);
SchedulePanel.add(this.sButt);
}
private void Pilots(){
this.Pilots = new JPanel();
Pilots.setLayout(null);
this.getContentPane().add(Pilots);
}
private void PilotsButton(JPanel PilotsPanel){
this.pButt = new JButton ("Check pilots' shifts");
this.pButt.setBounds(75, 70, 150, 50);
PilotsPanel.add(this.pButt);
}
private void AirplanesFood(){
this.AirplanesFood = new JPanel();
AirplanesFood.setLayout(null);
this.getContentPane().add(AirplanesFood);
}
private void AirplanesButton(JPanel afPanel){
this.afButt = new JButton ("Airplanes and Food");
this.afButt.setBounds(75, 130, 150, 50);
afPanel.add(this.afButt);
}
private void Shifts(){
this.Shifts = new JPanel();
Shifts.setLayout(null);
this.getContentPane().add(Shifts);
}
private void ShiftsButton(JPanel ShiftsPanel){
this.shButt = new JButton ("Possible shift changes");
this.shButt.setBounds(75, 190, 150, 50);
shButt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
contact = "1";
}
});
this.shButt.setToolTipText("Check wheter shift changes are possible");
ShiftsPanel.add(this.shButt);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new AirlinesClient());
Socket connection = null;
BufferedReader socketIn = null;
PrintWriter socketOut = null;
int port = 1234;
String host = "localhost";
Scanner keyIn = new Scanner(System.in);
try{
try{
connection = new Socket(host,port);
socketIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
socketOut = new PrintWriter(connection.getOutputStream(),true);
}catch(ConnectException e){
System.out.println("Could not connect to the host!");
return;
}
System.out.println("Successfully connected to the server!");
String command;
command = AirlinesClient.contact;
do{
socketOut.flush();
socketOut.println(command);
String breakline;
while (!(breakline =socketIn.readLine()).equals("$$$")){
System.out.println(breakline);
}
}while((command = keyIn.nextLine())!="0");
System.out.println("Closing connection to server!");
}catch(IOException e){
e.printStackTrace();
} finally{
try{
if(socketIn!=null) socketIn.close();
if(socketOut!=null) socketOut.close();
if(connection!=null) connection.close();
}
catch(IOException e){
System.err.println("Socket could not be closed!");
}
}
}
public void run() {
this.Schedule();
this.ScheduleButton(this.Schedule);
this.setVisible(true);
this.Pilots();
this.PilotsButton(this.Pilots);
this.setVisible(true);
this.AirplanesFood();
this.AirplanesButton(this.AirplanesFood);
this.setVisible(true);
this.Shifts();
this.ShiftsButton(this.Shifts);
this.setVisible(true);
}
}
我會很高興,如果你也能告訴我一個方法來打印,我應該從服務器接收的信息(如字符串)到一個新的文本字段(放置在一個新的JFrame)。 這裏是什麼在服務器端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Scanner;
public class Airlines {
\t public static void main(String[] args) {
\t \t ServerSocket serverSocket = null;
\t \t Socket connection = null;
\t \t int port = 1234;
\t \t try{
\t \t \t serverSocket = new ServerSocket(port);
\t \t \t while ((connection = serverSocket.accept())!=null){
\t \t \t System.out.println("Client connected!");
\t \t \t Thread client = new Thread (new AirlinesThread(connection));
\t \t \t client.start();
\t \t \t }
\t \t }catch (IOException e){
\t \t \t System.out.println("Binding unsuccesful...");
\t \t }
\t }
}
class AirlinesThread implements Runnable{
Socket connection = null;
public AirlinesThread (Socket connection){
\t this.connection = connection;
}
private static Connection connect(String url, String user, String password){
Connection result = null;
try{
result = DriverManager.getConnection(url, user, password);
System.out.println("Database connection successful!");
}
catch(SQLException e){
System.out.println("Could not connect to the database!");
}
return result;
}
\t String url = "jdbc:mysql://localhost:3306/Airlines";
\t String user = "root";
\t String pass = "123456";
\t Connection link = AirlinesThread.connect(url, user, pass);
\t Statement stmt = null;
\t ResultSet resultSet = null;
\t public void run() {
\t \t PrintWriter socketOut = null;
\t \t Scanner socketIn = null;
\t \t try{
\t \t socketOut = new PrintWriter(this.connection.getOutputStream(),true);
\t \t socketIn = new Scanner(new BufferedReader(new InputStreamReader(this.connection.getInputStream())));
\t \t String command;
\t \t socketOut.flush();
\t \t loop:do{
\t \t \t socketOut.flush();
\t \t \t command = socketIn.nextLine();
\t \t \t switch (command){
\t \t \t case "1":
\t \t \t \t try{
\t \t \t \t stmt = link.createStatement();
\t \t \t \t resultSet = stmt.executeQuery("select Flight.id, Flight.Date, Flight.Time, Flight.Total_Flight_Time, Airports.Departure, Airports.Arrivals FROM Flight, Airports WHERE Flight.id = Airports.Flight");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("FlightID\tDate\t\tTime\t\tTotal Time\tDeparture\tArrivals");
\t \t \t \t while (resultSet.next()) {
\t \t \t \t \t socketOut.println(resultSet.getString("Flight.id")+"\t\t"+resultSet.getDate("Flight.Date")+"\t"+resultSet.getString("Flight.Time")+"\t"+resultSet.getString("Flight.Total_Flight_Time")+"\t\t"+resultSet.getString("Airports.Departure")+"\t\t"+resultSet.getString("Airports.Arrivals"));
\t \t \t \t
\t \t \t \t }
\t \t \t \t }
\t \t \t \t catch(SQLException e){
\t \t \t \t \t System.out.println("Something went wrong at 1");
\t \t \t \t }
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("\nSelect from the options below:\n1: Check schedules\n2: Check pilots shifts\n3: Check corresponding airplanes and food offered\n4: Possible pilot shift changes\n0: Exit");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("$$$");
\t \t \t \t break;
\t \t \t case "2":
\t \t \t \t try{
\t \t \t \t stmt = link.createStatement();
\t \t \t \t resultSet = stmt.executeQuery("select Flight.id, Flight.Date, Flight.Time, Pilots.First_Name, Pilots.Last_Name from Flight RIGHT JOIN Pilots ON Flight.id = Pilots.FlightID;");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("FlightID\tDate\t\tTime\t\tFirst Name\tLast Name");
\t \t \t \t while (resultSet.next()) {
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println(resultSet.getString("Flight.id")+"\t\t"+resultSet.getDate("Flight.Date")+"\t"+resultSet.getString("Flight.Time")+"\t"+resultSet.getString("Pilots.First_Name")+"\t\t"+resultSet.getString("Pilots.Last_Name"));
\t \t \t \t }
\t \t \t \t }
\t \t \t \t catch(SQLException e){
\t \t \t \t \t System.out.println("Something went wrong at 2");
\t \t \t \t }
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("\nSelect from the options below:\n1: Check schedules\n2: Check pilots shifts\n3: Check corresponding airplanes and food offered\n4: Possible pilot shift changes\n0: Exit");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("$$$");
\t \t \t \t break;
\t \t \t case "3": \t \t
\t \t \t \t String FlightID;
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Select your Flight ID: ");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t command = socketIn.nextLine();
\t \t \t \t FlightID = command;
\t \t \t \t try{ \t \t \t \t \t
\t \t \t \t stmt = link.createStatement();
\t \t \t \t resultSet = stmt.executeQuery("SELECT Airplanes.Plane_Model, Food.Breakfast, Food.Lunch, Food.Dinner FROM Airplanes JOIN Flight ON Airplanes.FlightID = Flight.id JOIN Food ON Flight.id = Food.FlightID WHERE Flight.id = "+FlightID+";"); \t \t
\t \t \t \t if(!resultSet.isBeforeFirst()){
\t \t \t \t \t socketOut.flush();
\t \t \t \t \t socketOut.println("You've entered wrong FlightID!");
\t \t \t \t }
\t \t \t \t while (resultSet.next()) {
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println(resultSet.getString("Airplanes.Plane_Model")+"\t\t"+resultSet.getString("Food.Breakfast")+"\t\t"+resultSet.getString("Food.Lunch")+"\t\t"+resultSet.getString("Food.Dinner"));
\t \t \t \t
\t \t \t \t }
\t \t \t \t }
\t \t \t \t catch(SQLException e){
\t \t \t \t \t System.out.println("Something went wrong at 3");
\t \t \t \t }
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("\nSelect from the options below:\n1: Check schedules\n2: Check pilots shifts\n3: Check corresponding airplanes and food offered\n4: Possible pilot shift changes\n0: Exit");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("$$$");
\t \t \t \t break;
\t \t \t \t
\t \t \t case "4":
\t \t \t \t String FirstName=null;
\t \t \t \t String LastName=null;
\t \t \t \t Date date1 = new Date();
\t \t \t \t Date date2 = new Date();
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Please enter the First name of the pilot to be replaced: ");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t command = socketIn.nextLine();
\t \t \t \t FirstName = command;
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Please enter the Last name of the pilot to be replaced: ");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t command = socketIn.nextLine();
\t \t \t \t LastName = command;
\t \t \t \t String FirstName1=null;
\t \t \t \t String LastName1=null;
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Please enter the First name of the pilot to take the shift: ");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t command = socketIn.nextLine();
\t \t \t \t FirstName1 = command;
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Please enter the Last name of the pilot to take the shift: ");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t command = socketIn.nextLine();
\t \t \t \t LastName1 = command;
\t \t \t \t int id1 = 0;
\t \t \t \t int id2 = 0;
\t \t \t \t try{ \t \t \t \t \t
\t \t \t \t stmt = link.createStatement();
\t \t \t \t resultSet = stmt.executeQuery("Select Flight.Date, Pilots.First_Name, Pilots.Last_name, Pilots.FlightID FROM Flight, Pilots WHERE Flight.id=Pilots.FlightID and Pilots.First_Name="+"\""+FirstName+"\""+"and Pilots.Last_Name="+"\""+LastName+"\""+";"); \t \t \t \t
\t \t \t \t if(!resultSet.isBeforeFirst()){
\t \t \t \t \t socketOut.flush();
\t \t \t \t \t socketOut.println("You've entered a wrong name!");
\t \t \t \t }
\t \t \t \t while (resultSet.next()) {
\t \t \t \t date1 = resultSet.getDate("Flight.Date");
\t \t \t \t id1 = resultSet.getShort("Pilots.FlightID");
\t \t \t \t
\t \t \t \t }
\t \t \t \t resultSet = stmt.executeQuery("Select Flight.Date, Pilots.First_Name, Pilots.Last_name, Pilots.FlightID FROM Flight, Pilots WHERE Flight.id=Pilots.FlightID and Pilots.First_Name="+"\""+FirstName1+"\""+"and Pilots.Last_Name="+"\""+LastName1+"\""+";"); \t
\t \t \t \t if(!resultSet.isBeforeFirst()){
\t \t \t \t \t socketOut.flush();
\t \t \t \t \t socketOut.println("You've entered another wrong name!");
\t \t \t \t }
\t \t \t \t while (resultSet.next()) {
\t \t \t \t \t
\t \t \t \t \t date2 = resultSet.getDate("Flight.Date");
\t \t \t \t \t id2 = resultSet.getShort("Pilots.FlightID");
\t \t \t \t \t if (date1.equals(date2)){
\t \t \t \t \t \t \t socketOut.flush();
\t \t \t \t \t \t socketOut.println("Both pilots have a flight at the same date or are on the same flight.");
\t \t \t \t \t \t socketOut.println(FirstName+" "+LastName+"is on flight "+id1+", "+FirstName1+" "+LastName1+"is on flight "+id2+".");
\t \t \t \t \t \t }
\t \t \t \t \t \t \t
\t \t \t \t \t \t else {
\t \t \t \t \t \t \t socketOut.flush();
\t \t \t \t \t \t socketOut.println(FirstName+" "+LastName+" can be replaced by "+FirstName1+" "+LastName1+".");
\t \t \t \t \t \t }
\t \t \t \t \t }
\t \t \t \t
\t \t \t \t
\t \t \t \t
\t \t \t \t }
\t \t \t \t catch(SQLException e){
\t \t \t \t \t System.out.println("Something went wrong at 4");
\t \t \t \t }
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("\nSelect from the options below:\n1: Check schedules\n2: Check pilots shifts\n3: Check corresponding airplanes and food offered\n4: Possible pilot shift changes\n0: Exit");
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("$$$");
\t \t \t \t break;
\t \t \t case "0" :
\t \t \t \t socketOut.flush();
\t \t \t \t socketOut.println("Exitting...");
\t \t \t \t break loop;
\t \t \t default:
\t \t \t \t System.out.println("Unknown command!");
\t \t \t \t socketOut.println("Unknown command!");
\t \t \t \t socketOut.println("$$$");
\t \t \t \t break;
\t \t \t }
\t \t }while(command!="0");
\t \t System.out.println("Closing connection to the client!");
\t \t }catch (IOException e){
\t \t \t e.printStackTrace();
\t \t }finally{
\t \t try{
\t \t if (socketIn!=null) socketIn.close();
\t \t if (socketOut!=null) socketOut.close();
\t \t if (connection!=null) connection.close();
\t \t System.out.println("Connection to server closed!");
\t \t }
\t \t catch(IOException e){
\t \t System.err.println("Could not close connection!");
\t \t }
\t }
\t \t try{
\t \t \t if(stmt != null) stmt.close();
\t \t \t if(resultSet != null) resultSet.close();
\t if(link != null) link.close();
\t System.out.println("Database connection closed successfully!");
\t \t }catch(SQLException ex){
\t \t \t System.out.println("Could not close connection to the database!");
\t \t }
}
}
到目前爲止,我設法文本發送到服務器,並從它那裏得到一個控制檯的答案,但我現在的問題是,我不能添加任何東西除了這個「時間表」按鈕。無論我嘗試添加什麼都不可見,或者它取代了按鈕。有任何想法嗎?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class AirlinesClient extends JFrame implements ActionListener {
\t public static BufferedReader socketIn = null;
\t public static PrintWriter socketOut = null;
\t public static Socket connection = null;
\t public static String breakline;
\t public static String command;
\t private static void initGUI() throws UnknownHostException, IOException{
\t \t JFrame mainFrame = new JFrame("Airlines Client");
\t \t JPanel schPanel = new JPanel();
\t \t JButton Schedules = new JButton ("Flight Schedules");
\t \t JTextField schedArea = new JTextField("HI",20);
//mainFrame
\t \t mainFrame.setSize(300, 400);
\t \t mainFrame.setLocationByPlatform(true);
\t mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
\t mainFrame.setVisible(true);
//adding ScheduleButton's panel to the root frame
\t schPanel.setLayout(null);
\t mainFrame.getContentPane().add(schPanel);
//Adding Schedule button
\t Schedules.setBounds(75, 10, 150, 50);
\t Schedules.setVisible(true);
\t schPanel.add(Schedules);
//Adding action on click
\t Schedules.addActionListener(new ActionListener() {
\t \t \t public void actionPerformed(ActionEvent event) {
\t \t socketOut.println("1");
\t \t \t }
\t \t });
\t
\t
\t
\t
\t }
\t
\t
\t
\t
\t public static void main(String[] args) throws UnknownHostException, IOException {
\t \t
\t \t initGUI();
\t \t
\t \t int port = 1234;
\t \t String host = "localhost";
\t \t connection = new Socket(host,port);
\t \t socketIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
\t \t socketOut = new PrintWriter(connection.getOutputStream(),true);
\t \t
\t \t try{ \t
\t \t System.out.println("Successfully connected to the server!");
\t \t do{
\t \t \t
\t \t \t
\t \t \t
\t \t \t while (!(breakline =socketIn.readLine()).equals("$$$")){
\t \t \t \t System.out.println(breakline);
\t \t \t }
\t \t \t
\t \t }while(command!="0");
\t \t System.out.println("Closing connection to server!");
\t }catch(IOException e){
\t \t e.printStackTrace();
\t } finally{
\t try{
\t if(socketIn!=null) socketIn.close();
\t if(socketOut!=null) socketOut.close();
\t if(connection!=null) connection.close();
\t }
\t catch(IOException e){
\t System.err.println("Socket could not be closed!");
\t }
\t }
\t \t
\t }
\t @Override
\t public void actionPerformed(ActionEvent e) {
\t \t // TODO Auto-generated method stub
\t \t
\t }
\t
\t
}
這會失敗:'command = keyIn.nextLine())!=「0」'因爲你不應該用'=='或'!='來比較字符串。改爲使用「equals(...)」或「equalsIgnoreCase(...)」方法。理解'=='檢查兩個*對象引用*是否相同,而不是你感興趣的。另一方面,方法檢查兩個字符串是否具有相同順序的相同字符,這就是這裏很重要。此外,您的代碼並不是Swing應用程序或任何應用程序如何通過套接字進行通信。不要使用GUI更改的靜態字段,而是... –
當事件指示應該發送某些內容時,GUI會在套接字上發送適當的信息,並讓它從背景中的Socket中讀取信息線程,通知GUI的變化。 –
此外,如果您的代碼正在生成異常或錯誤,請向您的原始問題展示它們,並指出引起它們涉及哪條線。此外,你聲明你正在向MySQL服務器發送信息,但我沒有看到上面的代碼。 –