How to compare an entry in the top row of a JTable to a matching value?

回眸只為那壹抹淺笑 提交于 2019-12-13 08:55:10

问题


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.

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.


回答1:


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);
  }
}


来源:https://stackoverflow.com/questions/54147711/how-to-compare-an-entry-in-the-top-row-of-a-jtable-to-a-matching-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!