问题
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