Java с кнопками и GUI - PullRequest
       3

Java с кнопками и GUI

0 голосов
/ 06 мая 2018

Я закончил с моим кодом для этого проекта. Однако у меня возникли проблемы с кнопками. По какой-то причине моя скорость и тормоза не работают, когда я нажимаю кнопки. * Текстовое поле «Скорость» должно отображать скорость в 0, когда я нажимаю кнопку ускорения, она должна увеличиваться на 7, когда я нажимаю кнопку тормоза, она должна уменьшаться на 5. Я не уверен, что я делаю неправильно. Вот мои занятия Car.Java

public class Car
{
    private String make;    //holds car make
    private int speed;      //holds car speed
    private int yearModel;  //holds year model

    //Costructor that will accept the year model as
    //an argument
    public Car(String mk, int ym)
    {
        this.yearModel = ym;
        this.make = mk;
        this.speed = 0;
    }

    //getYearModel accesor
    public int getYearModel()
    {
        return yearModel;
    }

    //getSpeed accesor
    public int getSpeed()
    {
        return speed;
    }

    //getMake accessor
    public String getMake()
    {
        return make;
    }

    //method for accelerate, this method is also additng 7(mph/km)
    public void accelerate()
    {
        speed += 7; // accelerate the speed counter by 7
    }

    //Method for brake, this method should subtract 5
    //from the current speed
    public void brake()
    {
        speed = speed - 5;
    }
}

Вот мой другой класс CarView , где я предполагаю, что кнопки не работают

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class CarView extends JFrame 
{
    private JLabel yearModel,make,speed, color;    //labels for; yearModel, make, and speed
    private JTextField yearModelText, makeText, speedText;     //Text field for yearMake, make, 
    private JButton accelerate, brake; //botton for accelerate, brake 

    //Constructor
    public CarView(Car car)
    {
        //setting name/header for window
        super("Car Simulation View Window");
        //Setting frame size of window
        setSize(400, 250);
        //Specifying what will happen when botton clicked
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Setting the window to non-adjustable
        setResizable(false);
        //Adding components to panel
        addComponents(car);
        //Setting frame to visible
        setVisible(true);

    }

    //Adding components
    private void addComponents(Car car) 
    {
        //Create panel to hold UI compoenents
        JPanel panel = new JPanel();
        //Setting title of JPanel as CarUI
        panel.setBorder(BorderFactory.createTitledBorder("CarUI"));
        //Setting the panel layout
        panel.setLayout(new GridBagLayout());

        //Creating the year label
        yearModel = new JLabel("Year");
        //Adding the year label (0by0colum)
        addToPanel(panel, yearModel, 0, 0);
        //Creating the year text
        yearModelText = new JTextField(car.getYearModel() + "");
        //Making yearModelText to only readible
        yearModelText.setEditable(false);
        //Adding the yearText (0by2colum)
        addToPanel(panel, yearModelText, 0, 2);

        //Creating make label
        make = new JLabel("Make");
        //Adding the make label (1by0colum)
        addToPanel(panel, make, 1, 0);
        //Creating the make text
        makeText = new JTextField(car.getMake());
        //Making make text to onely readeble
        makeText.setEditable(false);
        //Adding makeText to panel (1by2colum)
        addToPanel(panel, makeText, 1, 2);

        //Creating the speed label
        speed = new JLabel("Speed");
        //Adding the speed label
        addToPanel(panel, speed, 2, 0);
        speedText = new JTextField(car.getSpeed());
        speedText.setEditable(false);
        addToPanel(panel, speedText, 2, 2);


        //Creating the accelerate button
        accelerate = new JButton("Accelerate");
        //Adding the accelerate button to a 4by0colum
        addToPanel(panel, accelerate, 4, 0);
        //Adding the action listener to the accelerate button
        accelerate.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                //accelerating the car
                car.accelerate();
            }
        });

        //Creating the brake button
        brake = new JButton("Brake");
        //Adding the brake button at 4 row and 2 column
        addToPanel(panel, brake, 4, 2);
        //Adding the action listener to the acceleration button
        brake.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                //Apply brakes to the car
                car.brake();
            }
        });

        // Add panel to the frame
        add(panel);
    }

    //Ading components to panel
    private void addToPanel(JPanel panel, Component comp, int row, int column) 
    {
        //Seting Constrain for layaout
        GridBagConstraints layoutConstraint = new GridBagConstraints();
        layoutConstraint.fill = GridBagConstraints.BOTH;
        layoutConstraint.anchor = GridBagConstraints.NORTH;
        //Setting constrain sizes in the folowing lines
        layoutConstraint.gridwidth = 2;
        layoutConstraint.weightx = 1;
        layoutConstraint.weighty = 0;
        layoutConstraint.ipady = 10;
        layoutConstraint.gridx = column;
        layoutConstraint.gridy = row;
        //Adding the constrains to panel
        panel.add(comp, layoutConstraint);
    }

    public static void main(String[] args)
    {
        //New Car object that will be displayed
        Car c = new Car("Toyota", 1995);
        new CarView(c);
    }
}

Любая помощь будет высоко ценится

Ответы [ 2 ]

0 голосов
/ 06 мая 2018

Поскольку при обновлении вспомогательного поля в обратном вызове вы не обновляете speedText.

Вы хотели бы сделать что-то вроде:

 accelerate.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                //accelerating the car
                car.accelerate();
                speedText.setText(Integer.toString(car.getSpeed()));
            }
        });

        brake.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                //Apply brakes to the car
                car.brake();
                speedText.setText(Integer.toString(car.getSpeed()));
            }
        });
0 голосов
/ 06 мая 2018

На самом деле вам нужно будет взять значение состояния из Car и обновить JTextField, когда оно изменится ...

accelerate.addActionListener(new ActionListener() 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            //accelerating the car
            car.accelerate();
            speedText.setText(Integer.toString(car.getSpeed()));
        }
    });

Теперь сделайте то же самое для взлома

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...