如何将JTable顶行中的条目与匹配值进行比较? [英] How to compare an entry in the top row of a JTable to a matching value?

查看:94
本文介绍了如何将JTable顶行中的条目与匹配值进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个应用程序,其中用户将时间和日期输入到JTable中,然后在那时收到警报.我计划的方式是,条目按时间顺序显示,最上面的一行显示在最接近的位置,然后每5分钟与用户的日期/时间进行比较,直到它们匹配为止.

I am trying to create an application where the user inputs a time and date into a JTable and then receives an alert at that time. The way in which I have planned it is that the entries are displayed in chronological order with the nearest on the top row and are then compared every 5 minutes to the user's date/time until they match.

我觉得我可以算出此计划中的所有内容,除了实际扫描中只有顶行和3列中的2列(DATE和TIME列,而不是NAME).如果有人对如何进行此工作有任何建议,或者如果我应该更改处理此问题的方式,我将不胜感激,谢谢.

I feel that I can figure out everything in this plan except the actual scanning of only the top row and 2 columns out of 3 (Columns DATE and TIME, but not NAME). If anyone has any recommendations on how to make this work or if I should change how I am approaching this problem I would much appreciate it, thank you.

推荐答案

我希望下面的示例能够回答您的问题.

I hope below example will answer your question.

(这里我假设该表是按日期和时间排序的,最早的警报位于该表的顶部.)

(Here I'm assuming that the table is sorted by date and time and the earliest alert is at the top of the table.)

import javax.swing.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimerTask;
import java.util.Timer;

public class DateTimeTable
{
  public static void main(String[] args)
  {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTable table = new JTable(
        new String[][] {
            {"Water plants", "2019.01.12", "09:21"},
            {"Read Java book", "2019.01.12", "19:30"},
            {"Go to bed", "2019.01.12", "22:30"}},
        new String[] {"Name", "Date", "Time"});

    TimerTask task = new TimerTask()
    {
      @Override
      public void run()
      {
        String date = table.getValueAt(0, 1).toString();
        String time = table.getValueAt(0, 2).toString();
        LocalDateTime alertTime = LocalDateTime.parse(date + " " + time,
            DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm"));

        if (alertTime.isBefore(LocalDateTime.now()))
        {
          JOptionPane.showMessageDialog(f, table.getValueAt(0, 0));
        }
        else
        {
          System.out.println("No alerts");
        }
      }
    };

    Timer timer = new Timer();
    timer.schedule(task, 1000, 5 * 60 * 1000);

    f.getContentPane().add(new JScrollPane(table));
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

这篇关于如何将JTable顶行中的条目与匹配值进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆