1
public class Temp_sim implements Runnable {

private double temperature = 21.0;
private double set_temp = 21.0;
private long sleeptime = 100;
@Override
public void run() {

    while(true){

        if(temperature <= set_temp)
        {
            temperature = temperature +0.1;

        }
        else if(temperature > set_temp)
        {   
            new Runnable(){

                @Override
                public void run() {

                    for(double i = 0.0; i < 2.0;i = i+0.05)
                    {
                        temperature = temperature -0.05;
                    //  System.out.println("Temperature is: \t"+temperature);
                        try {
                            Thread.sleep(sleeptime);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                } 

            }.run();
        }
    //  System.out.println("Temperature is: \t"+temperature);

        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }



}

public double getTemperature() {
    return temperature;
}

public void setTemperature(double current_temp) {
    this.set_temp = current_temp +1;
}
public double getSetTemp(){
    return set_temp;
}
}

in this class, I have a thread simulating a temperature as a double, I then use start and use the thread in another class:

@SuppressWarnings("serial")
public class Temperature_GUI extends JFrame {

private JPanel contentPane;
private JTextField textField;
private TimeSeries series;
private Timer timer = new Timer(250, new tempListener());
Temp_sim temp = new Temp_sim();
Thread thread = new Thread(temp);
private JTextField textField_1;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Temperature_GUI frame = new Temperature_GUI();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
@SuppressWarnings("deprecation")
public Temperature_GUI() {

    thread.start();

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1150, 600);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    JPanel Button_Panel = new JPanel();
    contentPane.add(Button_Panel, BorderLayout.EAST);
    Button_Panel.setLayout(new BorderLayout(0, 0));

    JPanel panel = new JPanel();
    Button_Panel.add(panel, BorderLayout.NORTH);
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

    JPanel panel_1 = new JPanel();
    panel.add(panel_1);

    JButton btnUp = new JButton("Up");
    panel_1.add(btnUp);
    btnUp.addActionListener(new BtnUpActionListener());
    btnUp.setPreferredSize(new Dimension(150, 105));

    textField = new JTextField();
    Font font = new Font("Tahoma",Font.PLAIN,30);
    textField.setText(String.valueOf(temp.getSetTemp())+" \u2103");
    textField.setEditable(false);
    textField.setPreferredSize(new Dimension(95,95));
    textField.setFont(font);
    textField.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    panel.add(textField);
    textField.setColumns(10);

    JPanel panel_2 = new JPanel();
    panel.add(panel_2);

    JButton btnDown = new JButton("Down");
    panel_2.add(btnDown);
    btnDown.addActionListener(new BtnDownActionListener());
    btnDown.setPreferredSize(new Dimension(150, 105));

    JLabel lblCurrentTemperature = new JLabel("current temperature:");
    panel.add(lblCurrentTemperature);

    this.textField_1 = new JTextField();
    panel.add(this.textField_1);
    this.textField_1.setColumns(10);
    final Timer updater = new Timer(1000, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             DecimalFormat df = new DecimalFormat("##.00");
            String getTemp = df.format(temp.getTemperature());
             textField_1.setText(getTemp+" \u2103");
        }
    });
    this.textField_1.setEditable(false);

    JPanel panel_3 = new JPanel();
    Button_Panel.add(panel_3, BorderLayout.SOUTH);

    JButton btnReturn = new JButton("Return");
    btnReturn.addActionListener(new BtnReturnActionListener());
    btnReturn.setPreferredSize(new Dimension(150, 105));
    panel_3.add(btnReturn);
    updater.start();
    JPanel center = new JPanel();
    contentPane.add(center, BorderLayout.CENTER);


    this.series = new TimeSeries("Temperature", Millisecond.class);
    final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
    final JFreeChart chart = createChart(dataset);
    timer.setInitialDelay(1000);
    chart.setBackgroundPaint(Color.LIGHT_GRAY);

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(800, 500));
    center.add(chartPanel);
        timer.start();
}

private JFreeChart createChart(final XYDataset dataset) {
    final JFreeChart result = ChartFactory.createTimeSeriesChart(
        "Temperature Component",
        "Time",
        "Temperature"+" ("+"\u2103"+")",
        dataset,
        true,
        true,
        false
    );

    final XYPlot plot = result.getXYPlot();

    plot.setBackgroundPaint(new Color(0xffffe0));
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.lightGray);


    ValueAxis xaxis = plot.getDomainAxis();
    xaxis.setAutoRange(true);

    //Domain axis would show data of 60 seconds for a time
    xaxis.setFixedAutoRange(60000.0);  // 60 seconds
    xaxis.setVerticalTickLabels(true);

    ValueAxis yaxis = plot.getRangeAxis();
    yaxis.setRange(0.0, 50.0);

    return result;
}
private class tempListener implements ActionListener{
    double lastValue;
     public void actionPerformed(ActionEvent e) {

           this.lastValue = temp.getTemperature();
            final Millisecond now = new Millisecond();
         //   this.series.add(new Millisecond(), this.lastValue);

            series.addOrUpdate(now, lastValue);

        }
}
private class BtnUpActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        double current_temp = Double.valueOf(textField.getText().substring(0, 3)) +1.0;
        temp.setTemperature(current_temp);
        textField.setText(String.valueOf(current_temp)+" \u2103");

    }
}
private class BtnDownActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        double current_temp = Double.valueOf(textField.getText().substring(0, 3)) -1.0;
        temp.setTemperature(current_temp);
        textField.setText(String.valueOf(current_temp)+" \u2103");


    }
}
private class BtnReturnActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        setVisible(false);
    }
}
}

Now, the million dollar question! I have another class (a navigator between GUI for other simulations, if you will)

And i need to read the same data as this started thread, but how do i do that without instantiating a new thread? This has been troubling me for days.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
  • 1
    You could setup some kind of observer pattern that would allow your UI to be notified of changes by the thread. You also need to ensure that any updates you make to the UI are made from within the context of the EDT – MadProgrammer Dec 10 '13 at 19:43
  • 1
    Just a note: `new Runnable() { ... }.run()` doesn't make much sense. The runnable is run synchronously, in the current thread, just as if you had the body of the run() method directly in the enclosing method. – JB Nizet Dec 10 '13 at 19:55
  • You should look into javas Executor Services for simplifying thread interaction. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html – Deadron Dec 10 '13 at 20:15
  • What observer pattern should i use, since my GUI extends JPanel? Those patterns that I've found, uses extend for their Observers, which in my case are the GUI – user3072098 Dec 11 '13 at 07:22

0 Answers0