I can read but Can't edit Main class contents - java

I'm using netbeans to program something with a user interface...
I hava a main class that named "NewJFrame.java"(A) and one more class
that named "NewClass.java"(B). Class A is extended to class B like this:
public class NewClass extends NewJFrame{
...
}
Contents of ClassA are public static like this:
public static javax.swing.JTextField TextBox1;
I also has a button in classA .So when I click the button, it will call a function
from the classB and that function needs to edit TextBox1's text...
Here is whats going on when I click the button:
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String Str1;
NewClass nc = new NewClass();
Str1=nc.call();
}
Here is the funcion in ClassB:
public String call()
{
String Str;
Str = TextBox1.getText();
TextBox1.setText(Str + "1"); //This part isn't work.
JOptionPane.showConfirmDialog(null,Str,"22222222",JOptionPane.PLAIN_MESSAGE);
return Str;
}
So I can read the text of TextBox1 and show it in a messagebox but cannot edit his text.
If I put this code in main class it works perfectly but in another class it doesn't work.
Can someone help me to reslove this problem?
(I'm using netbeans 6.9.1)
I Just Trying to use some another class to add my code because I dont want all the codes stay in same file this is not usefull... Come on someone needs to know how to do that you can't be writing all the codes in a *.java file right?

The problem you are facing has nothing to do with NetBeans IDE,
you will face the same problem with any IDE for this code.
One way of achieving this is by aggregating the NewJFrame class in the NewClass
instead of extending it:
Let me exlplain with some code:
public class NewClass {
private NewJFrame frame = null;
public NewClass(NewJFrame frame) {
this.frame = frame;
}
public String call()
{
String text;
text = frame.TextBox1.getText();
frame.TextBox1.setText(text + "1"); //This will work now.
JOptionPane.showConfirmDialog(null,text,"22222222",JOptionPane.PLAIN_MESSAGE);
return text;
}
}
Here we will receive a reference to the calling JFrame class and will use fields
defined in that class.
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String Str1;
NewClass nc = new NewClass(this); // see the parameter we are passing here
Str1=nc.call();
}
When we create an object of class NewClass we will pass the reference of the
currently calling NewJFrame object
This will work check it.
Now coming to why your code is not working. When NewClass is extending NewJFrame
and when you create a new object of NewClass class it contains a separate
copy of the NewJFrame which is different from the calling NewJFrame reference hence
the field is getting set in another JFrame and not what you wanted.
with regards
Tushar Joshi, Nagpur

AFAIK Netbeans prevents you from editing by hand GUI's and behaves diferrently depending on strange issues like the one you have... but it was months ago, I dont know if current version sucks that much yet.

I really don't understand why you are forcing yourself to use a new class for this? Even if you NEED to, I don't understand why NewClass extends NewJFrame since you are only creating an instance to call a method that has nothing to do with GUI.
I think creating NewClass isn't necessary. Writing all the code in one class isn't bad by itself. This really depends on MANY factors: how much is "all the code"? Does it make sense to separate responsibilities? Etc, etc...
So make the JTextField and JButton NOT static and NOT public, and simply do everything in there:
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String str = TextBox1.getText();
TextBox1.setText(str + "1"); //This part isn't work.
JOptionPane.showConfirmDialog(null,Str,"22222222",JOptionPane.PLAIN_MESSAGE);
}
P.S.: variable names are start in lowercase: String str, not String Str.

I Found a solution. I'm throwing the contents whereever I'll use. Here is an Example:
Main class:
private void formWindowOpened(WindowEvent evt) {
Tab1Codes tc1 = new Tab1Codes();
if(!tc1.LockAll(TabMenu1))
System.exit(1);
tc1.dispose();
}
Another class where I added some of my codes:
public boolean LockAll(javax.swing.JTabbedPane TabMenu){
try
{
TabMenu.setEnabledAt(1, false);
TabMenu.setEnabledAt(2, false);
TabMenu.setEnabledAt(3, false);
TabMenu.setEnabledAt(4, false);
}catch(Exception e)
{
JOptionPane.showConfirmDialog(null, "I can't Lock the tabs!",
"Locking tabs...",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
So, I can edit the contents in another class but it's little useless to send every content I want to read and edit.
If someone knows any short way please write here.

Related

JTextArea field not updating

I have two classes, one does something like this:
public ClassOne:
package classes;
public class ClassOne {
public javax.swing.JTextArea progressListing
progressListing = new javax.swing.JTextArea();
public void files(File file){
Class method = new Class();
method.methodInOtherClass(files);
}
public void progressUpdate (String fileOutput){
progressListing.insert(fileOutput,0);
}
}
which then goes to the other class that has the following:
Other Class:
package classes;
public class OtherClass extends ClassOne{
public void methodInOtherClass(file){
String fileOutput
fileOutput = file.getName();
ClassOne input = new ClassOne();
input.progressUpdate(fileOutput);
}
}
It is not updating the progessListing field when the program runs. Is there a better way to do this or am I missing something?
What OtherClass does is it creates pdf files that need to show up in the text area(ie the file path with the file name). ClassOne is the swing interface. Even when it's extended into the other class it doesn't modify the text field when I need it to.
Correct me if I'm wrong, but looking at the code you have posted, I think that you are trying to read a file and put the data from the file into the text area. Again, please correct me if I'm wrong. I think you should use the following code:
BufferedReader br = new BufferedReader(new FileReader("fileName.txt");
String data = br.readLine();
jTextArea1.append("\n"+data);
Please tell me if it works.
Cheers.
PS. If you post your whole code I will be able to help better.
I figured it out. I used a getter method in the other class to assign the variable and returned it to the main class. I set the String inside the loop to have an assign and add function. Works like a charm.

Want access of textfield from another .java file within a program

I have many .java files within my project. From FTall.java i want to access {text field} t1 ('main' jFrame -> jPanel2) of the FormTTS.java
I am right now getting errors due to that only, because it cannot find symbol t1.
It is private and i cant change it to public
Edit:
I am using this code already to open up FTall from the FormTTS.java:
In a button in FormTTS
FTall forma = new FTall();
JFrame frame = forma.getFrame();
forma.setVisible(true);
and this in FTall
public JFrame getFrame() {
return jFrame1;
}
Because of the way your code is structure, you need to supply some way for FormTTS.t1
In FormTTS, provide a method to exposes t1, something like getMainTextField for example...
public JTextField getMainTextField() {
return t1;
}
You're next problem is FTall is going to need a reference to an instance of FormTTS. Probably the easiest way would be to pass a reference to the constructor of FTall
private FormTTS mainForm;
public FTall(FormTTS mainForm) {
this.mainForm= mainForm;
}
This will allow you to access t1 by simply using the mainForm reference...
JTextField field = mainForm.getMainTextField();
Personally, I would prefer not to expose the text field as it gives too much access to callers, instead I'd prefer to return the text and if required provide a means to change it...
So in FormTTS, I might do something like...
public String getMainText() {
return t1.getText();
}
// Do this only if you need to have write access
public void setMainText(String text) {
t1.setText(text);
}
But that's just me...
To obtain the value, you would use a similar approach as above (to getting the text field)
String text = mainForm.getMainText();
if i am understanding your question its simple first ensure that your text field come in to scope before access and once it come in, then use a setter to set its refrence in required class then you can access it.

How to use methods from two classes in eachother in Java?

I've been looking around and I only found one answer which wasn't clear enough, to me at least.
I am building a very basic chat application with a GUI and I have separated the GUI from the connection stuff. Now I need to call one method from GUI in server class and vice versa. But I don't quite understand how to do it (even with "this"). Here's what a part of code looks like (this is a class named server_frame):
textField.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
srv.sendData(arg0.getActionCommand());
} catch (Exception e) {
e.printStackTrace();
}
textField.setText("");
}
}
);
This is a code from server_frame, srv is an object from the other class (server) which contains sendData method, and I probably didn't define it correctly so hopefully someone could make a definition of it.
On the other side class server from which object srv was made contains method using JTextArea displayArea from server_frame in this code:
private void displayMessage(final String message){
sf = new server_frame();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
sf.displayArea.append(message);
}
}
);
}
Yet again sf is an object made of server_frame and yet again probably missdefined :)
Hopefully that was clear enough, sadly I tried the searching but it just didn't give me the results I was looking for, if you need any more info I will gladly add it!
Thanks for reading,
Mr.P.
P.S. Please don't mind if I made terminology mishaps, I am still quite new to java and open to any corrections!
Some class must be building both of these objects--the GUI and the server--and it should make each aware of the other. For example, say the main class is ServerApplication. I'll use standard Java convention of starting class names with an uppercase letter for clarity.
class ServerApplication {
Server server;
ServerFrame gui;
public static void main(String []) {
server = new Server(...);
gui = new ServerFrame(server);
server.setGui(gui);
}
}
Each class should store the reference to the other as well.
class Server {
ServerFrame gui;
public void setGui(ServerFrame gui) {
this.gui = gui;
}
...
}
class ServerFrame extends JFrame {
Server server;
public ServerFrame(Server server) {
this.server = server;
}
...
}
I think you may be looking for the ClassName.this.methodName syntax. this in those actionlisteners refer to the anonymous class you created. If you used the above syntax you would be referencing the class that contains the anonymous class.
Or if you are looking for a private field in the class, you would do ClassName.this.privateField

Clearing a JTextArea from another class

I'm very new to Java and I'm setting myself the challenge on writing a Caesar shift cipher decoder. I'm basically trying to clear a JTextArea from another class. I have two classes, a GUI class called CrackerGUI and a shift class. The JtextArea is in the GUI class along with the following method:
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
The GUI class also has a clear button with the following:
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift();
classShift.btnClear();
}
Lastly i have the method in the shift class to clear the JTextArea.
public class Shift extends CrackerGUI {
public void btnClear()
{
CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
The testing text is printing out to console but the JTextArea wont clear. I'm not sure as to why :). I am sure it's a very simple mistake but it has me baffled. Any help would be appreciated.
Thank you in advance.
You're misusing inheritance to solve a problem that doesn't involve inheritance. Don't have Shift extend CrackerGUI and don't create a new CrackerGUI object inside of the btnClear() method since neither CrackerGUi is the one that's displayed. Instead have Shift hold a reference to the displayed CrackerGUI object and have it call a public method of this object.
e.g.,
public class Shift {
private CrackerGUI gui;
// pass in a reference to the displayed CrackerGUI object
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
//CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
You also should probably not be creating new Shift objects in your GUI's actionPerformed methods, but rather use only one Shift object that is a class field.
The btnClear method clears the text area of a new CrackerGUI instance. It's like if you wanted to clear a drawing on a sheet of paper by taking a new blank sheet and clearing it. The original sheet of paper will keep its drawing.
You need to pass the gui instance to your Shift:
public class Shift {
private CrackerGUI gui;
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
this.gui.setPlainText(" ");
}
}
and in the CrackerGUI class :
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift(this);
classShift.btnClear();
}
Assuming CrackerGUI is your GUI, you should have the following instead:
public class CrackerGUI {
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
public void btnClear()
{
setPlainTextBox("");
System.out.println("testing");
}
}
One last thing, never make your GUI elements public! You should ask the GUI to clear itself and leave that knowledge of clearing elements hidden inside it.
You could try using static methods, as you would end up creating a new gui, then displaying that one, in stead of the current one already displayed.
This would require the parent class to be static too, which may cause errors in some of your methods, just a heads up.
Or else, you could create your own setText method:
void setText(JTextField t, String s){
t.setText(s);
}
that may enable you to directly edit components in the current GUI.

JPanel.addComponentListener does not work when the listener is a class variable

I have a public class which has the following method and instance variable:
public void setImagePanel(JPanel value) {
imagePanel = value;
if (imagePanel != null) {
//method 1 : works
imagePanel.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent evt) {
System.out.println("Here 1");
}
});
//method 2 : does not work
panelResizeListener = new ResizeListener();
imagePanel.addComponentListener(panelResizeListener);
//method 3 : works
//ResizeListener listener = new ResizeListener();
//imagePanel.addComponentListener(listener);
//method 4 : works
//imagePanel.addComponentListener(new ResizeListener());
//method 5 : does not work -- THIS IS THE DESIRED CODE I WANT TO USE
imagePanel.addComponentListener(panelResizeListener);
}
}
public class ResizeListener extends ComponentAdapter {
#Override
public void componentResized(ComponentEvent evt) {
System.out.println("RESIZE 3");
}
}
private ResizeListener panelResizeListener = new ResizeListener();
private static JPanel imagePanel;
Each of the methods above correspond the to code immediately below until the next //method comment. What i don't understand is why i can't use the class instance variable and add that to the JPanel as a component listener.
What happens in the cases above where i say that the method does not work is that i don't get the "RESIZE 3" log messages. In all cases where i list that it works, then i get the "RESIZE 3" messages.
The outer class is public with no other modification except that it implements an interface that i created (which has no methods or variables in common with the methods and variables listed above).
If anyone can help me i would greatly appreciate it. This problem makes no sense to me, the code should be identical.
Man camickr, you were right. Man this was a weird one to solve. There was something else wrong with my code. The order of the methods calls into my class resulted in me adding the listener then another method would end up removing the listener referenced by that variable so of course i would never get events. Thanks a lot for all the help ppl.
I think your problem is that you're declaring panelResizeListener after you're using it. That normally kills just about anything.

Categories