I am not understanding why I am getting a runtime error when I try to .setText() to a JTextArea Object in my program. In my main GUI class I have set up a event that creates a pop up JFrame object, this JFrame has a button in it which is set up too do a JTextArea.setText(); to a JTextArea in my main GUI class called MainOut.
public class GUI extends JFrame implements ActionListener {
JTextArea MainOut = new JTextArea(20,50);
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ExitVar){
System.exit(0);
}
else if (e.getSource() == ServerLoginVar) { //This is my event that creates a
//new JFrame popup
new ServerLoginGUI(this);
}
//-------------------------------------------------------------------
public class ServerLoginGUI extends JFrame implements ActionListener {
JTextField ServerIP = new JTextField(15);
JPasswordField ServerPassword = new JPasswordField(15);
JPanel ServerLoginPanel = new JPanel();
JButton LoginButton = new JButton("Login");
JTextArea Area;
JLabel ServerIPLabel = new JLabel("Server Address:");
JLabel ServerPasswordLabel = new JLabel("Password :");
GUI GUi;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == LoginButton){
if (ServerIP.getText().isEmpty() || ServerPassword.getText().isEmpty()){
} //do nothing
else {
new ServerAccess(this);
// this is the .setText() that will generate a error
GUi.SiteNameField.setText("Test from the ServerLogin event!");
dispose();}
}
}
}
okay here is you problem. You have created the object of GUI in the ServerLoginGUI class. But you are not initializing your GUi object with the reference of calling class. Here is what you need to do to fix this. To your ServerLoginGUI class add the following constructor:
public ServerLoginGUI(GUI gui)
{
this.GUi = gui;
}
Now your code should work fine and not give a run time error. Which I am assuming is a nullpointer error though you have not specified.
PS: Please get the Java conventions right. Variables start with letter in lower case. :)
Related
I have a class called Windows. The class extends JFrame and adds GUI components to the JFrame container. One of those components is a JTextfield. I am trying to set the text in the JTextfield through the actionPerformed() when generator JButton is clicked. The actionPerformed() is a class called EvenHandler. This is the eventHandler:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class EventHandler implements ActionListener {
int x = 0;
PassWordGenerator password;
Window Window; // It works only when static Window Window.
public void start() {
Window = new Window();
}
#Override
public void actionPerformed(ActionEvent e) {
password = new PassWordGenerator(3,3,3,3);
Window.setGeneratedPswd(password.getPswd());
x += 1;
System.out.println(x);
}
public static void main(String[] args) {
EventHandler x = new EventHandler();
x.start();
}
}
the window class if you want to know how the GUI looks like. The button is the one calling actionePerfome().
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
Label passwordLength;
Label labelGnPswd;
JTextField psdLength;
JCheckBox upperCase_letters;
JCheckBox lowerCase_letters;
JCheckBox numbers;
JCheckBox symbols;
JTextField generatedPswd;
EventHandler event = new EventHandler();
JButton generetor;
public Window() {
setLayout(new FlowLayout());
setTitle("PasswordGenerator");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
//Password Length
passwordLength = new Label("Password Length");
add(passwordLength);
//Input text
psdLength = new JTextField("0", 5);
add(psdLength);
//Create checkBoxes
createcheckbxs();
//Label Generated psw
labelGnPswd = new Label("Generated pswd");
add(labelGnPswd);
//Generated Password;
generatedPswd = new JTextField("****", 5);
generatedPswd.setEditable(false);
add(generatedPswd);
//Button
generetor = new JButton("Generate pswd!");
generetor.addActionListener(event);
add(generetor);
setSize(200, 400);
setVisible(true);
}
public String getpsdLength() {
return psdLength.getText();
}
public void setGeneratedPswd(String pswd) {
generatedPswd.setText(pswd);
}
private void createcheckbxs() {
upperCase_letters = new JCheckBox("Include uppercase");
add(upperCase_letters);
lowerCase_letters = new JCheckBox("Include lowercase");
add(lowerCase_letters);
numbers = new JCheckBox("Include numbers ");
add(numbers);
symbols = new JCheckBox("Include symbols ");
add(symbols);
}
}
My question is that When I clicked on the generator JButton I get an error message along the line, "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException..." I debugged the actionPerformed() and I found out that the Window Window is null when actionPefromed() is called after clicking genetor Jbutton. Why is Window null? Int x is working fine and it is not null. Isn't var x and window the same varaible scope. The only way I could keep the value of Window not null was to make Window a static variable.I hope my problem is a little more clear. Thanks in advance
Your problem seems in this line in Window.java:
generetor.addActionListener(event);
Variable event is declared in Window.java:
EventHandler event = new EventHandler();
The problem is that on event start() is not called so its instance variable Window Window remains null. The EventHandler you instantiate in main() is not used. What you might do is delete your start method and put its contents in the constructor.
I am writing a Login GUI and want the cancel button to close the entire program when clicked. I'm a freshman computer science major and still semi-new to java and programming in general. Here is my code:
Main Class:
public class loginGui
{
public static void main(String[] args)
{
lGui gui = new lGui();
lGui.gui();
}
}
GUI class:
public class lGui
{
public static void gui()
{
JFrame frame;
JTextField field;
JLabel l;
JPasswordField p;
JButton login, cancel;
JCheckBox check;
frame = new JFrame("Login");
frame.setSize(300, 150);
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setLocation(300, 200);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
l = new JLabel("Username: ");
l.setLocation(15, 14);
l.setSize(l.getPreferredSize());
frame.add(l);
field = new JTextField("Username");
field.setColumns(15);
field.setSize(field.getPreferredSize());
field.setBackground(Color.DARK_GRAY);
field.setForeground(Color.LIGHT_GRAY);
field.setLocation(90, 10);
field.setToolTipText("Enter User Name");
frame.add(field);
l = new JLabel("Password: ");
l.setLocation(15, 54);
l.setSize(l.getPreferredSize());
frame.add(l);
p = new JPasswordField("Password");
p.setColumns(15);
p.setSize(p.getPreferredSize());
p.setBackground(Color.DARK_GRAY);
p.setForeground(Color.LIGHT_GRAY);
p.setLocation(90, 50);
p.setToolTipText("Enter Password");
frame.add(p);
login = new JButton("Login");
login.setSize(login.getPreferredSize());
login.setLocation(195, 78);
login.setToolTipText("Login");
frame.add(login);
login.addActionListener(new loginAction());
cancel = new JButton("Cancel");
cancel.setSize(cancel.getPreferredSize());
cancel.setLocation(95, 78);
cancel.setToolTipText("Cancel");
frame.add(cancel);
cancel.addActionListener(new cancelAction());
check = new JCheckBox("Remember me?");
check.setSize(check.getPreferredSize());
check.setLocation(120, 100);
check.setToolTipText("Remember your username for next time");
frame.add(check);
frame.setVisible(true);
}
static class cancelAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
}
static class loginAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
}
I keep getting a "cannot find symbol" error here in the cancel button ActionListener:
frame.dispose();
frame only has context from within your static method gui. Start by getting rid of the static declaration and make frame an instance field of the class
public class lGui
{
private JFrame frame;
private JTextField field;
private JLabel l;
private JPasswordField p;
private JButton login, cancel;
private JCheckBox check;
public void gui()
{
//...
You also won't need the static declarations on the inner classes...
protected class cancelAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
}
protected class loginAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
You might find it easier to make initialise the UI from within the classes constructor instead of the gui method, leaving it to show the window
You should also avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Instead, have a look at Laying Out Components Within a Container for some more ideas
The code in gui method has to be in a constructor and your JFrame object has to be defined outside of any methods, as a field of the class :)
I am writing a program which has a JFrame with a JMenu in it. Once the user clicks a menuItem, a JDialog is being called, to get a String from the user. I want to use that string in my main programm but i don't know how to return that value from the JFrame to the main programm (I managed to return the value from the JDialog to the JFrame). Any ideas?
My main::
public static void main(String[] args)
{
myFirstFrame m = new myFirstFrame();
m.setVisible(true);
String localhost = m.getLh();
System.out.println(localhost);
}
My JFrame::
public class myFirstFrame extends JFrame
{
String lh;
myDialog myD;
public myFirstFrame(JFrame mf)
{
super();
setTitle("Welcome");
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JMenuItem playg = new JMenuItem("Play game");
simetoxi.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
myD = new myDialog(myFirstFrame.this);
myD.setVisible(true);
String lh = myD.getText();
System.out.println(lh + "ASasASas");
dispose();
}
});
JMenu game = new JMenu("GAME");
game.add(playg);
JMenuBar myBar = new JMenuBar();
myBar.add(game);
setJMenuBar(myBar);
}
public String getLh()
{
return lh;
}
}
My JDialog::
public class myDialog extends JDialog
{
JTextField t1;
String sname;
public myDialog(JFrame fr)
{
super(fr, true);
setTitle("Connect");
setSize(200, 200);
setLayout(new FlowLayout());
JLabel l1 = new JLabel("Give the server name");
t1 = new JTextField(15);
add(l1);
add(t1);
JButton okb = new JButton("submit");
okb.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
sname = t1.getText();
dispose();
}
});
add(okb);
}
public String getText()
{
return sname;
}
}
The problem is that when main creates the Frame, it doesn't stop and wait for the value to become available before executing the rest of the main function.
There are many ways you could solve this problem. For example, rather than putting System.out.println(localhost) in main, you could put it in a different method. Then, in the Frame, call that method when you get the value.
If you really want to put that call in main, you will have to find some way to make main block until the value is available. For example, you could create a BlockingQueue, and try to dequeue the value from within main. In the Frame event handler, push the needed value onto the queue.
The main method will not wait for your JFrame to go through those steps, so calling a getter in your main program (even if you "correct"
String lh = myD.getText();
to
lh == myD.getText();
will not work. - Pass this information to a class/method that makes good use of it, perhaps processing it in a separate thread - depends of what you want to do with "localhost".
Here is the problem:
I want an interactive GUI that has a TextField and a JButton. Users enter their pincode in TextField, press the JButton and the value fetches from main class to use as an argument in a function.
This is my JFrame with TextField and Button code:
public class JTextFieldDemo extends JFrame {
//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
ButtonHandler handler = null;
String pin;
//Constructor
public JTextFieldDemo() {
super("Smart Token Utility");
Container container = getContentPane();
container.setLayout(new FlowLayout());
jtfText1 = new JTextField(10);
jtfUneditableText = new JTextField("Please Enter Your PIN Code", 20);
jtfUneditableText.setEditable(false);
container.add(jtfText1);
container.add(jtfUneditableText);
handler = new ButtonHandler();
JButton button = new JButton("Enter");
button.setSize(3,5);
button.addActionListener(handler);
container.add(button);
setSize(325, 100);
setLocationRelativeTo(null);
setVisible(true);
jtfText1.addActionListener(handler);
}
//Inner Class ButtonHandler
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
pin = jtfText1.getText();
}
}
and This is my main class code:
public static void main(String args[]) {
JTextFieldDemo test = new JTextFieldDemo();
String pincode = test.pin;
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyStore.load(null, pincode);
}
I have two problems:
1) When I run the main class, the Jframe appears and before I can type anything in TextField it disappears.
2) The pincode in the main class is always null even if I hardcoded it in ButtonHandler class.
As your main method get the pin code after creation of the JFrame, it will have the default value-null. So Getting the pin code(KeyStore.load(null, pincode)) method should be in ButtonHandler#actionPerformed().
But in your case you can use JOptionPane#showInputDialog(java.lang.Object, java.lang.Object) to get the input.
I'm having troubles with the .getText() command trying to retrieve data from a JTextField. I've been looking for the solution but couldn't find it. Is there anybody who can see what I'm doing wrong?
What I'm trying is to make is a bouncing ball which parameters such as elasticity, gravity and initial speed can be changed.
When trying to compile the following message appears:
ERROR in BBPanel.java (at line 88) String gravityIn = gravity_input.getText();
gravity_input cannot be resolved
Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/////////////////////////////////////////////////////////////////// BBPanel
class BBPanel extends JPanel {
BallInBox n_bb; // The bouncing ball panel
//========================================================== constructor
/** Creates a panel with the controls and bouncing ball display. */
BBPanel() {
//... Create components
n_bb = new BallInBox();
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
JButton resetButton = new JButton("Reset");
JButton gveButton = new JButton("GetData");
JLabel gravityLbl = new JLabel (" set gravity " );
JLabel velocity_yLbl = new JLabel (" set initial y-dir speed " );
JLabel elasticityLbl = new JLabel (" set elasticity [0-100%]" );
JTextField gravity_input = new JTextField(20);
JTextField velocity_y_input = new JTextField(20);
JTextField elasticity_input = new JTextField(20);
//... Add Listeners
startButton.addActionListener(new StartAction() );
stopButton.addActionListener(new StopAction() );
resetButton.addActionListener(new ResetAction() );
gveButton.addActionListener(new DataAction() );
//... Layout inner panel with three buttons horizontally
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
buttonPanel.add(resetButton);
//
JPanel variablePanel = new JPanel();
variablePanel.setLayout(new GridLayout(0,2));
variablePanel.add(gravityLbl);
variablePanel.add(gravity_input);
variablePanel.add(velocity_yLbl);
variablePanel.add(velocity_y_input);
variablePanel.add(elasticityLbl);
variablePanel.add(elasticity_input);
variablePanel.add(gveButton);
//... Layout outer panel with button panel above bouncing ball
this.setLayout(new BorderLayout());
this.add(buttonPanel , BorderLayout.NORTH);
this.add(n_bb , BorderLayout.CENTER);
this.add(variablePanel, BorderLayout.EAST);
}//end constructor
////////////////////////////////////// inner listener class StartAction
class StartAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
n_bb.setAnimation(true);
}
}
//////////////////////////////////////// inner listener class StopAction
class StopAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
n_bb.setAnimation(false);
}
}
///////////////////////////////////////// inner listener class ResetAction
class ResetAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
n_bb.resetAnimation(true);
}
}
////////////////////////////////////////// inner listener class GravityAction
class DataAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
String gravityIn = gravity_input.getText();
//System.out.println(gravityIn);
n_bb.setData(true);
}
}
}//endclass BBPanel
The variable gravity_input is only defined locally in the scope of the constructor of BBPanel. You need to make it a class member variable if you wish to make it visible to your DataAction class.
public class BBPanel extends JPanel {
private JTextField gravity_input; // to be initialized...
...
Side note:
Java uses camel-case which would make gravity_input gravityInput.
Your problem is one of scope. The gravity_input is declared inside of a constructor or method. To be visible outside of these blocks, it should be declared in the class similar to how you declare the n_bb field.
Your variable gravity_input should be declared as an instance variable (outside the constructor), for it to be later accessed.
The way you're defining it, the name (not the text field) gravity_input dies as soon as the constructor code terminates (reaches closing brace }).
pass parameters as follows into constructor of DataAction:
class DataAction implements ActionListener {
final JTextField textField;
final BallInBox bb;
public DataAction(final JTextField textField, final BallInBox bb) {
this.textField = textField;
this.bb = bb;
}
public void actionPerformed(ActionEvent e) {
String gravityIn = textField.getText();
//System.out.println(gravityIn);
bb.setData(true);
}
}
and use it like this:
gveButton.addActionListener(new DataAction(gravity_input, n_bb));
Then refactor your other actions in a similar way.
The problem is, that your class DataAction doesn't know about your gravity_input textfield.
The textfield gravity_input is only visible to the class BBPanel. To make it visible to the class DataAction, you have to pass the textfield to that class like this:
class DataAction implements ActionListener {
private JTextField gravity_input;
public DataAction(JTextField txtField) {
gravity_input = txtField;
}
public void actionPerformed(ActionEvent e) {
String gravityIn = gravity_input.getText();
//System.out.println(gravityIn);
n_bb.setData(true);
}
}
and change your BBPanel constructor to this:
BBPanel() {
//... omitted
gveButton.addActionListener(new DataAction(gravity_input));
//... omitted
}