Pasar al contenido principal

Ejemplo de termometro en Java

Enviado por drw el
TermometroExisten muchas de las veces en que nos proponemos programar un termómetro para darle mas pinta a nuestras aplicaciones en un caso especifico he utilizado la librería gratuita de java jfree lo he utilizado para graficar los niveles de tanques de agua en la empresa en donde trabajo. Este es un ejemplo muy básico de lo que se puede hacer con esta muy útil librería. He intentado explicar lo que me parece un poco difícil de entender pero bueno si tienes alguna dificultad con el código solamente tienes que escribir. Aquí les pongo un ejemplo sencillo de como lo pueden hacer y mostrando algunas de sus funcionalidades .. al ejemplo lo he modificado de su author original Bryan Scott quitandole algunas cosas del código que el programo para hacerlo un poco mas entendible al inicio para mi y ahora para Uds.


El código es el siguiente: /* ====================================== * JFreeChart : a free Java chart library * ====================================== * * Project Info: http://www.jfree.org/jfreechart/index.html * Project Lead: David Gilbert (david.gilbert@object-refinery.com); * * (C) Copyright 2000-2003, by Object Refinery Limited and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * -------------------- * ThermometerDemo1.java * -------------------- * (C) Copyright 2002, 2003, by Australian Antarctic Division and Contributors. * * Original Author: Bryan Scott (for Australian Antarctic Division). * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ThermometerDemo1.java,v 1.2 2003/05/29 15:23:35 mungady Exp $ * * Changes (since 24-Apr-2002) * --------------------------- * 24-Apr-2002 : added standard source header (DG); * 17-Sep-2002 : fixed errors reported by Checkstyle 2.3 (DG); * 07-May-2008 : Modify for taller * */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.JThermometer;
import org.jfree.data.general.DefaultValueDataset;
/** * A demonstration application for the thermometer plot. * Un demostracion para la aplicacion de un termometro * * @author Bryan Scott * @mofify by Darwin Betancourt Castillo */

public class ThermometerDemo1 extends JPanel implements ActionListener {
/** Options for the value label position combo box. */
protected static final String[] OPTIONS = {"Ninguna", "Derecha", "Izquierda","Centro"}; /** Panel 1. */
private JPanel jPanel1 = new JPanel(); /** Borderlayout 3. */
private BorderLayout borderLayout3 = new BorderLayout(); /** Panel 2. */ private JPanel jPanel2 = new JPanel(); /** Decrement button for thermometer ?. */
private JButton btnDown = new JButton(); /** Increment button for thermometer ?. */
private JButton btnUp = new JButton(); /** Grid layout 1. */
private GridLayout gridLayout1 = new GridLayout(); /** Thermometer 2. */
private JThermometer thermo2 = new JThermometer(); /** Borderlayout 1. */
private BorderLayout borderLayout1 = new BorderLayout(); /** Panel 3. */
private JPanel jPanel3 = new JPanel(); /** Grid layout 3. */
private GridLayout gridLayout3 = new GridLayout(); /** Combo box 2 for value label position. */
private JComboBox pickShow2 = new JComboBox(OPTIONS); /** Borderlayout 4. */
private BorderLayout borderLayout4 = new BorderLayout(); /** * Default constructor. */

public ThermometerDemo1() { try { jbInit(); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Controla los eventos de los botones
* @param e ActionEvent */

public void actionPerformed(ActionEvent e){
if(e.getSource() instanceof JButton){
JButton boton = (JButton) e.getSource();
if(boton.getName().matches("btnUp")){ setValue(1); }
if(boton.getName().matches("btnDown")){ setValue(-1); } } } /** * Initialises the class. * * @throws Exception for any exception. */
void jbInit() throws Exception {
thermo2.setValue(0);
thermo2.setOutlinePaint(null);
thermo2.setUnits(0);
thermo2.setForeground(Color.blue);
thermo2.setBackground(Color.white);
// Se establece el rango de 0 a 100 thermo2.setRange(0.0,100.0);
// El numero inicial representa el color (Solo hay tres colores y el color por defecto gris)
// 0 = verde, 1=anaranjado 2=rojo
thermo2.setSubrangeInfo(2, 80.0, 100.0, 22.0, 40.0);
thermo2.setSubrangeInfo(1, 50.0, 80.0, 18.0, 26.0);
thermo2.setSubrangeInfo(0, 0.0, 50.0, 0.0, 100.0);
thermo2.addSubtitle("Nivel del Tanque", new Font("SansSerif", Font.PLAIN, 16));
// Se establece el formato del valor del grafico
//thermo2.setValueFormat(new DecimalFormat("#0.0"));
thermo2.setValueFormat(new DecimalFormat("#0"));
// Layout para el JPanel principal setLayout(gridLayout1);
jPanel1.setLayout(borderLayout3);
btnDown.setText("Bajar");
btnDown.setName("btnDown");
btnDown.addActionListener(this);
btnUp.setText("Subir");
btnUp.setName("btnUp");
btnUp.addActionListener(this);
pickShow2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { setShowValue(); } });
jPanel3.setLayout(gridLayout3); jPanel3.add(pickShow2,null); jPanel1.setBorder(BorderFactory.createEtchedBorder());
// Contenedor de los botones del panel 4
jPanel2.add(btnDown, null); jPanel2.add(btnUp, null);
jPanel1.add(jPanel3, BorderLayout.NORTH);
// Se agrega el thermometro al panel
jPanel1.add(thermo2, BorderLayout.CENTER); // Contenedor del panel 4
jPanel1.add(jPanel2, BorderLayout.SOUTH);
// Se agrega el panel del nivel add(jPanel1, null); }
/** * Starting point for the demo application. * * @param args ignored. */
public static void main(String[] args) {
final ThermometerDemo1 panel = new ThermometerDemo1();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout(5, 5));
frame.setDefaultCloseOperation(3);
frame.setTitle("Ejemplo de Termometro en Java");
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); frame.setVisible(true); }
/** * Sets the value of the thermometer. * * @param value Valor del nivel del termometro */
private void setValue(double value) {
try {
thermo2.setValue(thermo2.getValue().doubleValue() + value); }
catch (Exception ex) { ex.printStackTrace(); } }
/** * Sets the value label position for one of the thermometers. */
private void setShowValue() {
thermo2.setValueLocation(pickShow2.getSelectedIndex());
} }

Saludos y espero les sea de mucha utilidad
Zemanta Pixie
Secciones
luis (no verificado)

En respuesta a por DrakoFire (no verificado)

Aunque ya ha pasado mucho tiempo desde la duda y creo que ya la ha resuelto, la coloco aqui para aquellos que tengan la misma duda, que yo tambien tuve.
Los que hize fue crear un bufer con la imagen jfreechart del termometro convirtiendo esta imagen en un icono para luego pueda ser enviada bien sea a un panel, o label o un button, en fin.
1) creo una clase llamada Termometro, donde realizaremos segun los varios ejemplos que hay en internet el termometro con el jfreechart, donde le dejo dos parametros de entrada que son el titulo y el valor de la temperatura. Ademas sera necesario declarar como variable global el jafreechart que vamos a utilizar, para cuando llamemos la clase podamos acceder a esta variable. quedaria asi:

public class Termometro extends ApplicationFrame
{
public JFreeChart jfreechart;// declaracion de la variable
public Termometro(String titulo, Double temperatura) {
//...
}
//demas codigo necesario
}
luego al haber creado la clase, la podremos llamar desde cualquier parte. yo cree un JForm y hay inclui un jlabel y en la propiedad icon envie la imagen mediante un boton, asi:

t2 = Double.valueOf(temperatura1.getText());
Termometro ter1 = new Termometro("Termometro 1",t2);
BufferedImage im = ter1.jfreechart.createBufferedImage(300, 300);
label1.setIcon(new ImageIcon(im));

donde el objeto temperatura1 es un campo de texto que recojo como parametro de entrada o cualquier objeto que querais utilizar.
espero que a alguno le sirva...

Lun, 06/02/2012 - 11:32 Enlace permanente
deimos (no verificado)

que onda!! oye, disculpa, pero no pudieras pasar el proyecto completo, no me corre, no se si porque no supe cargar las librerias

Mar, 16/07/2013 - 13:44 Enlace permanente

Contenido Relacionado

Ireport y Oracle en Linux

Ireport y Oracle en Linux

Ejemplo de termometro en Java

Ejemplo de termometro en Java

Estrategias para desarrollo en Palm

Estrategias para desarrollo en Palm