Я делаю программу, в которой одна часть программы предназначена для получения введенного текста от пользователя, который находится в текстовом поле. И проверьте, равен ли введенный текст «Благослови вас». И если это так, одна булева переменная сбрасывается, и я вызываю repaint для запуска других функций рисования. Я использую 'String input = TextField.getText ()', но каждый раз, когда я набираю что-то в текстовое поле и нажимаю ввод, возникает куча ошибок. Может кто-нибудь сказать мне, если я использую getText () неправильно? Спасибо.
Вот мой код-
// 3/22/19
// SneezePanels.java
/* IDEA of this program: PanelHolder, which is added to the frame, holds two panels,
LeftPanel and RightPanel, which are added to PanelHolder in a GridLayout. The
LeftHolder has a BorderLayout and has two panels-a direction panel, with a FlowLayout
that has a the button, and a textField panel that contains the textField. When
the button is pressed, Achoo and a yellow oval are drawn on the Right Panel.
When the user types in "Bless you" in the textField, the RightPanel is erased
and variables are reset.
*/
/// Testing: Only clicking on the button will draw on the right panel. Only typing
/// in "Bless you" will clear it.
/// Try clicking anywhere other that the button. This should will not change anything.
/// Typing anything other than "Bless you" will not reset the panels.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
public class SneezePanels
{
public static void main( String[] args )
{
SneezePanels sp = new SneezePanels();
sp.run();
}
public SneezePanels()
{
}
public void run()
{
JFrame sneezeFrame = new JFrame ("Sneeze and Bless you.");
sneezeFrame.setSize( 600, 400);
sneezeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sneezeFrame.setLocation(400,50);
sneezeFrame.setResizable(true);
PanelHolder pHolder = new PanelHolder();
sneezeFrame.add( pHolder );
sneezeFrame.setVisible(true);
}
// This panel holds two panels-one on the left and one on the right, aptly named
class PanelHolder extends JPanel
{
private RightPanel rp; // these are field variables so the nested classes have access to them
private boolean nosePressed; // otherwise, we have to use getter-setter methods
private Font font;
private JTextArea directions;
private JButton nose;
private JTextField blessYou;
public PanelHolder()
{
setLayout( new GridLayout(1, 2) );
nosePressed = false;
font = new Font("Serif", Font.BOLD, 20);
LeftPanel lp = new LeftPanel();
add(lp);
rp = new RightPanel();
add( rp );
}
// This panel will have a BorderLayout
// It will have the directions panel in the center, and the
// textField panel in the south.
class LeftPanel extends JPanel
{
public LeftPanel()
{
setLayout(new BorderLayout());
// setBackground( Color.MAGENTA );
DirectionPanel dirP = new DirectionPanel ();
TFPanel tfp = new TFPanel();
add ( dirP, BorderLayout.CENTER );
add ( tfp, BorderLayout.SOUTH );
}
}
// DirectionPanel will print the directions and contain the
// nose button. It has a FlowLayout. It will use a
// ButtonHandler for actionPerformed.
class DirectionPanel extends JPanel
{
public DirectionPanel()
{
setLayout(new FlowLayout());
nose = new JButton("nose");
Button1Handler b1 = new Button1Handler();
nose.addActionListener(b1);
add(nose);
directions = new JTextArea("Directions: Press button to tickle the nose.");
add(directions);
setBackground(Color.RED);
}
public void paintComponent( Graphics g )
{
super.paintComponent(g);
}
}
// The TFPanel will have a FlowLayout and contain a text field
// that will be on the left. It uses a handler class for
// actionPerformed
class TFPanel extends JPanel
{
private JTextField blessYou;
public TFPanel()
{
setLayout(new FlowLayout());
blessYou = new JTextField();
TextFieldHandler tfh = new TextFieldHandler();
blessYou.addActionListener(tfh);
blessYou.setText("Type: Bless you");
add(blessYou);
}
}
// The RightPanel is used to draw "Achoo" and a yellow oval when the
// button is pressed and cleared when "Bless you" is typed in
// the textField
class RightPanel extends JPanel
{
public RightPanel()
{
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(nosePressed)
{
g.setFont(font);
g.drawString("Achoo!", 125, 60);
g.setColor(Color.YELLOW);
g.fillOval(100, 80,100, 120);
}
}
}
// When the button is pressed, the method actionPerformed is
// used to call paintComponent in RightPanel
class Button1Handler implements ActionListener
{
public Button1Handler()
{
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == nose)
{
nosePressed = true;
}
rp.repaint();
}
} // end class Button1Handler
// When the user types in "Bless you" in the textField, the
// boolean is reset and RightPanel's paintComponent is called
class TextFieldHandler implements ActionListener
{
public TextFieldHandler()
{
}
public void actionPerformed(ActionEvent e)
{
****String input = blessYou.getText(); ****
if(input.equalsIgnoreCase("bless you"))
{
nosePressed = false;
rp.repaint();
}
}
} // end class TextFieldHandler
}
}
Я поместил 4 звездочки в строку, которая вызывает ошибки на основе компилятора. Строка находится в классе TextFieldHandler (нижняя часть класса code-last) и в методе actionPerformed. Основная ошибка Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SneezePanels$PanelHolder$TextFieldHandler.actionPerformed(SneezePanels.java:211)
(строка 211 - это строка, на которой я поставил 4 звездочки, она находится в классе TextFieldHandler). Там также есть куча других ошибок, относящихся к классам JPanel и JFrame.
Что я хочу сделать, так это взять введенный текст из TextField, который называется «blessYou», и затем проверить, равна ли введенная строка значению «Bless you», а затем, если это так, сбросить логическую переменную nosePressed ложно, а затем перекрасить. Вся помощь приветствуется. Пожалуйста, спросите меня, если у вас есть какие-либо вопросы о моем коде.