2013-10-09 2 views
0

Я создаю приложение с резьбой, а основной класс также является классом runnable. по какой-то причине моя нить не начнет. любая идея почему? updateThread является виновником ...Почему мой нить не начинается?

вот код:

package avtech.software.bitprice.display; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JTextField; 

import avtech.software.bitprice.dialogs.*; 
import avtech.software.bitprice.listeners.*; 

@SuppressWarnings("serial") 
public class Display extends JFrame implements Runnable { 

    /** 
    * variables 
    */ 
    private static final int WIDTH = 200, HEIGHT = 200; 
    private static double currentPrice = 0.0; 
    private static double pauseLength; 
    private static boolean running = false; 
    private static String greaterLess = ""; 
    /** 
    * objects 
    */ 
    private static Display d; 
    private static Thread updateThread; 
    private static JLabel currentPriceLabel = new JLabel("Current Price: $" + currentPrice); 
    private static JTextField pullDelayArea = new JTextField("Price Pull Delay In Minutes..."); 
    private static JTextField priceValueArea = new JTextField("Price You Are Waiting For..."); 
    private static JButton update = new JButton("UPDATE DATA"); 

    public Display() { 
     running = true; // program is now running 
     updateThread = new Thread(d); // create the local thread 

     /** 
     * create the frame 
     */ 
     setLayout(null); 
     setSize(WIDTH, HEIGHT); 
     setResizable(false); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setTitle("BitPrice"); 

     /** 
     * set bounds of the components 
     */ 
     currentPriceLabel.setBounds(((WIDTH/2) - (currentPriceLabel.toString().length()/5)), 5, WIDTH, 50); 
     pullDelayArea.setBounds(10, 40, WIDTH - 25, 25); 
     priceValueArea.setBounds(10, 70, WIDTH - 25, 25); 
     update.setBounds(10, 100, WIDTH - 25, 25); 

     /** 
     * set up the listeners to the components 
     */ 
     pullDelayArea.addMouseListener(new PullDelayAreaListener(pullDelayArea)); 
     pullDelayArea.addActionListener(new PullDelayAreaListener(pullDelayArea)); 
     priceValueArea.addMouseListener(new PriceValueAreaListener(priceValueArea)); 
     priceValueArea.addActionListener(new PriceValueAreaListener(priceValueArea)); 
     update.addActionListener(new UpdateButtonListener()); 

     /** 
     * add everything 
     */ 
     add(currentPriceLabel); 
     add(pullDelayArea); 
     add(priceValueArea); 
     add(update); 

     setLocationRelativeTo(null); 
     setVisible(true); 
     requestFocus(); 

     /** 
     * start the update process 
     */ 
     System.out.println("hi"); 
     updateThread.start(); 
    } 

    /** 
    * everything that happens when the thread is updated, including updating 
    * the price label, and all that good stuff :) 
    */ 
    public static void update() { 
     /** 
     * make sure that there is data in the boxes taht is valid 
     */ 
     if (pullDelayArea.getText().equals("Price Pull Delay In Minutes...") || pullDelayArea.getText().equals("")) { 
      new MessageDialog(d, "Please enter a valid number into Price Pull Delay."); 
     } 
     if (priceValueArea.getText().equals("Price You Are Waiting For...") || priceValueArea.getText().equals("")) { 
      new MessageDialog(d, "Please enter a valid number into Price Value."); 
     } 

     // set the new price double from the website 

     // update the label 
     currentPriceLabel.setText("Current Price: $" + currentPrice); 
     currentPriceLabel.setBounds(((WIDTH/2) - (currentPriceLabel.toString().length()/5)), 5, WIDTH, 50); 
     currentPriceLabel.repaint(); 

     /** 
     * check to see if the current value is what the client is waiting for 
     */ 
     String priceValueString = priceValueArea.getText(); 
     double priceValue = Double.parseDouble(priceValueString); 

    } 

    /** 
    * this thread is checking the price of the Bitcoin, and will send out the 
    * notification if it reaches a certain price 
    */ 
    public void run() { 
     System.out.println("started"); 
     /** 
     * initial pause, letting the client get all set up 
     */ 
     try { 
      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      new ErrorDialog(this, "Error delaying the pull request. Please restart client."); 
     } 
     System.out.println("started"); 
     while (running) { 
      update(); 

      /** 
      * add a pause to not just destroy internet speeds, pause settable 
      * through the GUI 
      */ 
      try { 
       Thread.sleep((long) (pauseLength * 1000000)); // 1 million cause 
                   // its in 
       // milliseconds 
      } catch (InterruptedException e) { 
       new ErrorDialog(this, "Error delaying the pull request. Please restart client."); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     d = new Display(); 
    } 
} 

Любая помощь будет принята с благодарностью.

PS: мой интернет вот-вот отключится, поэтому ответы могут быть отложены до завтра.

+2

Это ужасное использование статики, и это может укусить вас в хвост. Вы назначаете d для нового объекта Display, а затем используете ту же самую переменную внутри конструктора Display? Это заставляет мою голову вращаться. Вы не должны этого делать, используя объект перед его построением. –

+0

хорошо, я не совсем уверен, что вы имеете в виду .... lol. также, может быть, поэтому моя нить не начинается? причина в том, что это моя проблема ... – PulsePanda

+3

Прежде всего - избавьтесь от ** каждой ** статической переменной, которую вы используете. Все. Затем исправьте свой код так, чтобы вам не нужны статические переменные. –

ответ

1

Короткая версия, что ссылка на d не не установлена ​​до выходов конструктора, так что в вашем Display, вы создаете новый объект потока и передавая статическую ссылку на d, который до сих пор в настоящее время нуля в этой точке , Я бы удалил строку new Thread(d) и строку .start() от конструктора и просто вызвал d.start() из основного метода.

+1

Я вижу проблему ... ладно, спасибо, XD, я бы не подумал об этом .... :) Я соглашусь с этим, когда смогу – PulsePanda

Смежные вопросы