这是我到目前为止的代码。我正在尝试让jframe在用户的输入等待时间连续检查。
package currencyCheck;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class Main extends javax.swing.JFrame{
// private int waitTimeInSec;
// private double targetRate;
// private String currencyPair;
private CurrencyHandler handler;
XMLParser var = new XMLParser();
private InputStream is;
private URLConnection connection;
private final String url = "https://rates.fxcm.com/RatesXML";
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
// public XMLParser()
// {
// this.getCurrencySymbol();
// this.getTargetRate();
// this.setWaitTime();
// this.handler = new CurrencyHandler(currencyPair);
// }
private void parseXML()
{
SAXParserFactory parser = SAXParserFactory.newInstance();
try {
connection = new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
is = connection.getInputStream();
SAXParser saxParser = parser.newSAXParser();
saxParser.parse(is, handler);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void scheduleXMLParser()
{
while (handler.getCurrentBid() != var.getTargetBidRate()) {
try {
//System.out.println("Scheduler: Waiting for " + this.waitTimeInSec + " sec");
Thread.sleep(var.getWaitTimeInSec() * 1000);
} catch (InterruptedException ex) {
Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
}
this.parseXML();
//System.out.println("testing - current bid: " + this.handler.getCurrentBid());
}
JOptionPane.showMessageDialog(null, "Target Reached!");
//System.out.println("Target Reached: " + this.handler.getCurrentBid());
}
// private void getCurrencySymbol(){
// CurrencyPairs currency = new CurrencyPairs();
// currencyPair = currencySymbolInputField.getText().trim();
//
// while(!currency.validateCurrencySymbol(currencyPair)){
// JOptionPane.showMessageDialog(null, "Incorrect Symbol");
// }
// }
// private void getTargetRate(){
// String tarRate = targetRateInputField.getText().trim();
//
// try{
// targetRate = Double.parseDouble(tarRate);
// }catch(NumberFormatException nd){
// JOptionPane.showMessageDialog(null, nd);}
//
// }
// private void setWaitTime(){
// String waitTime = waitTimeInputField.getText().trim();
//
// //waitTimeInSec = Integer.parseInt(waitTime);
// try{
// //Check for an integer input
// waitTimeInSec = Integer.parseInt(waitTime);
// }catch(NumberFormatException e){
// JOptionPane.showMessageDialog(null, e);
// }
// }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
currencySymbolInputField = new javax.swing.JTextField();
targetRateInputField = new javax.swing.JTextField();
waitTimeInputField = new javax.swing.JTextField();
startButton = new javax.swing.JButton();
exitButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Currency Check");
setAlwaysOnTop(true);
setLocation(new java.awt.Point(50, 50));
jLabel1.setText("Currency Symbol");
jLabel2.setText("Target Rate");
jLabel3.setText("Wait Time ");
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
exitButton.setText("Exit");
exitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(78, 78, 78))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(currencySymbolInputField)
.addComponent(targetRateInputField)
.addComponent(waitTimeInputField, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(38, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(currencySymbolInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(targetRateInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(waitTimeInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38))
);
pack();
}// </editor-fold>
private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(currencySymbolInputField.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter a currency symbol.");
}else if(targetRateInputField.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter a target rate.");
}else if(waitTimeInputField.getText().isEmpty()){
JOptionPane.showMessageDialog(null,"Please enter a wait time.");
}else{
// //Currency Symbols
CurrencyPairs currency = new CurrencyPairs();
String currencyPair = currencySymbolInputField.getText().trim();
while(!currency.validateCurrencySymbol(currencyPair)){
JOptionPane.showMessageDialog(null, "Incorrect Symbol");
}
//Set Currency Pair
var.setCurrencyPair(currencyPair);
//Target rates
String tarRate = targetRateInputField.getText().trim();
try{
var.setTargetBidRate(Double.parseDouble(tarRate));
}catch(NumberFormatException nd){
JOptionPane.showMessageDialog(null,"Not a double.");
}
//Wait Time
String waitTime = waitTimeInputField.getText().trim();
try{
var.setWaitTimeInSec(Integer.parseInt(waitTime));
}catch(NumberFormatException ni){
JOptionPane.showMessageDialog(null,"Not an integer.");
}
scheduleXMLParser();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField currencySymbolInputField;
private javax.swing.JButton exitButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton startButton;
private javax.swing.JTextField targetRateInputField;
private javax.swing.JTextField waitTimeInputField;
// End of variables declaration
}
CurrencyHandler.java类
public class CurrencyHandler extends DefaultHandler {
private boolean foundCurrency = false;
private boolean bBid = false;
private String currencySymbol;
private float currentBid;
CurrencyHandler(String currencySymbol)
{
this.currencySymbol = currencySymbol;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
// System.out.println("s " + qName);
if (currencySymbol.equalsIgnoreCase(attributes.getValue("Symbol")))
{
foundCurrency = true;
}
else if(qName.equalsIgnoreCase("Bid"))
this.bBid = true;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// System.out.println("e " + qName);
if(qName.equalsIgnoreCase("Rate"))
{
this.foundCurrency = false;
}
else if(qName.equalsIgnoreCase("Bid"))
this.bBid = false;
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
// System.out.println("c " + new String(ch, start, length));
if(this.foundCurrency == true && this.bBid == true)
{
// System.out.println(Float.parseFloat(new String(ch, start, length)));
this.currentBid = Float.parseFloat(new String(ch, start, length));
}
}
float getCurrentBid() {
return currentBid;
}
}
CurrencyCheck.java类
public class CurrencyPairs {
private final String[] currencyList = {"EURUSD","USDJPY","GBPUSD","USDCHF","EURCHF","AUDUSD","USDCAD",
"NZDUSD","EURGBP","EURJPY","GBPJPY","CHFJPY","GBPCHF","EURAUD",
"EURCAD","AUDCAD","AUDJPY","CADJPY","NZDJPY","GBPCAD","GBPNZD",
"GBPAUD","AUDNZD","USDSEK","EURSEK","EURNOK","USDNOK","USDMXN",
"AUDCHF","EURNZD","USDZAR","USDHKD","USDTRY","EURTRY","NZDCHF",
"CADCHF","NZDCAD","TRYJPY","USDILS","USDCNH","AUS200","ESP35" ,
"FRA40","GER30","HKG33","JPN225","NAS100","SPX500","UK100","US30",
"Copper","CHN50","EUSTX50","USDOLLAR","USOil","UKOil","SOYF","NGAS",
"Bund","XAUUSD","XAGUSD"};
public boolean validateCurrencySymbol(String currency)
{
for (String i : currencyList)
{
if(currency.equalsIgnoreCase(i))
return true;
}
return false;
}
}
XMLParser.java类
公共类XMLParser {
private CurrencyHandler handler;
private InputStream is;
private URLConnection connection;
private final String url = "https://rates.fxcm.com/RatesXML";
private double targetBidRate;
private int waitTimeInSec;
private String currencyPair;
public XMLParser() {
this.handler = new CurrencyHandler(currencyPair);
this.targetBidRate = getTargetBidRate();
this.waitTimeInSec = getWaitTimeInSec();
this.currencyPair = getCurrencyPair();
}
public CurrencyHandler getHandler() {
return handler;
}
public void setHandler(CurrencyHandler handler) {
this.handler = handler;
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
public URLConnection getConnection() {
return connection;
}
public void setConnection(URLConnection connection) {
this.connection = connection;
}
public double getTargetBidRate() {
return targetBidRate;
}
public void setTargetBidRate(double targetBidRate) {
this.targetBidRate = targetBidRate;
}
public int getWaitTimeInSec() {
return waitTimeInSec;
}
public void setWaitTimeInSec(int waitTimeInSec) {
this.waitTimeInSec = waitTimeInSec;
}
public String getCurrencyPair() {
return currencyPair;
}
public void setCurrencyPair(String currencyPair) {
this.currencyPair = currencyPair;
}
}
显示的异常如下:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at currencyCheck.Main.scheduleXMLParser(Main.java:71)
at currencyCheck.Main.startButtonActionPerformed(Main.java:251)
at currencyCheck.Main.access$000(Main.java:19)
at currencyCheck.Main$1.actionPerformed(Main.java:149)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
我将非常感谢您的帮助,因为我似乎无法发现自己在做什么错。