如何将 JTable 顶行中的条目与匹配值进行比较?
How to compare an entry in the top row of a JTable to a matching value?
我正在尝试创建一个应用程序,用户可以在其中将时间和日期输入 JTable
,然后在该时间收到警报。我计划的方式是条目按时间顺序显示,最近的条目显示在第一行,然后每 5 分钟与用户的 date/time 进行比较,直到它们匹配。
我觉得我可以弄清楚这个计划中的所有内容,除了实际只扫描顶行和 3 列中的 2 列(列 DATE 和 TIME,但不包括 NAME)。如果有人对如何完成这项工作有任何建议,或者如果我应该改变我处理这个问题的方式,我将不胜感激,谢谢。
我希望下面的例子能回答你的问题。
(这里我假设 table 按日期和时间排序,最早的警报在 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
,然后在该时间收到警报。我计划的方式是条目按时间顺序显示,最近的条目显示在第一行,然后每 5 分钟与用户的 date/time 进行比较,直到它们匹配。
我觉得我可以弄清楚这个计划中的所有内容,除了实际只扫描顶行和 3 列中的 2 列(列 DATE 和 TIME,但不包括 NAME)。如果有人对如何完成这项工作有任何建议,或者如果我应该改变我处理这个问题的方式,我将不胜感激,谢谢。
我希望下面的例子能回答你的问题。
(这里我假设 table 按日期和时间排序,最早的警报在 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);
}
}