Text of JTextArea not being retrieved? - java

I want to get the text of private access JTextArea from another class in the same package and store/save the text into a String.
public class JTextAreaDemo extends javax.swing.JFrame {
public JTextAreaDemo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class();
d.readJtxtAreaText();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTextAreaDemo().setVisible(true);
}
});
}
private javax.swing.JTextArea jTextArea1;
/**
* #return the jTextArea1
*/
public String getjTextArea1() {
return jTextArea1.getText();
}
/**
* #param jTextArea1 the jTextArea1 to set
*/
public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
this.jTextArea1 = jTextArea1;
}
Now I want to save the text of JTextArea to string in below class
public class TxtArea_Class {
JTextAreaDemo demo;
String txt;
public TxtArea_Class(){
demo = new JTextAreaDemo();
txt = new String();
}
public void readJtxtAreaText(){
txt = demo.getjTextArea1();
if(txt.isEmpty()){
System.out.println("Failed To Get TextArea Contents ");
}
else{
System.out.println("Successfully Get TextArea Contents ");
}
}
Console Output :
Failed to Get TextArea Contents

Problem is in your TextArea_Calss's constructor
try the following.
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
and in button event. do this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}
In current implementation, Every-time you create an instance of TextArea-calss a new frame get created. because in TextArea_Class constructor you are creating an new instance of demo class.
and you are trying to get value from newly created demoFrame(that might be invisible for you but exist).
I'm hoping this will solve your issue.

You have two different instances of JTextAreaDemo!! One created in main and made visible, the other created in TxtArea_Class. The first one is the one on the screen, and the second is the one you read the string from. So the text you enter into the first doesn't show in the second.

I got the contents of JTxtArea from another class by updating my code by this.
TextArea_class
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
JTxtAreaDemo
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}

Related

unable to setText in Java Frame

Hey I am creating a java project. In which I have a insert record frame, on insert frame I have a option to enter father ID and if the user did not know the father id, so I have set a button to find the father id.
when the user will click on that button, the new frame will appear and user can search for id, the result will show in a table and when user click on the particular record, the frame will dispose and should set the respective id on the previous frame.
I have written the code for it, and it is passing the value to the previous frame but it is not setting the value to the textfield that I want it to be. Where I am doing wrong? Here is the code.
FamilyInsert.java
public class FamilyInsert extends javax.swing.JFrame {
/**
* Creates new form FamilyInsert
*/
int id = DBManager.genID();
public int fid;
public FamilyInsert() {
initComponents();
txtId.setText(""+id);
txtName.requestFocus();
}
public void setFid(int fid){
txtFid.setText(""+fid);
System.out.println("setFID "+fid);
}
public void reset()
{
txtName.setText("");
txtFather.setText("");
txtFid.setText("");
txtCity.setText("");
txtState.setText("");
txtName.requestFocus();
}
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
int id = Integer.parseInt(txtId.getText());
String name = txtName.getText();
String fname = txtFather.getText();
int fid = Integer.parseInt(txtFid.getText());
String city = txtCity.getText();
String state = txtState.getText();
Family family = new Family(id,name,fname,fid, city,state);
boolean flag = false;
flag = DBManager.insertMember(family);
if(flag==true){
JOptionPane.showMessageDialog(this,"Successfully Saved");
id++;
txtId.setText(""+id);
reset();
}
else
{
JOptionPane.showMessageDialog(this,"Error Occured");
}
}
private void txtFidActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
SearchFatherFrame f = new SearchFatherFrame();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
and from the search frame:
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int id;
if(evt.getClickCount()==2){
if(jTable1.getSelectedRow()!=-1)
{
int index = jTable1.getSelectedRow();
Family s = list.get(index);
id = s.getId();
System.out.println("ID from search frame "+id);
FamilyInsert f = new FamilyInsert();
f.setFid(id);
this.dispose();
//JOptionPane.showMessageDialog(this, s.getId()+"\n"+s.getName());
}
}
Your problem is that you're creating a new FamilyInsert object within the other class, and changing its state, but this leaves the state of the original FamilyInsert object unchanged. What you need to do instead is to pass a reference of the original displayed FamilyInsert into the 2nd object, and then change its state.
Change this:
SearchFatherFrame f = new SearchFatherFrame();
to something more like:
SearchFatherFrame f = new SearchFatherFrame(this);
Pass the reference into the class and use to set a field:
public class SearchFatherFrame {
private FamilyInsert familyInsert;
public SearchFatherFrame(FamilyInsert familyInsert) {
this.familyInsert = familyInsert;
// other code....
}
}
Then use that reference passed in to change the state of the original object.
if(jTable1.getSelectedRow()!=-1) {
int index = jTable1.getSelectedRow();
Family s = list.get(index);
id = s.getId();
System.out.println("ID from search frame "+id);
// FamilyInsert f = new FamilyInsert();
// f.setFid(id);
familyInsert.setFid(id); // **** add
this.dispose();
//JOptionPane.showMessageDialog(this, s.getId()+"\n"+s.getName());
}
Also you want the 2nd window to be a JDialog not a JFrame. Please see: The Use of Multiple JFrames, Good/Bad Practice?
Could you try
public void setFid(int fid){
txtFid.setText(""+fid);
System.out.println("setFID "+fid);
yourJFrame.setVisible(true); //Reloads the frame
}

How to Show output Jlabel another Jframe

When i input Text in the JtextField of FrameIn, and then click button OK, the Text will display on the Jfield of FrameShow the last frame is what I want, cause I still don't know how to make it.
I am using NetBeans GUI builder.
package learn;
public class FrameIn extends javax.swing.JFrame {
private String Name = null;
public FrameIn() {
initComponents();
}
*
*
private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
FrameShow show = new FrameShow();
Name = Text.getText();
this.dispose();
show.setVisible(true);
}
public String getName(){
return this.Name;
}
and This my FrameShow
public class FrameShow extends javax.swing.JFrame {
/**
* Creates new form Frame1
*/
public FrameShow() {
FrameIn inName = new FrameIn();
initComponents();
Label.setText(inName.getName());
}
So if i input Text in the JtextField of FrameIn, then output will display on the Jfield of FrameShow second Jframe
Output form this code is null on the Jfield
You can pass your parametres between the two Frame,
so when you click a your button, make an action that call your frameShow, and you can pass your values, in the constructor of your frame or you can create a field in your second frame and use setter to put your value, here is the idea.
class A{
...
//action
String v = textField.getText();
B b = new B(v);
...
}
class B{
public B(String v){
this.label.setText(v);
}
}
Second idea :
class A{
...
//action
String v = textField.getText();
B b = new B();
b.setLabelValue(v);
...
}
Here is your code should be look like:
private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
Name = Text.getText();
FrameShow show = new FrameShow(Name);
this.dispose();
show.setVisible(true);
}
public FrameShow(String name) {
initComponents();
Label.setText(name);
}
Hope you get my point and you understand the idea.

Setting the text in jTextField and then retrieving that text

package test2;
public class NewJFrame extends javax.swing.JFrame {
private static void valueGen(javax.swing.JTextField jTextField1) {
String x = jTextField1.getText();
System.out.println(x);
}
public NewJFrame() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jTextField1.setText("Hello");
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
public javax.swing.JTextField getTextField() {
jTextField1.getText();
return this.jTextField1;
}
public static void main(String args[]) {
NewJFrame myFrame = new NewJFrame();
valueGen(myFrame.getTextField());
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
}
I have a program as shown above. I need to set the text "hello" in a text field when the submit button is clicked. It works. But then i need to use that text in a function called valueGen where it is printed. But the text doesn't get printed by executing the above code. What is wrong with this code?
It's unorganized. Always put class variables at the top.
Like Cool Guy said, put myFrame instead of new NewJTest()
valueGen is actually being called before you can click the button. Put it in the jTextField1ActionPerformed; that might fix it.
In netbeans out put of the System.out.println(); will be displayed in the output window as shown in the bellow picture.
If you want to display it as a message replace the following method with your valueGen() method.
private static void valueGen(javax.swing.JTextField jTextField1) {
String x = jTextField1.getText();
System.out.println(x);
JOptionPane.showMessageDialog(null, x);
}
And use myFrame.setVisible(true); to make visible your JFrame.
public void run() {
NewJFrame myFrame = new NewJFrame();
myFrame.setVisible(true);
valueGen(myFrame.getTextField());
}

Java Swing button actionEvent

sorry to bother everyone.
Overall problem: I'm trying to open a dialogue box let the user enter something then close it
Issue: - A function is not being called (i think)
- The main problem is when i use debug it works fine so Its difficult for me to track down the problem
I'm having trouble with JButtons,
it works in debug but not in normal run. this was probably because i was using an infinite loop. someone online suggested i used SwingUtilities but that didn't work (at least i don't think.
/**
*
* #author Deep_Net_Backup
*/
public class butonTest extends JFrame {
String name;
boolean hasValue;
//name things
private JLabel m_nameLabel;
private JTextField m_name;
//panel
private JPanel pane;
//button
private JButton m_submit;
//action listener for the button submit
class submitListen implements ActionListener {
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
}
}
//constructor
public butonTest(){
//normal values
name = null;
hasValue = false;
//create the defauts
m_nameLabel = new JLabel("Name:");
m_name = new JTextField(25);
pane = new JPanel();
m_submit = new JButton("Submit");
m_submit.addActionListener(new submitListen());
//
setTitle("Create Cat");
setSize(300,200);
setResizable(false);
//add components
pane.add(m_nameLabel);
pane.add(m_name);
pane.add(m_submit);
add(pane);
//last things
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//submit
private void submit()
{
System.out.println("submit");
name = m_name.getText();
hasValue = true;
}
//hasValue
public boolean hasValue()
{
return(hasValue);
}
//get the text name
public String getName()
{
return(name);
}
public void close()
{
setVisible(false);
dispose();
}
public static void main(String[] args)
{
/* Test 1
boolean run = true;
String ret = new String();
butonTest lol = new butonTest();
while(run)
{
if(lol.hasValue())
{
System.out.println("Done");
run = false;
ret = new String(lol.getName());
lol.close();
}
}
System.out.println(ret);*/
//Tset 2
/*
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
butonTest lol = new butonTest();
if(lol.hasValue())
{
System.out.println(lol.getName());
}
}
});*/
}
}
Edit:
How its not working: When i run Test the program will print test and submit then it should change the hasValue to true. this will (hopefully) allow the if statement to run to print done. This does not happen.
Edit 2:
I have just added a few more lines for further testing 2 prints and this seems to have solved the issue (but this is bad)
System.out.println("hasValue " + hasValue); -> to the hasValue() function
System.out.println("set to true"); -> submit() function
You are doing something far too complicated than is necessary. Instead of having the listener as a seperate class, you could have it as an anonymous class. That way you can get a handle on the outer class (butonTest.this), and call any method you want on it.
m_submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
butonTest.this.close();
}
});
I'm not sure what you are trying to do with the infinite loop. It would have run to completion before you show the dialog anyway.
It would help to read up a bit on how Event-Handling works in Swing :)
I am afraid your constructor butonTest() and submit() method are out of your
class (public class butonTest extends JFrame).
you need to get them inside your class:

Access static variable from another class

I have two classes in same package. i have declared a static variable in one class and want to access that variable in another class.
Here is my code in which i have declared the static variable
public class wampusGUI extends javax.swing.JFrame {
static String userCommand;
public wampusGUI() {
initComponents();
}
public void setTextArea(String text) {
displayTextArea.append(text);
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
userCommand = commandText.getText();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
wampusGUI w = new wampusGUI();
w.setVisible(true);
Game g = new Game(w);
g.play();
}
});
}
}
Here is the code in which i want to access variable
public class Game {
private wampusGUI gui;
public Game(wampusGUI w) {
world = new World();
world.start();
gui = w;
}
public void play() {
gui.setTextArea(welcome());
gui.setTextArea(describe());
for (;;) {
String s = userCommand; // here value should come should
System.out.println(userCommand);
Command c = Command.create(s);
String r = c.perform(world);
// is game over?
if (r == null) {
break;
}
System.out.println(r);
}
System.out.println("Game over");
}
}
However, i can pass the variable from first class as a argument. but the problem is that, when i will run program the value is going null first time, which i dont want. i want when i enter value in textfield then it should go to another class.
Thank you.
Looking at your code, it seems you want to show dialogs to your user with a certain text
gui.setTextArea(welcome());
gui.setTextArea(describe());
and sometimes, that dialog should capture user input which is handled afterwards.
Those setTextArea calls are not what you want to use. The user will never see the welcome message as it will immediately be replaced by the describe message.
Make sure you do not block the Event Dispatch Thread (EDT) or nothing will be shown at all. I do not know what your Command class will do, but I see an infinite loop on the Event Dispatch Thread which is never a good thing. Take a look at the Concurrency in Swing tutorial for more information
Thanks to that for loop, the user will simply not be capable to input any command as the EDT is busy handling your loop. What you need is a blocking call allowing the user to provide input (not blocking the EDT, but just blocking the execution of your code). The static methods in the JOptionPane class are perfectly suited for this (e.g. the JOptionPane#showInputDialog). These methods also have a mechanism to pass the user input back to the calling code without any static variables, which solves your problem.
I suggest that you use a listener of one sort or another to allow the Game object to listen for and respond to changes in the state of the GUI object. There are several ways to do this, but one of the most elegant and useful I've found is to use Swing's own innate PropertyChangeSupport to allow you to use PropertyChangeListeners. All Swing components will allow you to add a PropertyChangeListener to it. And so I suggest that you do this, that you have Game add one to your WampusGUI class (which should be capitalized) object like so:
public Game(WampusGUI w) {
gui = w;
gui.addPropertyChangeListener(new PropertyChangeListener() {
// ....
}
This will allow Game to listen for changes in the gui's state.
You'll then want to make the gui's userCommand String a "bound property" which means giving it a setter method that will fire the property change support notifying all listeners of change. I would do this like so:
public class WampusGUI extends JFrame {
public static final String USER_COMMAND = "user command";
// ....
private void setUserCommand(String userCommand) {
String oldValue = this.userCommand;
String newValue = userCommand;
this.userCommand = userCommand;
firePropertyChange(USER_COMMAND, oldValue, newValue);
}
Then you would only change this String's value via this setter method:
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
setUserCommand(commandText.getText());
}
The Game's property change listener would then respond like so:
gui.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
// is the property being changed the one we're interested in?
if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {
// get user command:
String userCommand = pcEvt.getNewValue().toString();
// then we can do with it what we want
play(userCommand);
}
}
});
One of the beauties of this technique is that the observed class, the GUI, doesn't have to have any knowledge about the observer class (the Game). A small runnable example of this is like so:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
public class WampusGUI extends JFrame {
public static final String USER_COMMAND = "user command";
private String userCommand;
private JTextArea displayTextArea = new JTextArea(10, 30);
private JTextField commandText = new JTextField(10);
public WampusGUI() {
initComponents();
}
private void setUserCommand(String userCommand) {
String oldValue = this.userCommand;
String newValue = userCommand;
this.userCommand = userCommand;
firePropertyChange(USER_COMMAND, oldValue, newValue);
}
private void initComponents() {
displayTextArea.setEditable(false);
displayTextArea.setFocusable(false);
JButton enterButton = new JButton("Enter Command");
enterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
enterButtonActionPerformed(evt);
}
});
JPanel commandPanel = new JPanel();
commandPanel.add(commandText);
commandPanel.add(Box.createHorizontalStrut(15));
commandPanel.add(enterButton);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(new JScrollPane(displayTextArea));
mainPanel.add(commandPanel, BorderLayout.SOUTH);
add(mainPanel);
}
public void setTextArea(String text) {
displayTextArea.append(text);
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
setUserCommand(commandText.getText());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
WampusGUI w = new WampusGUI();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.pack();
w.setLocationRelativeTo(null);
w.setVisible(true);
Game g = new Game(w);
g.play();
}
});
}
}
class Game {
private WampusGUI gui;
public Game(WampusGUI w) {
gui = w;
gui.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
// is the property being changed the one we're interested in?
if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {
// get user command:
String userCommand = pcEvt.getNewValue().toString();
// then we can do with it what we want
play(userCommand);
}
}
});
}
public void play() {
gui.setTextArea("Welcome!\n");
gui.setTextArea("Please enjoy the game!\n");
}
public void play(String userCommand) {
// here we can do what we want with the String. For instance we can display it in the gui:
gui.setTextArea("User entered: " + userCommand + "\n");
}
}
I agree with Jon Skeet that this is not a good solution...
But in case u want an dirty solution to ur problem then u can try this:
public class wampusGUI extends javax.swing.JFrame
{
private static wampusGUI myInstance;
public wampusGUI( )
{
myInstance = this;
initComponents();
}
public static void getUserCommand()
{
if(myInstance!=null)
{
return myInstance.commandText.getText();
}
else
{
return null;
}
}
......
......
}
in the other class use:
public void play()
{
.....
//String s = userCommand; // here value should come should
String s = wampusGUI.getUserCommand();
.....
}
This kind of code is there in some of our legacy projects... and I hate this.

Categories