简体   繁体   English

在java中将控制台界面转换为GUI

[英]Converting a console interface to GUI in java

I am trying to change a console-based interface for a parking system to a GUI based one.我正在尝试将停车系统的基于控制台的界面更改为基于 GUI 的界面。 I am using Swing and I have created a GUI class G that will act as the main menu of the new system.我正在使用 Swing 并创建了一个 GUI 类 G,它将充当新系统的主菜单。 This is what I have so far:这是我到目前为止:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.GraphicsConfiguration;
public class G extends javax.swing.JFrame {
    
    G(){    
        JFrame f=new JFrame("Parking System"); 
        
                    //submit button
        JButton b=new JButton("Confirm"); 
        
        b.setBounds(600,500,100, 40); 
        JButton b1 = new JButton("Back");
        
                    //enter name label
        JLabel label = new JLabel();        
        label.setText("Please enter number of slots for staff:");
        label.setBounds(10, 10, 400, 100);
        JTextField textfield1= new JTextField();
        textfield1.setBounds(280, 50, 50, 20);
        textfield1.setHorizontalAlignment(JTextField.CENTER);
                    //empty label which will show event after button clicked
        JLabel label1 = new JLabel();
        label1.setText("Please enter number of slots for visitor:");
        label1.setBounds(10, 210, 400, 100);
        JTextField textfield2 = new JTextField();
        textfield2.setBounds(280, 250, 50, 20); 
        textfield2.setHorizontalAlignment(JTextField.CENTER);
        
        JLabel label3 = new JLabel();
        
    
        JLabel label2 = new JLabel();
        
        JLabel label4= new JLabel();
        label4.setText("The slots for visitor have been created");
        
        JLabel menu = new JLabel();
        JLabel lab1= new JLabel();
        JLabel lab2 = new JLabel();
        JLabel lab3 = new JLabel();
        JLabel lab4 = new JLabel();
        JLabel lab5 = new JLabel();
        JLabel lab6 = new JLabel();
        
        JLabel lab7 = new JLabel();
        JLabel lab8 = new JLabel();
        
        JButton in = new JButton();
        JTextField textfield3 = new JTextField();
        textfield3.setHorizontalAlignment(JTextField.CENTER);
        
        //textfield to enter name
        
                    //add to frame
        f.add(label);
        f.add(textfield1);
        f.add(label1);
        f.add(label2);
        f.add(label3);
        f.add(textfield2);
        f.add(label2);
        f.add(menu);
        f.add(lab1);
        f.add(lab2);
        f.add(lab3);
        f.add(lab4);
        f.add(lab5);
        f.add(lab6);
        f.add(lab7);
        f.add(lab8);
        f.add(in);
        f.add(textfield3);
        
        f.add(b);   
        f.add(b1);
        f.setSize(800,600);    
        f.setLayout(null);    
        f.setVisible(true);    
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        
                            //action listener
        b.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                   label.setText(textfield1.getText());
                   textfield1.setBounds(280, 50, 0, 0);
                   label1.setText("slots for staff are created successfully");
                   label1.setBounds(30, 10, 400, 100);
                   label3.setText(textfield2.getText());
                   label3.setBounds(10, 30,50,100);
                   textfield2.setBounds(280,50,0,0);
                   label2.setText("slots for visitors are created successfully");
                  label2.setBounds(30, 30, 400,100);
                  
                  menu.setBounds(10, 60, 400,100);
                  menu.setText("Main Menu");
                  
                  lab1.setText("1: List all car slots");
                  lab1.setBounds(10, 80, 400, 100);
                  lab2.setText("2: Park a car");
                  lab2.setBounds(10, 120, 400, 100);
                  lab3.setText("3: Find a car");
                  lab3.setBounds(10, 160, 400, 100);
                  lab4.setText("4: Remove a car");
                  lab4.setBounds(10, 200, 400, 100);
                  lab5.setText("5: Add a car");
                  lab5.setBounds(10, 240, 400, 100);
                  lab6.setText("6: Delete a car slot");
                  lab6.setBounds(10, 280, 400, 100);
                  lab7.setText("7: Exit");
                  lab7.setBounds(10, 320, 400, 100);
                  lab8.setText("Please select an option from (1-7)");
                  lab8.setBounds(10, 360,400,100);
                  textfield3.setBounds(240, 402, 30, 20);
                  
                  b1.setBounds(100,500,100,40);
                  
                  
                  
                  
                   
            }          
          });
               
        }         
    
   
        public static void main(String[] args) {    
            new G();  
            
            
            
 }
}

From the initial console-based interface, I have the CarPark class which is responsible for maintaining a list of available parking slots.在最初的基于控制台的界面中,我有 CarPark 类,它负责维护可用停车位的列表。 This is a part of the CarPark class这是 CarPark 类的一部分

import java.util.*;

public class CarPark {
    private Map<String, String> staffParking = new HashMap<String, String>();
    private Map<String, String> visitorParking = new HashMap<String, String>();
    private static int s_slots;
    private static int v_slots;
    private static int nextStaffSlot = 1;
    private static int nextVisitorSlot = 1;
    private List<ParkingSlot> slotInfos = new ArrayList<ParkingSlot>();
    
    CarPark( int v_slot, int s_slot) {
        v_slots = v_slot;
        s_slots = s_slot;
        int number = 1;
        
        for (int i=0; i<v_slots; i++) {
            String slot = "V" + String.format("%03d", number++);
            visitorParking.put(slot, "not occupied");
        }
        number = 1;
        for (int j = 0; j<s_slots; j++) {
            String slot = "S" + String.format("%03d", number++);
            staffParking.put(slot, "not occupied");
        }
    }
    public void getSlots() {
        for (Map.Entry<String, String> id : staffParking.entrySet()) { 
            System.out.print("SlotID is: "+id.getKey() + ", is for staff, "); 
            System.out.println("and is "+id.getValue()); 
        } 
        for (Map.Entry<String, String> id : visitorParking.entrySet()) { 
            System.out.print("SlotID is: "+id.getKey() + ", is for visitor, "); 
            System.out.println("and is "+id.getValue()); 
        } 
    }
    private boolean validRego(String carNum) { //validate car registration
        
        if (!Character.isUpperCase(carNum.charAt(0))) {
        
            return false;
        }
        for(int i=1;i<carNum.length();i++) { //use ascii values to check if valid
            if(!(carNum.charAt(i)>47 && carNum.charAt(i)<58)) {
                return false;
            }
            else if ((carNum.length()>6) || (carNum.length()<6) ){
                return false;}
        }
        
        return true;
    }
    
    
    
    public void parking() { //enter parking info
        System.out.println("Enter S for staff parking or V for visitor parking ");
        Scanner in = new Scanner(System.in);
        char slotType = in.next().charAt(0);
        ParkingSlot slotInfo;
        if(slotType == 'V') { //for visitor 
            if(nextVisitorSlot<=v_slots) {
                System.out.println("Please enter slot number:");
                String slot_num = in.next();
                if(!(visitorParking.containsKey(slot_num))) {
                    System.out.println("Enter valid slot number!"); 
                }
                else {
                
                System.out.println("Please enter car registration number:");
                String c_number = in.next();    
                if(validRego(c_number)) {
                    System.out.println("Enter owner's name: ");
                    String owner = in.next();
                           
                    if(visitorParking.containsKey(slot_num)) {
                        if(visitorParking.get(slot_num) != "occupied") {
                            nextVisitorSlot++;
                            visitorParking.put(slot_num,"occupied");
                            slotInfo = new VisitorParkingSlot(c_number,owner,slot_num);
                            slotInfos.add(slotInfo);
                            System.out.println("Car successfully added!");
                        }
                        else {
                            System.out.println("The slot is already occupied");
                        }
                        
                    }
                    
                    
                }else {
                    System.out.println("Enter valid car registration number.");
                }
            }
        }
            else {
                System.out.println("All Visitor parking slots are occupied.");
            }
        }
        else if(slotType == 'S') { //for staff 
             if(nextStaffSlot<=s_slots) {
                System.out.println("Enter the slot number:");
                String slot_num = in.next();
                if(!(staffParking.containsKey(slot_num))) {
                    System.out.println("Enter valid slot number!"); 
                }
                else {
                System.out.println("Enter the car number:");
                String c_number = in.next();
                if(validRego(c_number)) {
                    System.out.println("Enter owner's name");
                    String owner = in.next();
                    if(staffParking.containsKey(slot_num)) {
                        if(staffParking.get(slot_num)!="occupied") {
                            nextStaffSlot++;
                            staffParking.put(slot_num,"occupied");
                            slotInfo = new StaffParkingSlot(c_number,owner,slot_num);
                            slotInfos.add(slotInfo);
                            System.out.println("Car successfully added!");
                        }else {
                            System.out.println("The slot is already occupied");
                        }
                        
                    }
                    
                }else {
                    System.out.println("Enter valid car registration number.");
                }
                
            }
        }
            else {
                System.out.println("All Staff parking slots are occupied.");
            }
            
        }
        else {
            System.out.println("Parking slots must start with S or V!");
        }
    }
}

My question is how can I link the GUI class G with the CarPark class so that if the user for example enters 1 into textfield3, the method getSlots is called or if the user enters 2, the method parking is called and the code inside the methods is executed and the output inside the methods is displayed in the GUI window when the confirm button is clicked.我的问题是如何将 GUI 类 G 与 CarPark 类链接起来,例如,如果用户在 textfield3 中输入 1,则调用 getSlots 方法,或者如果用户输入 2,则调用方法停车和方法中的代码单击确认按钮时,方法内部的输出将显示在 GUI 窗口中。 I am new to GUI so I have been looking up tutorials so far but I haven't found anything to help me with this issue.我是 GUI 的新手,所以到目前为止我一直在查找教程,但我没有找到任何可以帮助我解决这个问题的东西。 Any help would be appreciated!任何帮助,将不胜感激!

The question is quiet broad.这个问题很广泛。 I'll try to outline a rough roadmap.我将尝试勾勒出一个粗略的路线图。
The first thing to do is to sperate UI from data.首先要做的是从数据中分离出 UI。 To do that add a class that its sole purpose it to hold all the data (and some logic) that is required by the UI.要做到这一点,添加一个类,它的唯一目的是保存 UI 所需的所有数据(和一些逻辑)。
Such class is typically referred to as model class.这样的类通常被称为模型类。 Let's call it CarParkModel .我们称之为CarParkModel
To demonstrate the idea consider a very basic CarPark that only creates a number of parking slots and shows the number of free slots:为了演示这个想法,考虑一个非常基本的CarPark ,它只创建多个停车位并显示空闲位置的数量:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CarPark {

    private final CarParkModel model;

    CarPark() {

        model = new CarParkModel();
         Scanner in = new Scanner(System.in);
         int parkingSlot = 0;
         while(true){
             System.out.println("Please enter valid number of parking slots <1-5>: ");
             parkingSlot = in.nextInt();
             if(parkingSlot>0 && parkingSlot<6) {
                break;
            }
         }
         
        for (int i=0; i<parkingSlot; i++) {
            model.addStaffParking(true);
        }
    }

    public int freeParkings() {
        return model.freeParkings();
    }

    public static void main(String[] args) {
        CarPark cp = new CarPark();
        System.out.println("number of free slots is " + cp.freeParkings());
    }
}

class CarParkModel{

    private final List<String> parking = new ArrayList<>();
    private final static String OCCUPIED = "occupied", FREE = "free";

    void addStaffParking(boolean isFree){
        if(isFree){
            parking.add(FREE);
        }else{
            parking.add(OCCUPIED);
        }
    }

    int freeParkings(){
        int numberOfFreeParkings = 0;
        for(String s : parking){
            if(s.equals(FREE)) {
                numberOfFreeParkings++;
            }
        }
        return numberOfFreeParkings;
    }
}  

Next step would be creating a GUI, using the very same model.下一步是使用完全相同的模型创建 GUI。 This is why we separate the data (model) from the view (UI).这就是我们将数据(模型)与视图(UI)分开的原因。
When you build swing gui, do not set bounds.在构建swing gui 时,不要设置边界。 Use layout managers .使用布局管理器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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