【发布时间】:2012-10-31 05:40:04
【问题描述】:
所以我只是把我作业的最后一个细节放进去,我注意到了 getCursor();当我运行我的程序时工作,但后来在程序中(在两个 actionListeners 中)它不会转向 fahrenheitTB。我想知道我是否可以得到一些输入。非常感谢。这是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Part3Question1 extends JPanel
{
private JTextField fahrenheitTB;
private JTextField celsiusResultTB;
private JButton tryAgain;
public Part3Question1()
{
Color color=new Color(255,0,0);
JLabel fahrenheitLabel = new JLabel ("Enter Fahrenheit temperature:");
add (fahrenheitLabel);
fahrenheitTB = new JTextField (5);
fahrenheitTB.setHorizontalAlignment(fahrenheitTB.CENTER);
//Works here!
fahrenheitTB.getCursor();
add (fahrenheitTB);
JLabel celsiusLabel = new JLabel ("Temperature in Celsius: ");
add (celsiusLabel);
celsiusResultTB = new JTextField (5);
celsiusResultTB.setForeground(color);
celsiusResultTB.setEditable(false);
celsiusResultTB.setHorizontalAlignment(celsiusResultTB.CENTER);
add (celsiusResultTB);
JButton convertButton = new JButton("Convert!");
add (convertButton);
tryAgain = new JButton("Try Again!");
tryAgain.setVisible(false);
add (tryAgain);
convertButton.addActionListener (new myFirstActionListener());
tryAgain.addActionListener (new mysecondActionListener());
}
private class myFirstActionListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheitTB.getText();
try
{
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
celsiusResultTB.setText (Integer.toString (celsiusTemp));
tryAgain.setVisible(true);
}
catch (NumberFormatException e)
{
String myException="Invalid entry. Please enter Integers Only";
JOptionPane.showMessageDialog(null,myException);
fahrenheitTB.setText("");
//doesn't work here!
fahrenheitTB.getCursor();
}
}
}
private class mysecondActionListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
fahrenheitTB.setText("");
//doesn't work here!
fahrenheitTB.getCursor();
celsiusResultTB.setText("");
}
}
public static void main (String[] args)
{
JFrame myFrame = new JFrame ();
myFrame.setTitle("Fahrenheit to Celsius Converter");
myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
myFrame.setPreferredSize(new Dimension(300,150));
myFrame.setLocation(400,300);
Part3Question1 panel = new Part3Question1();
myFrame.getContentPane().add(panel);
myFrame.pack();
myFrame.setVisible(true);
}
}
【问题讨论】:
-
it doesn't work是什么意思?据我所知,你什么也没做?您是否试图将注意力转移到该领域?然后你需要使用requestFocusInWindow。getCursor只会返回该字段正在使用的鼠标光标形状。 -
@MadProgrammer,你是对的,我不清楚。基本上我试图让光标回到那个 fahrenheitTB。我要试试你说的。感谢您的回复。
-
所以我尝试了 requestFocusInWindow 并且光标没有重新出现在 fahrenheitTB 中。
标签: java swing cursor mouseevent actionlistener