Java: Add Place Holder on JTextField - java

Is there a way or method in which we can add placeholder in j text field. I want to add placeholder "Enter Your Number" in field but how can I do this. I check all methods but didn't working.
Code:
public class Loop extends JFrame{
private JTextField t1;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main:
public class Main {
public static void main(String[] args) {
L object = new L();
}
}

Check out Text Prompt for a flexible solution.
You can control when prompt is displayed (always, focus gained or focus lost). You can also customize the style of the text.

Here is an example of which you can you inspire
package TinyOS;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.Document;
#SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {
public static void main(final String[] args) {
final PlaceholderTextField tf = new PlaceholderTextField ("");
tf.setColumns(20);
tf.setPlaceholder("Here is a placeHolder!");
final Font f = tf.getFont();
tf.setFont(new Font(f.getName(), f.getStyle(), 30));
JOptionPane.showMessageDialog(null, tf);
}
private String placeholder;
public PlaceholderTextField () {
}
public PlaceholderTextField (
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}
public PlaceholderTextField (final int pColumns) {
super(pColumns);
}
}
I hope that can help you

This code should work, it listen on first click and removes the text
public class Loop extends JFrame{
private JTextField t1;
private boolean clicked = false;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setText("Enter Your Number");
t1.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
if(!clicked){
clicked=true;
t1.setText("");
}
}
}
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Maybe better solution exists
Note - not tested
EDIT (how the boolean clicked works)
when you call method mousePressed(MouseEvent) at the first time, the clicked variable is false, by declaration:
private boolean clicked = false;
So the if body is executed (because !clicked = !false = true)
in the if body, the clicked variable is set to true, so if condition will be then false: (because !clicked = !true = false)
This solves the problem of running code just once.

Related

Java doubts about ActionEvent

this is my first question on this website.
I have this problem, in this class I have two buttons with two different functions, one to exit and another to put the first and last name in a text field.
I can't get the second ActionEvent to work, please help me, thanks.
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
Remove public void actionPerformed1(ActionEvent e) method and add the body of that method in the else branch in the body of public void actionPerformed(ActionEvent e).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
When you provide an ActionListener object to a buttons button.addActionListener(listener)
You have several ways to accomplish this.
button.addActionListener(this);
Is only one way. This way says the the class implements ActionListener.
In effect it implements the
public void actionPerformed(ActionEvent e)
method.
Your
public void actionPerformed1(ActionEvent e)
can't be used by the button at all.
Fortunately there are many other ways to describe the code that should be executed when an action event is produced.
An inner class, static or not. Other class/object.
A lambda expression.
You can find how to express a lambda here.

Java ActionListener in another class - accessing objects from main class

i am writing a simple BMI calculator program. The application includes ActionListener, which handles button click, check if textfields are filled in and executes calculations.
For now, the ActionListener method is as a subclass of a main class. And it looks like this:
BMICalc.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BMICalc extends JFrame {
private JMenuBar menuBar1;
private JMenu jMenu1;
private JMenuItem jMenuItem1, jMenuItem2;
private JButton jButton1;
private JPanel mainPanel, jPanel1;
private JLabel jLabel1, jLabel2;
private JTextField jTextField1, jTextField2;
private BMICalc() {
super("BMI Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(250, 300));
setLocationRelativeTo(null);
setLayout(new BorderLayout(10, 10));
mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(mainPanel);
jPanel1 = new JPanel(new GridLayout(6,2));
mainPanel.add(jPanel1, BorderLayout.CENTER);
menuBar1 = new JMenuBar();
jMenu1 = new JMenu("Help");
menuBar1.add(jMenu1);
jMenuItem1 = new JMenuItem("The purpose");
jMenu1.add(jMenuItem1);
jMenuItem2 = new JMenuItem("About");
jMenu1.add(jMenuItem2);
setJMenuBar(menuBar1);
jLabel1 = new JLabel("Enter weight in [kg]:");
jPanel1.add(jLabel1);
jTextField1 = new JTextField("");
jPanel1.add(jTextField1);
jLabel2 = new JLabel("Enter height in [cm]:");
jPanel1.add(jLabel2);
jTextField2 = new JTextField("");
jPanel1.add(jTextField2);
jButton1 = new JButton("Calculate");
mainPanel.add(jButton1, BorderLayout.SOUTH);
Handler handler = new Handler();
jButton1.addActionListener(handler);
jMenuItem1.addActionListener(handler);
jMenuItem2.addActionListener(handler);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BMICalc bmicalc = new BMICalc();
bmicalc.setVisible(true);
}
});
}
private class Handler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton1) {
if (jTextField1.getText().equals("") || jTextField2.getText().equals("")) {
JOptionPane.showMessageDialog(null, "All fields must be filled in!", "Error", JOptionPane.INFORMATION_MESSAGE);
}
else {
Calculations calcs = new Calculations();
calcs.calculateBMI(jTextField1.getText(), jTextField2.getText());
JOptionPane.showMessageDialog(null, "Your BMI: " +calcs.returnBMI());
}
}
else if (event.getSource() == jMenuItem1) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
else if (event.getSource() == jMenuItem2) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
Calculations.java
public class Calculations {
private double BMI;
private int weight, height;
public void calculateBMI(String sWeight, String sHeight) {
weight = Integer.parseInt(sWeight);
height = Integer.parseInt(sHeight);
BMI = weight/(height*height*0.0001);
}
public String returnBMI() {
return String.format("%.2f", BMI);
}
}
It works just fine, but I would like to make the code 'clenaer' and make the Handler a class, not a subclass, in another file. I've created a Handler.java and moved the whole Handler subclass, but the class doesn't see the jTextFields and jButton, as they are private (and as far as I'm concerned, they should be).
How can I separate ActionListener class, access these jObjects in it and still be fair with privacy stuff?
Thank you very much for answers.
You can pass the objects you need to the Handler class using the constructor:
public class Handler {
private JButton button;
private JTextField textField;
public Handler(JButton button, JTextField textField) {
this.button = button;
this.textField = textField;
}
}
And when you instantiate the class you just pass in the two variables you want:
Handler handler = new Handler(jButton1, jTextField1);
Explanation:
your Handler class is inner class of of BMICalc. When a nested class is not static (see also difference between static and non-static nested classes) it means that objects of those class exist within an object of the parent class. That's why your Handler class see private fields.
This is no problem for us when the class is static. You just have to pass in those variables to the Handler somehow (constructor or setter fields) and then you can reuse your class for other button-text field combinations.
Edit: Yet another way:
If your handler is to be used here, and only here, and nowhere else in the code, you could instantiate anonymous Handler and assign it to the field (no need to reuse somewhere else). So, in example:
jMenuItem1.addActionListener(new Handler() {
#Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
});
jMenuItem2.addActionListener(new Handler() {
#Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
});
Now you don't have to create one huge Handler with a lot of fields and ifs...
Note that the class Handler that you show is not a subclass of Main. To be a subclass means it inherits. What you have is an inner class.
You need to pass the references to the handler so it can refer to them. For example:
public class Handler implements ActionListener {
private final JTextField jTextField1;
private final JButton jButton1;
public Handler(final JTextField textField, final JButton button)
{
this.jTextField1 = textField;
this.jButton1 = button;
}
}
And create it like this:
Handler handler = new Handler(jTextField1, jButton1);
If you want to protect those JTextField and JMenuItem from the others classes while having the handler in another classe, then you need to add some methods to the BMICalc class:
public boolean isButton1(ActionEvent event) {
return event.getSource() == jButton1;
}
public boolean isJMenuItem1(ActionEvent event) {
return event.getSource() == jMenuItem1;
}
public boolean isJMenuItem2(ActionEvent event) {
return event.getSource() == jMenuItem2;
}
public String getJButton1Text() {
return this.jButton1.getText();
}
public String getJTextField1Text() {
return jTextField1.getText();
}
public String getJTextField2Text() {
return jTextField2.getText();
}
Then you need to have the following Handler class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class Handler implements ActionListener {
private final BMICalc calc;
public Handler(BMICalc calc) {
this.calc = calc;
}
public void actionPerformed(ActionEvent event) {
if (calc.isButton1(event)) {
if (calc.getJTextField1Text().equals("") || calc.getJTextField2Text().equals("")) {
JOptionPane.showMessageDialog(null, "All fields must be filled in!", "Error", JOptionPane.INFORMATION_MESSAGE);
}
else {
Calculations calcs = new Calculations();
calcs.calculateBMI(calc.getJTextField1Text(), calc.getJTextField2Text());
JOptionPane.showMessageDialog(null, "Your BMI: " +calcs.returnBMI());
}
}
else if (calc.isJMenuItem1(event)) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
else if (calc.isJMenuItem2(event)) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
}
}
And change on line in the BMICalc :
Handler handler = new Handler(this);
But as the handler is supposed to handle only button and input of this view (and BMICalc class), it would make more sense (for me) to keep this Handler class private and inside the BMICalc class).
Hope this helps !

How to make a Gui actually prompt for the dialog boxes?

So I was trying to understand using a Gui in Java and did so by making a little guess the number game. It compiles correctly, however when I run the program it just shows the frame with "Congratulations you win!" at the top. My main question is why the dialog boxes aren't popping up at all and what I should do to fix that. On a related note, when I had the code as JOptionPane.showInputDialog(this,"Play again? Y/N") I got the error message "non-static variable this cannot be referenced from a static context." My secondary, and much less important question, is how to make the message be in the center of the box vertically as well as horizontally.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class RandomNumberGame{
public static JLabel higherThan;
public static JPanel tooHigh;
public static JLabel lowerThan;
public static JPanel tooLow;
public static JPanel exactlyCorrect;
public static JLabel correctAnswer;
public static JFrame guiFrame;
public static void main(String[] args){
RandomFun();
}
public static void RandomFun()
{
Scanner input=new Scanner(System.in);
guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Fun Games!");
guiFrame.setSize(500,500);
guiFrame.setLocationRelativeTo(null);
guiFrame.setVisible(true);
final JPanel tooHigh = new JPanel();
higherThan = new JLabel("Too High!");
final JPanel tooLow = new JPanel();
lowerThan = new JLabel("Too Low!");
final JPanel exactlyCorrect = new JPanel();
correctAnswer = new JLabel("Congratulations, you won!");
tooHigh.add(higherThan);
tooLow.add(lowerThan);
exactlyCorrect.add(correctAnswer);
guiFrame.add(tooHigh, BorderLayout.CENTER);
guiFrame.add(tooLow, BorderLayout.CENTER);
guiFrame.add(exactlyCorrect, BorderLayout.CENTER);
}
public static void GuessNumber(){
String again;
String lastGuess = "0";
boolean moreGame=true;
int lastGuessInt = Integer.parseInt(lastGuess.toString());
int winner = (int) (Math.random()*999+1);
while(moreGame){
lastGuess = JOptionPane.showInputDialog("Guess a Number");
if(winner < lastGuessInt){
tooHigh.setVisible(true);
tooLow.setVisible(false);
exactlyCorrect.setVisible(false);
}
else if(winner > lastGuessInt){
tooHigh.setVisible(false);
tooLow.setVisible(true);
exactlyCorrect.setVisible(false);
}
else{
tooHigh.setVisible(false);
tooLow.setVisible(false);
exactlyCorrect.setVisible(true);
moreGame=false;
}
}
again = JOptionPane.showInputDialog("Play again? Y/N");
switch(again){
case "y": case "Y":
GuessNumber();
break;
case "n": case "N":
System.exit(0);
break;
}
}
}
Why the "mis-behavior":
Your main method calls RandomFun()
And RandomFun() then creates a JFrame and displays.
It adds 3 JPanels all in the BorderLayout.CENTER position!
Thus only the last JPanel will show because it will cover all the previously added JPanels as per BorderLayout's documented behavior.
Thus your code is behaving exactly as you'd expect it to.
Other issues include a gross over-use of the static modifier, calling setVisible(true) on the JFrame before adding all components, setting the size of the JFrame, creating a method, GuessNumber() that is never called by viable running code, code not adhering to Java naming conventinons (methods and fields should begin with a lower-case letter, classes with an upper-case letter),...
If I were in your shoes, I'd put the GUI coding to the side as I'd first want to concentrate on learning Java basics, including avoiding all static methods and fields and instead creating true OOPs-compliant classes, since this understanding is critical prior to delving into GUI coding. Just a few weeks of study should be enough to get you strong enough to then try some Swing coding.
My attempt to create a guessing game program:
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.text.JTextComponent;
#SuppressWarnings("serial")
public class RandomNumberGame2 extends JPanel {
private static final int LOW = 0;
private static final int HIGH = 100;
public static final String START_GAME = "Please guess the random number between "
+ LOW + " and " + HIGH;
public static final String TO_HIGH = "Your guess is too high. Please try again";
public static final String TO_LOW = "Your guess is too low. Please try again";
public static final String CONGRATS_YOU_WIN = "Congratulations, you win!!!";
private Random random = new Random();
private int randomNumber; // holds the randomly selected number
private JTextField inputField = new JTextField(5); // where user enters guess
private JButton submitButton = new JButton(new SubmitAction("Submit", KeyEvent.VK_S));
private JButton resetButton = new JButton(new ResetAction("Reset", KeyEvent.VK_R));
private JLabel statusLabel = new JLabel(START_GAME, SwingConstants.CENTER);
public RandomNumberGame2() {
// so field will select all when gains focus
inputField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
// so input field will submit number if enter is pressed
inputField.addActionListener(submitButton.getAction());
JPanel centerPanel = new JPanel(); // uses flow layout by default
centerPanel.add(new JLabel("Enter number here:"));
centerPanel.add(inputField);
centerPanel.add(submitButton);
centerPanel.add(resetButton);
setLayout(new BorderLayout());
add(statusLabel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
resetGame();
}
public void resetGame() {
randomNumber = random.nextInt(HIGH - LOW) + LOW;
inputField.setText("");
statusLabel.setText(START_GAME);
inputField.requestFocusInWindow();
inputField.selectAll();
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
try {
int input = Integer.parseInt(inputField.getText().trim());
if (input > randomNumber) {
statusLabel.setText(TO_HIGH);
} else if (input < randomNumber) {
statusLabel.setText(TO_LOW);
} else {
statusLabel.setText(CONGRATS_YOU_WIN);
}
inputField.requestFocusInWindow();
inputField.selectAll();
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(RandomNumberGame2.this,
"Please enter only integer data", "Non-numeric Data Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
}
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
resetGame();
}
}
private static void createAndShowGui() {
RandomNumberGame2 mainPanel = new RandomNumberGame2();
JFrame frame = new JFrame("Fun Games 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java JTextField information access from another class

I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects

Java: actionPerformed method not firing when button clicked

I'm creating a gui application that requires some simple input, however, when I click the button in the JFrame the actionPerformed method I'm using is not fired/firing (nothing happens). I can't seem to figure out what I've missed (new to java if that helps). thanks for any help/advice.
Here is all the code:
//gui class
public class guiUser extends JFrame implements ActionListener {
private JButton buttonClose_;
private final int frameWidth = 288;
private final int frameHeight = 263;
private final int closeX = 188;
private final int closeY = 195;
private final int closeWidth = 75;
private final int closeHeight = 25;
public guiUser() {
setTitle("Create a User");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setSize(frameWidth, frameHeight);
setResizable(false);
buttonClose_ = new JButton("Exit");
buttonClose_.setLayout(null);
buttonClose_.setSize(closeWidth, closeHeight);
buttonClose_.setBounds(closeX, closeY, closeWidth, closeHeight);
buttonClose_.setLocation(closeX, closeY);
add(buttonClose_);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonClose_) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you wish to exit user creation?");
if(result == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
}
//tests the gui
public class test {
public static void main(String args[]) {
guiUser gUser_ = new guiUser();
gUser_.setVisible(true);
}
}
You need to add an action listener to your button component like this.
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
You must add an "addActionListener to your button
You could also use #182Much's method as was discussed here: java detect clicked buttons
Hope it is helpful if there are still concerns.

Categories