gpt4 book ai didi

java - 日期和时间未更新

转载 作者:行者123 更新时间:2023-12-01 21:36:03 25 4
gpt4 key购买 nike

我的程序使用日期来检查工程师访问机器的时间。唯一的问题是日期不是最新的。机器显示的日期和时间是机器启动的确切时间。不是在单击按钮时。任何帮助都会有帮助。

代码:

package com.perisic.beds.peripherals;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.*;

import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;

import com.perisic.beds.machine.CustomerPanel;


/**
* A Simple Graphical User Interface for the Recycling Machine.
* @author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {

/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();

ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();

CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);

private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";

private int numberOfVisits;



DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* @param myCookie
* @return
*/

public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}

public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}

/**
* Web service to authenticate the user with proper password.
* @param passwd
* @return
*/

public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}

public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}

/**
* Web service to logout from the system.
*/

public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}


public static final String SUN_JAVA_COMMAND = "sun.java.command";

//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}

public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;

boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);


//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);

//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}

//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}

//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);


}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}


}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );


}

//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");

JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");

/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);

slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);

panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);

/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);

getContentPane().add(panel);
panel.repaint();

}

public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}

}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}

public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}

@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};

System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}

public void print(String str) {
System.out.println(str);

}

}

最佳答案

您永远不会重新初始化date,您只是用现有date更新storedDate登录。您可以在 login

中更改此行
storedDate = date;

storedDate = new Date();

然后(我认为)您可以删除日期

关于java - 日期和时间未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36944035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com