即時製作一個貨幣計算器,我有一個問題,無法將計算結果設置爲結果JTextField,這是對象otherTextField。爲什麼JTextField的setText在actionPerformed方法中不起作用?
這裏是我的類:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ValutaKalkulator implements ActionListener {
private double nokValue;
private double otherValue;
private JButton buttonRemoveNok;
private JButton removeOther;
private JButton removeBoth;
private JButton exitButton;
private JButton usdButton;
private JButton sekButton;
private JButton gbpButton;
private JButton eurButton;
private JLabel nokLabel;
private JTextField nokTextField;
private JLabel otherLabel;
private JTextField otherTextField;
public ValutaKalkulator()
{
JFrame frame = new JFrame();
frame.setTitle("VALUTAKALKULATOR");
buttonRemoveNok = new JButton("Fjern NOK");
removeOther = new JButton("Fjern annen valuta");
removeBoth = new JButton("Fjern begge");
exitButton = new JButton("Avslutt");
usdButton = new JButton("USD");
sekButton = new JButton("SEK");
gbpButton = new JButton("GBP");
eurButton = new JButton("EUR");
nokLabel = new JLabel("NOK");
JTextField nokTextField = new JTextField();
otherLabel = new JLabel("Annen valuta");
otherTextField = new JTextField();
buttonRemoveNok.addActionListener(this);
removeOther.addActionListener(this);
removeBoth.addActionListener(this);
exitButton.addActionListener(this);
usdButton.addActionListener(this);
sekButton.addActionListener(this);
gbpButton.addActionListener(this);
eurButton.addActionListener(this);
JPanel pnlSouth = new JPanel(new GridLayout(1, 4));
JPanel pnlCenter = new JPanel(new GridLayout(2, 2));
JPanel pnlNorth = new JPanel(new GridLayout(1, 4));
pnlNorth.add(nokLabel);
pnlNorth.add(nokTextField);
pnlNorth.add(otherLabel);
pnlNorth.add(otherTextField);
pnlCenter.add(gbpButton);
pnlCenter.add(eurButton);
pnlCenter.add(usdButton);
pnlCenter.add(sekButton);
pnlSouth.add(buttonRemoveNok);
pnlSouth.add(removeOther);
pnlSouth.add(removeBoth);
pnlSouth.add(exitButton);
frame.add(pnlNorth, BorderLayout.NORTH);
frame.add(pnlSouth, BorderLayout.SOUTH);
frame.add(pnlCenter, BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
}
public String calculateFromNok(String nokValueString, String toValue)
{
double result = 0;
double nokValue = Double.valueOf(nokValueString);
switch(toValue)
{
case "GBP":
result = nokValue * 10.8980/100;
break;
case "EUR":
result = nokValue * 9.2450/100;
break;
case "USD":
result = nokValue * 8.5223/100;
break;
case "SEK":
result = nokValue * 96.48/100;
break;
}
String resultString = Double.toString(result);
return resultString;
}
public void actionPerformed(ActionEvent event)
{
String text = event.getActionCommand();
switch(text)
{
case "USD":
String txt = nokTextField.getText();
String txt2 = calculateFromNok(txt, "USD");
otherTextField.setText(txt2);
break;
}
}
}
我知道貨幣是不正確的,還有其他的邏輯上的缺陷和不良變量名,但我現在的問題是,爲什麼我不能從方法把結果calculateFromNok到我的JTextField otherTextField?
幫助讚賞thx!
嘗試設置斷點並在縮進箱體後運行調試器 –