getCursor() не работает в моем actionListener

Итак, я просто добавляю последние детали своего задания и заметил, что getCursor(); работает, когда я запускаю свою программу, но позже в программе (в двух actionListeners) она не переключается на фаренгейтТБ. Мне было интересно, могу ли я получить некоторый вклад, пожалуйста. Большое спасибо. Вот мой код:

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);
}
}

person Essi Joon    schedule 31.10.2012    source источник
comment
Что вы имеете в виду под it doesn't work? Насколько я понимаю, ты ничего с ним не делаешь? Вы пытаетесь переместить фокус на поле?? Тогда вам нужно использовать requestFocusInWindow. getCursor просто вернет вам форму курсора мыши, которая используется полем.   -  person MadProgrammer    schedule 31.10.2012
comment
@MadProgrammer, вы правы, я не ясно выразился. По сути, я пытался заставить курсор вернуться к фаренгейту ТБ. Я собираюсь попробовать то, что вы сказали. Спасибо за ответ.   -  person Essi Joon    schedule 31.10.2012
comment
поэтому я попробовал requestFocusInWindow, и курсор больше не появлялся в ФаренгейтТБ.   -  person Essi Joon    schedule 31.10.2012


Ответы (2)


Для начала неплохо было бы прочитать этот учебник: "Как использовать Подсистема фокуса". В вашей ситуации вы можете попробовать вызвать requestFocusInWindow() в вашем компоненте

Вот ваш обновленный код:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

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);
        // updated
        fahrenheitTB.requestFocusInWindow();
        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("");
            }finally{
                // updated
                fahrenheitTB.requestFocusInWindow();
                    }
        }
    }

    private class mysecondActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            fahrenheitTB.setText("");
            // updated
            fahrenheitTB.requestFocusInWindow();
            celsiusResultTB.setText("");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                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);

            }
        });
    }
}
person Sujay    schedule 31.10.2012
comment
+1 за то, что вы на правильном пути -1 за то, что пропустили очевидную ошибку ... исправьте, и я верну ее;) - person MadProgrammer; 31.10.2012
comment
Sunjay, Большое спасибо. Я заметил, что вы добавили несколько строк кода. Мне нужно прочитать о них и посмотреть, что они из себя представляют. Я очень новичок в этом, поэтому, например, код, который вы добавили в main, мне нужно изучить. Спасибо за вашу помощь и вклад. - person Essi Joon; 31.10.2012
comment
@MadProgrammer: О, ты имеешь в виду, что это в блоке finally :) Упс, примечание для себя: проверьте свой ответ перед публикацией! :D - person Sujay; 31.10.2012

Проблема в вашем myFirstActionListener, никогда не начинается запрос на фокус.

Блок исключения будет выполняться только в том случае, если есть исключение, в противном случае он будет проигнорирован.

Вместо...

} catch (NumberFormatException e) {
    String myException = "Invalid entry. Please enter Integers Only";
    JOptionPane.showMessageDialog(null, myException);
    fahrenheitTB.setText("");
    //doesn't work here!
    fahrenheitTB.requestFocusInWindow();
}

Вам нужно использовать

} catch (NumberFormatException e) {
    String myException = "Invalid entry. Please enter Integers Only";
    JOptionPane.showMessageDialog(null, myException);
    fahrenheitTB.setText("");
    //doesn't work here!
} finally {
    fahrenheitTB.requestFocusInWindow();
}

В моем тестировании «Попробуй еще раз» сработало, как и ожидалось.

Лично вы можете также вызвать selectAll после того, как запросите фокус fahrenheitTB.selectAll. Это личное дело, но теперь пользователю не нужно вручную очищать поле, чтобы ввести следующее значение... ;)

person MadProgrammer    schedule 31.10.2012