Java cumple aplicación gráfica cronómetro, pero no se ejecuta

Kiana:

Tengo una misión en la que tengo para crear un programa de cronómetro interfaz gráfica de usuario que tiene un inicio, parada, y el botón de reinicio para el temporizador.

Hasta ahora tengo un programa que compila correctamente, pero produce el error abajo cuando voy a ejecutar el programa, así que estoy seguro de cómo corregir esto.

at java.awt.Container.checkNotAWindow(Container.java:492)
at java.awt.Container.addImpl(Container.java:1093)
at java.awt.Container.add(Container.java:419)
at TimerFrame.main(TimerFrame.java:30)

Process completed.

Cualquier ayuda con el funcionamiento de mi programa, o cualquier otra mejora que se podrían hacer para que el programa funcione mejor que sería muy apreciada. Soy nuevo en el aprendizaje de Java por lo que cualquier ayuda se agradece.

He incluido mi código de abajo también.

¡Gracias por adelantado!

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

public class TimerFrame {
   public static void main(String[] args){
      new TimerPanel();
      JFrame frame = new JFrame("Stopwatch GUI");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      TimerPanel panel = new TimerPanel();
      frame.getContentPane().add(panel);
      frame.pack();
      frame.setVisible(true);
   }
}
import java.awt.GridLayout;
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.JPanel;
import javax.swing.Timer;

public class TimerPanel extends JFrame implements ActionListener  {
    private int count;
    private JButton start;
    private JButton stop;
    private JButton reset;
    private JLabel label;
    private Timer timer;
    private double time;
    private double extra = 0;

    public TimerPanel(){
        setLayout(new GridLayout(2, 3));

        label = new JLabel("00.00", JLabel.CENTER);

        add(label);

        // Creating a panel (JPanel) for hte buttons to reside in
        JPanel buttons = new JPanel();

        // initilizing buttons
        start = new JButton("Start");
        stop = new JButton("Stop");
        reset = new JButton("Reset");

        // adds the buttons start, stop, and reset to the panel
        buttons.add(start);
        buttons.add(stop);
        buttons.add(reset);

        // adds the panel to the frame
        add(buttons);

        // adding action listeners to the buttons
        start.addActionListener(this);
        stop.addActionListener(this);
        reset.addActionListener(this);

        // initilize timer
        timer = new Timer(0, this);
        timer.setDelay(1000);

        setBackground(Color.pink);
        setPreferredSize(new Dimension(500, 300));
   }

   public void actionPerformed(ActionEvent event){

        //find the source of the action
        if(event.getSource().equals(timer)){
            // records the current time event from timer
            double currentTime = System.currentTimeMillis(); 

            // finds the elapsed time from time and currentTime
            double elapsed = (double) ( currentTime - time) / 1000;

            //adds the extra to the elapsed time
            elapsed = elapsed + extra;

            //displays time in JLabel label
            label.setText(String.format("%.1f", elapsed));

        } else if (event.getSource().equals(start)){
            // the start button has been clicked
            if(!timer.isRunning()){
                time = System.currentTimeMillis(); 
                timer.start();
            }

        } else if (event.getSource().equals(stop)) {
            // the stop button has been clicked
            if(timer.isRunning()){
                //record current time in currentTime
                double currentTime = System.currentTimeMillis();
                // finds the elapsed time from time and currentTime
                double elapsed = (double) ( currentTime - time ) / 1000;
                // (double) -> casts whatever is produced to be a double
                //adds the extra to the elapsed time
                elapsed = elapsed + extra;
                //stop the timer
                timer.stop();
            }
        } else{
            // the reset button has been clicked
            // stops the timer before resetting it
            if(timer.isRunning()){
                timer.stop();
            }
            // resets the timer
            time = System.currentTimeMillis();
            extra = 0;
            label.setText("00.00");
        }
   }
}

camickr:
public class TimerPanel extends JFrame implements ActionListener  {

Así, se llama a la clase TimerPanelsin embargo, su amplía un JFrame.

Si la clase es un "panel", entonces debe extender JPanel.

  TimerPanel panel = new TimerPanel();
  frame.getContentPane().add(panel);

Se obtiene el error porque no se puede añadir un JFrame a un JFrame.

Cualquier ayuda con el funcionamiento de mi programa, o cualquier otra mejora

¿Por qué estás tratando de escribir toda la clase antes de hacer la prueba? El ensayo será hecho paso a paso.

Así se inicia mediante la creación de un marco y prueba de eso.

A continuación, agregar algunos componentes en el bastidor y prueba si el diseño es correcto.

Luego se agrega ActionListeners a los botones (uno a la vez) y prueba de ellos.

De esta forma cuando usted tiene problemas ya sabes lo que acaba de cambiar.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=284373&siteId=1
Recomendado
Clasificación