Обработка событий Java с задержкой

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JPanel;
import javax.swing.Timer;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
 * A simple demonstration application showing how to create a pie chart using
 * data from a {@link DefaultPieDataset}.
 */
public class PieChartDemo1 extends ApplicationFrame implements ChartMouseListener {
private JFreeChart chart; 
private PiePlot plot;
private int angle=270;
private static double explodePercent = 0.99;
private static long count=0;
/**
 * Default constructor.
 *
 * @param title  the frame title.
 */
public PieChartDemo1(String title) {
    super(title);
           this.chart = ChartFactory.createPieChart(
            "Pie Chart Demo 1",  // chart title
            createDataset(),             // data
            true,               // include legend
            true,
            false
        );

        this.plot = (PiePlot) chart.getPlot();
        this.plot.setSectionOutlinesVisible(false);
        this.plot.setNoDataMessage("No data available");
        this.plot.setBackgroundAlpha(0.2f);
        this.plot.setBackgroundPaint(Color.WHITE); 
        this.plot.setExplodePercent("One",.99);
        this.angle=270;
        ChartPanel chartpanel = new ChartPanel(chart, false, false, false, false,      false);   
        chartpanel.setVisible(true);
    chartpanel.addChartMouseListener(this);
    chartpanel.setPreferredSize(new Dimension(500, 270));
    setContentPane(chartpanel);
}

/**
 * Creates a sample dataset.
 *
 * @return A sample dataset.
 */
private static PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("One", new Double(43.2));
    dataset.setValue("Two", new Double(10.0));
    dataset.setValue("Three", new Double(27.5));
    dataset.setValue("Four", new Double(17.5));
    dataset.setValue("Five", new Double(11.0));
    dataset.setValue("Six", new Double(19.4));
    return dataset;
}

/**
 * Creates a chart.
 *
 * @param dataset  the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart3D(
        "Pie Chart Demo 1",  // chart title
        dataset,             // data
        true,               // include legend
        true,
        false
    );

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setSectionOutlinesVisible(false);
    plot.setNoDataMessage("No data available");
    plot.setBackgroundAlpha(0.2f);
    return chart;

}

/**
 * Creates a panel for the demo (used by SuperDemo.java).
 *
 * @return A panel.
 */
public static JPanel createDemoPanel() {
    JFreeChart chart = createChart(createDataset());
    ChartPanel chartpanel = new ChartPanel(chart, false, false, false, false, false);   
    chartpanel.setVisible(true);      
    chartpanel.setPreferredSize(new Dimension(500, 270));
    return new JPanel();
}

/**
 * Starting point for the demonstration application.
 *
 * @param args  ignored.
 */
public static void main(String[] args) {


    PieChartDemo1 demo = new PieChartDemo1("Pie Chart Demo 1");
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
}

public void chartMouseClicked(ChartMouseEvent chartmouseevent)
{
ChartEntity chartentity = chartmouseevent.getEntity();
if (chartentity != null){
    this.plot.setStartAngle(angle);
    this.angle=angle+5;
    this.plot.setStartAngle(angle);
    this.plot.setExplodePercent("One", .8);
    System.out.println("Mouse clicked: " + chartentity.toString());
}
else
System.out.println("Mouse clicked: null entity.");
}

public void chartMouseMoved(ChartMouseEvent chartmouseevent)
{
int i = chartmouseevent.getTrigger().getX();
int j = chartmouseevent.getTrigger().getY();
ChartEntity chartentity = chartmouseevent.getEntity();
if (chartentity != null)
{
    //this.plot.setStartAngle(angle);
//this.angle=angle-5;
//this.plot.setStartAngle(angle);
    System.out.println("Explode Percent is "+plot.getExplodePercent("One"));        
    Rotator rotator=new Rotator(plot);
    rotator.setInitialDelay(10000000);
    rotator.setDelay(100000000);

    rotator.start();
   //System.out.println("Mouse moved: " + i + ", " + j + ": " + chartentity.toString());
}
//else
//System.out.println("Mouse moved: " + i + ", " + j + ": null entity.");
}

static class Rotator extends Timer   {

    /** The plot. */
    private PiePlot plot;

    /** The angle. */

    private int X,Y;

    /**
     * Constructor.
     *
     * @param plot  the plot.
     */
    Rotator(final PiePlot plot) { 
        super(100,null);            
        this.plot = plot;               

        while(count<999999999&&explodePercent>=0){
        if(explodePercent>0)    
        explodePercent=explodePercent-.0001;
        else
        explodePercent=explodePercent+.0001;
        plot.setExplodePercent("One", explodePercent);
        count++;
        }




    }
}

}

Приведенный выше код используется для создания диаграммы, и мне нужно разработать что-то вроде ссылка на amcharts

Я пытался использовать таймер, но события не задерживаются независимо от используемой задержки. Может ли кто-нибудь помочь мне получить задержку? Это не имеет ничего общего с Jcharts. Это просто обработка событий.


person Harish    schedule 10.07.2009    source источник
comment
Было бы неплохо, если бы вы могли организовать размещенный код, использовать среду кода, доступную в редакторе вопросов.   -  person freitass    schedule 10.07.2009
comment
Второй @freitass, он тоже довольно длинный, стремитесь к SCCEE (sscce.org). Краткий пример, показывающий, что вы пробовали с Timer и почему он не оправдал ваших ожиданий, был бы идеальным.   -  person Nick Meyer    schedule 10.07.2009
comment
Извините, я действительно это делал   -  person Harish    schedule 10.07.2009
comment
Где ваши методы setDelay или setInitialDelay в вашем классе Rotator?   -  person AlbertoPL    schedule 10.07.2009
comment
Это в таймере, и я думаю, что мне не нужно его переопределять.   -  person Harish    schedule 10.07.2009
comment
Времена не знают о логике вашего приложения, вы должны реализовать некоторую логику, используя эти периоды.   -  person freitass    schedule 10.07.2009
comment
Любой пример для этого. Я очень плохо разбираюсь в обработке событий.   -  person Harish    schedule 10.07.2009


Ответы (2)


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

вместо этого у вас должна быть реализация PieChartDemo ActionListener и обработка вашего таймера:

 public void actionPerformed(ActionEvent actionevent) {
   //you can test if the event has come in from the timer
   if (actionevent.getSource() == myTimer) {
    while(count<999999999&&explodePercent>=0){
      if(explodePercent>0)    
         explodePercent=explodePercent-.0001;
      else
         explodePercent=explodePercent+.0001;
      getPlot().setExplodePercent("One", explodePercent);
     count++;
    }
   }
 }

или что-то типа того.

вам также нужно будет передать свой ActionListener в конструктор:

старый:

 Rotator(final PiePlot plot) { 
    super(100,null);   // this passes a null listener to the timer object 

новый:

 Rotator(final PiePlot plot, ActionListener listener) { 
    super(100, listener); // this will pass in the listener, which will then get timer updates, delayed as you have specified.   

вот хорошее руководство по таймерам свинга

person akf    schedule 10.07.2009

Ваш обработчик событий мыши никогда не освобождает ЦП. Rotator не заставляет поток спать, поэтому вся задержка происходит, как только обрабатывается событие мыши.

person Kelly S. French    schedule 10.07.2009
comment
Итак, как освободить ЦП. В классе Timer нет метода сна - person Harish; 10.07.2009
comment
Thread.currentThread().wait(1); //используем ожидание только для того, чтобы освободить ЦП - person Kelly S. French; 10.07.2009