2013-09-23 3 views
0

Я написал программу, как «MadProgrammer спросил меня» Но я получаю ошибки Вот код:Неожиданные ошибки таймера Java

import java.util.Timer; 
import java.util.TimerTask; 
import java.awt.Toolkit; 
import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
//import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 


/** 
* 
* @author Windows 8 Java 
*/ 
public class NewJFrame extends javax.swing.JFrame { 

Toolkit toolkit; 
Timer timer; 


public NewJFrame() { 


    EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
      } 

      JFrame frame = new JFrame("Testing"); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.setLayout(new BorderLayout()); 
      frame.add(new TestPane()); 
      frame.pack(); 
      frame.setLocationRelativeTo(null); 
      frame.setVisible(true); 
     } 
    }); 

    /*toolkit = Toolkit.getDefaultToolkit(); 
    timer = new Timer(); 
    timer.schedule(new RemindTask(), 
       0,  //initial delay 
       1*1000); //subsequent rate*/ 
} 

/*class RemindTask extends TimerTask { 
int numWarningBeeps = 3; 

    public void run() { 
    if (numWarningBeeps > 0) { 
     toolkit.beep(); 
    System.out.format("Beep!%n"); 
    numWarningBeeps--; 
    } else { 
     toolkit.beep(); 
      System.out.format("Time's up!%n"); 
     //timer.cancel(); //Not necessary because we call System.exit 
     System.exit(0); //Stops the AWT thread (and everything else) 
    } 
    } 
} 
*/ 

public class TestPane extends JPanel { 

    private JTextField field; 
    private JButton button; 
    private int tick; 
    private Timer timer; 

    public TestPane() { 

     field = new JTextField(10); 
     field.setEditable(false); 
     button = new JButton("Start"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       button.setEnabled(false); 
       tick = 0; 
       timer.start(); 
      } 
     }); 

     timer = new Timer(1000, new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       field.setText(Integer.toString(++tick)); 
       if (tick > 4) { 
        timer.stop(); 
        button.setEnabled(true); 
       } 
      } 
     }); 
     timer.setInitialDelay(0); 

     setLayout(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridwidth = GridBagConstraints.REMAINDER; 
     add(field, gbc); 
     add(button, gbc); 

    } 
} 




/** 
* Creates new form NewJFrame 
*/ 


/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 400, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 300, Short.MAX_VALUE) 
    ); 

    pack(); 
}// </editor-fold>       

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* 
    * Set the Nimbus look and feel 
    */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* 
    * If Nimbus (introduced in Java SE 6) is not available, stay with the 
    * default look and feel. For details see 
    * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* 
    * Create and display the form 
    */ 


    System.out.format("About to schedule task.%n"); 
    new NewJFrame(); 
System.out.format("Task scheduled.%n"); 



    java.awt.EventQueue.invokeLater(new Runnable() { 

     public void run() { 
      new NewJFrame().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify      
// End of variables declaration     
} 

Я использую NetBeans ошибки в следующих строках:

in " `public class TestPane extends JPanel`" 
at "`timer.start();`" 
at " `timer = new Timer(1000, new ActionListener() {`" 
at "`timer.stop();`" 
and at "`timer.setInitialDelay(0);`" 

Пожалуйста, помогите заранее спасибо Дакш

+1

Всегда включайте полные сообщения об ошибках в ваших сообщениях. Вы можете использовать кнопку редактирования. Кроме того, попробуйте удалить ненужный контент, например, многие строки прокомментированного кода. – jlordo

+0

Вам нужно импортировать 'javax.swing.Timer', а не' java.util.Timer'. Вы ошиблись. – kiheru

ответ

3

У вас есть проблемы с вашим импорта:

new Timer(1000, new ActionListener() 

этот конструктор доступен только для javax.swing.Timer.

Но вы actualy импортировать java.util.Timer

import java.util.Timer; 
Смежные вопросы