简体   繁体   中英

Swing action listener won't listen to me

I am trying to add a GUI for my java client but I am banging my head against the wall once again. What I am trying to do is send a command to my MySQL server when I click a JButton(the Shifts button) but I get an exception ("Unknown command!") that I created when anything different than the numbers 0, 1-4 is sent. Without using the GUI it was working with keyboard input(scanner, etc.). Now I am trying to pass static arguments but it seems that they can't be read properly. I will be glad if anyone could help. Here's the code

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

    }


}

I would be glad if you could also tell me a way to print the information I should receive from the server(as a string) into a new text field(placed in a new JFrame). Here's what's on the server side:

 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 { public static void main(String[] args) { ServerSocket serverSocket = null; Socket connection = null; int port = 1234; try{ serverSocket = new ServerSocket(port); while ((connection = serverSocket.accept())!=null){ System.out.println("Client connected!"); Thread client = new Thread (new AirlinesThread(connection)); client.start(); } }catch (IOException e){ System.out.println("Binding unsuccesful..."); } } } class AirlinesThread implements Runnable{ Socket connection = null; public AirlinesThread (Socket connection){ 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; } String url = "jdbc:mysql://localhost:3306/Airlines"; String user = "root"; String pass = "123456"; Connection link = AirlinesThread.connect(url, user, pass); Statement stmt = null; ResultSet resultSet = null; public void run() { PrintWriter socketOut = null; Scanner socketIn = null; try{ socketOut = new PrintWriter(this.connection.getOutputStream(),true); socketIn = new Scanner(new BufferedReader(new InputStreamReader(this.connection.getInputStream()))); String command; socketOut.flush(); loop:do{ socketOut.flush(); command = socketIn.nextLine(); switch (command){ case "1": try{ stmt = link.createStatement(); 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"); socketOut.flush(); socketOut.println("FlightID\\tDate\\t\\tTime\\t\\tTotal Time\\tDeparture\\tArrivals"); while (resultSet.next()) { 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")); } } catch(SQLException e){ System.out.println("Something went wrong at 1"); } socketOut.flush(); 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"); socketOut.flush(); socketOut.println("$$$"); break; case "2": try{ stmt = link.createStatement(); 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;"); socketOut.flush(); socketOut.println("FlightID\\tDate\\t\\tTime\\t\\tFirst Name\\tLast Name"); while (resultSet.next()) { socketOut.flush(); 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")); } } catch(SQLException e){ System.out.println("Something went wrong at 2"); } socketOut.flush(); 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"); socketOut.flush(); socketOut.println("$$$"); break; case "3": String FlightID; socketOut.flush(); socketOut.println("Select your Flight ID: "); socketOut.println("$$$"); command = socketIn.nextLine(); FlightID = command; try{ stmt = link.createStatement(); 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+";"); if(!resultSet.isBeforeFirst()){ socketOut.flush(); socketOut.println("You've entered wrong FlightID!"); } while (resultSet.next()) { socketOut.flush(); 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")); } } catch(SQLException e){ System.out.println("Something went wrong at 3"); } socketOut.flush(); 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"); socketOut.flush(); socketOut.println("$$$"); break; case "4": String FirstName=null; String LastName=null; Date date1 = new Date(); Date date2 = new Date(); socketOut.flush(); socketOut.println("Please enter the First name of the pilot to be replaced: "); socketOut.println("$$$"); command = socketIn.nextLine(); FirstName = command; socketOut.flush(); socketOut.println("Please enter the Last name of the pilot to be replaced: "); socketOut.println("$$$"); command = socketIn.nextLine(); LastName = command; String FirstName1=null; String LastName1=null; socketOut.flush(); socketOut.println("Please enter the First name of the pilot to take the shift: "); socketOut.println("$$$"); command = socketIn.nextLine(); FirstName1 = command; socketOut.flush(); socketOut.println("Please enter the Last name of the pilot to take the shift: "); socketOut.println("$$$"); command = socketIn.nextLine(); LastName1 = command; int id1 = 0; int id2 = 0; try{ stmt = link.createStatement(); 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+"\\""+";"); if(!resultSet.isBeforeFirst()){ socketOut.flush(); socketOut.println("You've entered a wrong name!"); } while (resultSet.next()) { date1 = resultSet.getDate("Flight.Date"); id1 = resultSet.getShort("Pilots.FlightID"); } 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+"\\""+";"); if(!resultSet.isBeforeFirst()){ socketOut.flush(); socketOut.println("You've entered another wrong name!"); } while (resultSet.next()) { date2 = resultSet.getDate("Flight.Date"); id2 = resultSet.getShort("Pilots.FlightID"); if (date1.equals(date2)){ socketOut.flush(); socketOut.println("Both pilots have a flight at the same date or are on the same flight."); socketOut.println(FirstName+" "+LastName+"is on flight "+id1+", "+FirstName1+" "+LastName1+"is on flight "+id2+"."); } else { socketOut.flush(); socketOut.println(FirstName+" "+LastName+" can be replaced by "+FirstName1+" "+LastName1+"."); } } } catch(SQLException e){ System.out.println("Something went wrong at 4"); } socketOut.flush(); 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"); socketOut.flush(); socketOut.println("$$$"); break; case "0" : socketOut.flush(); socketOut.println("Exitting..."); break loop; default: System.out.println("Unknown command!"); socketOut.println("Unknown command!"); socketOut.println("$$$"); break; } }while(command!="0"); System.out.println("Closing connection to the client!"); }catch (IOException e){ e.printStackTrace(); }finally{ try{ if (socketIn!=null) socketIn.close(); if (socketOut!=null) socketOut.close(); if (connection!=null) connection.close(); System.out.println("Connection to server closed!"); } catch(IOException e){ System.err.println("Could not close connection!"); } } try{ if(stmt != null) stmt.close(); if(resultSet != null) resultSet.close(); if(link != null) link.close(); System.out.println("Database connection closed successfully!"); }catch(SQLException ex){ System.out.println("Could not close connection to the database!"); } } } 

So far I managed to send text to the Server and get a console answer from it but my problem now is that I can't add anything else than this "Schedule" button. Whatever I try to add is not visible or it replaces the button. Any ideas?

 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 { public static BufferedReader socketIn = null; public static PrintWriter socketOut = null; public static Socket connection = null; public static String breakline; public static String command; private static void initGUI() throws UnknownHostException, IOException{ JFrame mainFrame = new JFrame("Airlines Client"); JPanel schPanel = new JPanel(); JButton Schedules = new JButton ("Flight Schedules"); JTextField schedArea = new JTextField("HI",20); //mainFrame mainFrame.setSize(300, 400); mainFrame.setLocationByPlatform(true); mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); mainFrame.setVisible(true); //adding ScheduleButton's panel to the root frame schPanel.setLayout(null); mainFrame.getContentPane().add(schPanel); //Adding Schedule button Schedules.setBounds(75, 10, 150, 50); Schedules.setVisible(true); schPanel.add(Schedules); //Adding action on click Schedules.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { socketOut.println("1"); } }); } public static void main(String[] args) throws UnknownHostException, IOException { initGUI(); int port = 1234; String host = "localhost"; connection = new Socket(host,port); socketIn = new BufferedReader(new InputStreamReader(connection.getInputStream())); socketOut = new PrintWriter(connection.getOutputStream(),true); try{ System.out.println("Successfully connected to the server!"); do{ while (!(breakline =socketIn.readLine()).equals("$$$")){ System.out.println(breakline); } }while(command!="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!"); } } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } } 

You're likely repeatedly sending out in your socketOut null since you're getting extracting contact from your AirlinesClient only once, at the beginning of the program, when its null, and then are repeatedly sending it over the socket.

Again, I'd change the entire code's structure:

  • Make contact a non-static variable
  • Pass the Socket into the GUI
  • Call println on the Socket only when needed -- here in the button's ActionListener.
  • Read from the Socket in a SwingWorker background thread, and publish the results to the GUI using the SwingWorker's publish/process method pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM