当前位置: 首页 > 面试题库 >

尝试每x秒执行一次文件

祁绪
2023-03-14
问题内容

请查找每10秒钟重复一次的更新代码。但是,问题在于它每10秒在屏幕上创建一个新的GUI,而不是仅每10秒更新一次数据。请您指教

package learningfromscrach;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import javax.swing.JTextArea;
import com.sun.java.swing.*; 
import javax.swing.table.*;
import java.awt.FlowLayout;
import java.text.DecimalFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.BasicConfigurator;
import static org.quartz.DateBuilder.evenMinuteDate;
import org.quartz.Job;
import static org.quartz.JobBuilder.newJob;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;


public class Learningfromscrach extends JFrame implements Job {

    Toolkit toolkit;
    Timer timer;

//declare all the parts that make up the GUI    
private JLabel textJLabel;
private JPanel PanelJlabel;//JLabel is actually a parameter in JAVA
private TitledBorder PanelJborder;



DefaultTableModel model;
JTable table;


public Learningfromscrach(int seconds) 
   //tell java to initiate the create interface
        //this is what is passed to the timer every 10 seconds
   {

    createUserInterface();//create method private void createUserInterface//aframe is parameter this has to match the private void
    }

class Learningtask extends TimerTask {
public void run() {
System.out.format("Timer Task Finished..!%n");
//System.exit(0); // Terminate the timer thread
}
}

private void createUserInterface()

 //all the parts to create the userinterface      
{//from here
        Container contentPane = getContentPane();
        contentPane.setLayout( null);// i am responsible for setting positioning and size of components
        setTitle("Cashout Prices");//setTitle is also a JAVA Parameter


        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setSize((int) (screenSize.width/6), (int) (screenSize.height/1.1));//cast int for width
        setVisible(true);    //makes the java application show



       System.out.format("Timer task started at:"+new Date());   
         String url = "http://bmreports.com/bsp/additional/soapfunctions.php?element=SYSPRICE&dT=NRT";
  Document doc = null;
    try {
        doc = Jsoup.connect(url).get();
    } catch (IOException ex) {
        Logger.getLogger(Learningfromscrach.class.getName()).log(Level.SEVERE, null, ex);
    }
  Elements Periodparagraphs;      
  Elements SSPparagraphs;
  Elements SBPparagraphs;

  Periodparagraphs = doc.select("SP");//counts the number of SSP Paragraphs in the entire document
  SSPparagraphs = doc.select("SSP");//counts the number of SSP Paragraphs in the entire document
  SBPparagraphs = doc.select("SBP");//counts the number of SBP Paragraphs in the entire document

  //DecimalFormat df = new DecimalFormat("#.###");
//df.format(0.912385);


  String[] numbers1;
    numbers1 = Periodparagraphs.text().split(" ");



    String[] numbers;
    numbers = SSPparagraphs.text().split(" ");

    String[] numbers0;
    numbers0 = SBPparagraphs.text().split(" ");

    //String str = "1234";
//int num = Integer.parseInt(str);

    int tableRows;

    if (numbers0.length > numbers.length && numbers0.length > numbers1.length)

    {
        tableRows = numbers0.length;
    }

    else if (numbers.length > numbers0.length && numbers.length > numbers1.length)
    {
        tableRows = numbers.length;
    }
    else
    {
        tableRows = numbers1.length;
    }
    //model = new DefaultTableModel(col, 90);//50 is number of rows --You don't seem to need this

    Object[][] data = new String[tableRows][3];//3 is number of columns

    for (int x = 0; x < tableRows; x++ )
    {
        try
        {
            data[x][0] = numbers1[x];
        }
        catch (IndexOutOfBoundsException e)
        {
            data[x][0] = "  ";//error
        }

        try
        {
            data[x][1] = numbers[x];
        }
        catch (IndexOutOfBoundsException e)
        {
            data[x][1] = "  ";
        }

        try
        {
            data[x][2] = numbers0[x];
        }
        catch (IndexOutOfBoundsException e)
        {
            data[x][2] = "  ";
        }
    }



     //header.setBackground(Color.yellow);
    //    model = new DefaultTableModel(col,90);//50 is number of rows

    String col[] = {"SBP","SSP","Period"};
    table=new JTable(data,col){@Override



       public boolean isCellEditable(int arg0, int arg1) {
    return false;
        }};

       JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
    contentPane.add(table);

        //table.setValueAt(SBPparagraphs.text(),0,0); //first number is moves placing down by 2 rows//2nd number is next cclumn and so on
        //table.setValueAt("fgfg",0,0);




        table.setSize(screenSize.width/2, (int) (screenSize.height/1.1));
        table.setBounds(16,50,400,2000);
    table.setLayout(null);
        table.setVisible(true);
//add(table.getTableHeader(), BorderLayout.NORTH);   
  //      table.setLayout(new BorderLayout());
//add(table, BorderLayout.CENTER);
    setDefaultCloseOperation(EXIT_ON_CLOSE);


}





//to hear this all refers to the contentpane

    /**
     * @param args the command line arguments
     */


    public static void main(String[] args) throws SchedulerException, InterruptedException {
            // TODO code application logic here
// BasicConfigurator.configure();
        new Learningfromscrach(1);



        System.out.format("Task scheduled.. Now wait for 5 sec to see next message..%n");


    }




    //next step to understand how to get data into the panel

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        _log.info("Hello World! - " + new Date()); 
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

问题答案:

您只有一门课,Learningfromscrach。在其中,您具有主要功能。在主要功能内,您将创建 另一个 Learningfromscrach
实例 ,该 实例 现在传递给计时器,每10秒运行一次。当它在10秒内运行时,它会创建另一个Learningfromscrach实例,依此类推。

您实际上并不需要每10秒重新实施Learningfromscrach。您想要的是每10秒更新一次数据。您应该能够在每10秒运行一次的更新功能上设置计时器。(我现在无法编写代码示例,但请对此进行调查,看看有多深入。)

编辑:我重构了您的项目,消除了未使用的元素,并添加了一些方法和JScrollPane。希望这可以帮助。

import java.awt.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import javax.swing.table.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
import java.awt.BorderLayout;


public class Learningfromscrach extends JFrame 
{
    Toolkit toolkit;
    Timer timer = new Timer();
    DefaultTableModel model;
    JTable table;
    String url = "http://bmreports.com/bsp/additional/soapfunctions.php?element=SYSPRICE&dT=NRT";
    String col[] = {"SBP","SSP","Period"};
    JScrollPane scrollPane;

    public Learningfromscrach() 
    //tell java to initiate the create interface
    //this is what is passed to the timer every 10 seconds
    {
        createUserInterface();
    }

private void createUserInterface()
//all the parts to create the userinterface      
{//from here
    setLayout( new BorderLayout());
    setTitle("Cashout Prices");//setTitle is also a JAVA Parameter
    setVisible(true);    //makes the java application show


    table = CreateTable(url,col);

    scrollPane = new JScrollPane(table,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(scrollPane,BorderLayout.CENTER);
    pack();
    setSize(getWidth(), 200); //initial size

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    int delay = 5000; //5 seconds
    int period = 5000; //5 seconds

    timer.scheduleAtFixedRate(new TimerTask() 
    {
        public void run() {
            RefreshTable(url, col);
            System.out.format("Task run..");
        }
    }, delay, period);
}     
private Object[][] GetTableInfo(String url)
{
      Document doc = null;
      try 
      {
            doc = Jsoup.connect(url).get();
      } 
      catch (IOException ex) 
      {
            Logger.getLogger(Learningfromscrach.class.getName()).log(Level.SEVERE, null, ex);
      }
      Elements Periodparagraphs;      
      Elements SSPparagraphs;
      Elements SBPparagraphs;

      Periodparagraphs = doc.select("SP");//counts the number of SSP Paragraphs in the entire document
      SSPparagraphs = doc.select("SSP");//counts the number of SSP Paragraphs in the entire document
      SBPparagraphs = doc.select("SBP");//counts the number of SBP Paragraphs in the entire document

      String[] numbers1;
      numbers1 = Periodparagraphs.text().split(" ");

      String[] numbers;
      numbers = SSPparagraphs.text().split(" ");

      String[] numbers0;
      numbers0 = SBPparagraphs.text().split(" ");

      int tableRows;

      if (numbers0.length > numbers.length && numbers0.length > numbers1.length)
      {
          tableRows = numbers0.length;
      }
      else if (numbers.length > numbers0.length && numbers.length > numbers1.length)
      {
          tableRows = numbers.length;
      }
      else
      {
          tableRows = numbers1.length;
      }

      Object[][] data = new String[tableRows][3];//3 is number of columns

      for (int x = 0; x < tableRows; x++ )
      {
          try
          {
              data[x][0] = numbers1[x];
          }
          catch (IndexOutOfBoundsException e)
          {
              data[x][0] = "  ";//error
          }

          try
          {
              data[x][1] = numbers[x];
          }
          catch (IndexOutOfBoundsException e)
          {
              data[x][1] = "  ";
          }

          try
          {
              data[x][2] = numbers0[x];
          }
          catch (IndexOutOfBoundsException e)
          {
              data[x][2] = "  ";
          }
      }

    return data;
}

private JTable CreateTable(String url, String[] cols)
{
    JTable tempTable=new JTable(GetTableInfo(url),col)
    {
        @Override
        public boolean isCellEditable(int arg0, int arg1) 
        {
            return false;
        }   
    };

    JTableHeader header = tempTable.getTableHeader();
    header.setBackground(Color.yellow);

    tempTable.setLayout(null);
    tempTable.setVisible(true);

    return tempTable;
}

private void RefreshTable(String url, String[] cols)
{
    Object[][] info = GetTableInfo(url);
    for (int row = 0; row < info.length; row++)
    {
        for (int column = 0; column < cols.length; column++)
        {
            table.setValueAt(info[row][column],row, column);
        }
    }
}

public static void main(String[] args) throws InterruptedException 
{
    // TODO code application logic here
    // BasicConfigurator.configure();
    new Learningfromscrach();

    System.out.format("Task scheduled.. Now wait for 5 sec to see next message..%n");
}

}



 类似资料:
  • 问题内容: 我有一个ajax调用到一个php文件。我正在收到结果。现在,我正在研究是否有可能使ajax请求每1秒自动执行一次。我将结果发布到名为的输入字段中。如何每三秒钟执行一次ajax调用而不必调用该函数? 问题答案: 您可能要考虑的是服务器发送事件(SSE) 这是一种HTML5技术,JavaScript可以通过该技术“ 长期轮询 ”服务器端点(您的PHP文件)以查看是否发生了任何更改。长轮询基

  • 问题内容: 最近我一直在使用带有大量数字的循环来打印Hello World: 我知道这是一种非常愚蠢的方法,但是我从未使用过Java中的任何计时器库。一个如何修改以上内容以每3秒打印一次? 问题答案: 你还可以查看和类,这些类可用于计划任务每​​秒钟运行一次。 你需要一个扩展并覆盖该方法的类,该类将在每次将该类的实例传递给方法时执行。 这是一个示例,每5秒打印一次:-

  • 最近,我一直使用带有大数字的循环来打印: 我知道这是一个非常愚蠢的方法,但我从来没有使用任何计时器库在Java。如何修改上面的打印每说3秒?

  • 我想每10秒执行一段代码。我在这个论坛上找到了一个例子,但我的实现有一些问题。 我得到这个错误,指向:

  • 问题内容: 我想知道如何每x秒重绘和更新JPanel的背景…这是我的代码: 我的代码有2个问题:1-JPanel根本没有被绘制。2-第一张可以打印,然后每次打印数量增加一倍。有什么建议吗?先感谢您 更新:我以这种方式解决了这个问题: 更新2: 问题答案: 使用Swing计时器,

  • 最近我一直在使用带有大量数字的循环来打印: 我知道这是一种非常愚蠢的方法,但我还从未在Java中使用过任何计时器库。如何修改上述内容,使其每3秒打印一次?