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

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.

Related

Find swing component using ComponentFinder

I have a code (swing):
javax.swing.JButton loginbutton = new javax.swing.JButton("Login");
loginbutton.setName("LoginButton126");
and test for it:
ComponentFinder finder = BasicComponentFinder.finderWithCurrentAwtHierarchy();
javax.swing.JButton loginbutton = (javax.swing.JButton) finder.findByName("LoginButton126");
but unfortunatelly I have:
Exception in thread "main" java.lang.NoClassDefFoundError: org/fest/util/Strings
What should I change ?
Best regards
I think this should work fine
By creating a new ComponentFinder that only has access to the GUI components created after it. In the following example, finder has access to MainFrame but not to LoginFrame.
// new LoginFrame();
ComponentFinder finder = BasicComponentFinder.finderWithNewAwtHierarchy();
finder.findByName("login", true); // will fail finding component of login frame
// new MainFrame();
finder.findByName("pw", true); // will work finding label of main frame
The easiest solution is to make all of the component variables be class variables so that you can access them anywhere. However, not everyone wants to do that, and some (like myself) are using GUI Editors that don't generate the components as class variables.
My solution is simple, I'd like to think, and doesn't really violate any programming standards, as far as I know (referencing what fortran was getting at). It allows for an easy and straightforward way to access components by name.
Create a Map class variable. You'll need to import HashMap at the very least. I named mine componentMap for simplicity.
private HashMap componentMap;
Add all of your components to the frame as normal.
initialize() {
//add your components and be sure
//to name them.
...
//after adding all the components,
//call this method we're about to create.
createComponentMap();
}
Define the following two methods in your class. You'll need to import
Component if you haven't already:
private void createComponentMap() {
componentMap = new HashMap<String,Component>();
Component[] components = yourForm.getContentPane().getComponents();
for (int i=0; i < components.length; i++) {
componentMap.put(components[i].getName(), components[i]);
}
}
public Component getComponentByName(String name) {
if (componentMap.containsKey(name)) {
return (Component) componentMap.get(name);
}
else return null;
}
Now you've got a HashMap that maps all the currently existing components in your frame/content pane/panel/etc to their respective names.
To now access these components, it is as simple as a call to getComponentByName(String name). If a component with that name exists, it will return that component. If not, it returns null. It is your responsibility to cast the component to the proper type. I suggest using instanceof to be sure.
If you plan on adding, removing, or renaming components at any point during runtime, I would consider adding methods that modify the HashMap according to your changes.

JComboBox get item

I have a quick question. I don't get it...
I've got a JFrame where I add a JComboBox:
JComboBox<String> Team_ComboBox = new JComboBox<>();
Team_ComboBox_Handler ComboBox_Listener = new Team_ComboBox_Handler();
Team_ComboBox.addActionListener(ComboBox_Listener);
Team_ComboBox.addItem("Test 1");
Team_ComboBox.addItem("Test 2");
On this Frame I have a button which opens another JFrame.
Play = new JButton();
Play.setText("Play");
Play.setPreferredSize(dimension);
Play.addActionListener(menuhandler);
private class main_menuhandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Play){
teams Team = new teams();
Team.teams();
disposeMainMenue();
}
if(e.getSource()==Close) {
System.exit(DO_NOTHING_ON_CLOSE);
}
}
}
Anyway, I would like to transfer the Selected value of the Combobox to a method of the other class. I know how I can get the itemvalue of the combobox in the method itself (with getselecteditem) But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method.... I created another ActionListener (comboBox_Listener) but I haven't put any code into it...
Any idea? Thanks a lot in advance
Several issues appear to me:
Your main question:
But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method
Your likely best solution is to change your code and variable declaration placement so that you can access the JComboBox fromt he actionPerformed method. If you're declaring the combobox from within a method or constructor, change this so that it is a proper instance field of the class.
Other problems:
You should not be creating multiple JFrames. If you need a dependent window, then one should be a JDialog. If not, then consider swapping views with a CardLayout.
Learn and follow Java naming conventnions so others can better understand your code. Class names begin with capital letters and methods and variable names don't for instance.
I am not sure why you're doing this: System.exit(DO_NOTHING_ON_CLOSE);. Why pass that constant into the exit method?
Use a constructor for your action listener class:
private class main_menuhandler implements ActionListener {
private JComboBox<String> Team_ComboBox;
public main_menuhandler(JComboBox<String> Team_ComboBox){
this.Team_ComboBox = Team_ComboBox;
}
}
Now you can create the class main_menuhandlervia the constructor and add the combobox to it.
In your Overriden action you have access to it.
Try playing around with this as your code snippet isn't broad enough to actually provide proper code. But this should answer your question

Using Enabled Property on a JButton in netbeans

I am trying to setup a button similar to the save button with the default CRUD database template (where the button only becomes active if a variable is true). I have looked at the code for the save button and worked out that i need:
A variable to link it with (saveNeeded in their case)
An action to run
I have recreated both of these on another button but it never seams to get enabled. I have print statements on 2 other buttons i am using to set the variable i have my button linked to to true and false so i can see the value is changing.
Is there some crucial step i am missing? this seems like it should be fairly straight forward.
One other thing, if i manualy change the variable to true in my constructor to true and run the application it enables the button and false disables it so that part is working, just not the change.
Any help would be appreciated as i have spent the last few hours trying and can not figure it out
Thanks
The variable or "property" needs to be watched somehow, perhaps by using a PropertyChangeSupport object and allowing other objects to add a PropertyChangeListener to it, making it a "bound property". There's a special version of this for Swing applications that takes care with the Swing event thread, SwingPropertyChangeSupport, and you may wish to use it.
Edit
You asked
Thanks for the reply, i assume that would be what firePropertyChange("saveNeeded", !saveNeeded, saveNeeded); is doing but waht is this doing? does this just notify the program or do i need to catch an handle this somewhere. This is based off the pre generated code so im not sure if it added something in the background.
The class that holds the watched variable would need a private SwingPropertyChangeSupport field. You would give it a public addPropertyChangeListener method where you'd allow other classes to listen to its bound properties, something like this (if the property were a String):
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.SwingPropertyChangeSupport;
public class Foo {
public static final String MY_BOUND_PROPERTY = "My Bound Property";
private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
this);
private String myBoundProperty;
public void addPropertyChangeListener(PropertyChangeListener listener) {
spcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
spcSupport.removePropertyChangeListener(listener);
}
public String getMyBoundProperty() {
return myBoundProperty;
}
public void setMyBoundProperty(String myBoundProperty) {
Object oldValue = this.myBoundProperty;
Object newValue = myBoundProperty;
this.myBoundProperty = myBoundProperty;
PropertyChangeEvent pcEvent = new PropertyChangeEvent(this,
MY_BOUND_PROPERTY, oldValue, newValue);
spcSupport.firePropertyChange(pcEvent);
}
}
Then any class that would like to listen for changes would simply add a PropertyChangeListener to an object of this class and respond to changes as it saw fit.

I can read but Can't edit Main class contents

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.

Regarding Multiple Tab-Class

I've problem regarding GUI with one Menu and one Order Class.
I've created a variable to store how many items have been selected in the Menu Class.
private int totalSelected;
The var totalSelected is live updated. It can be changed anytime depending on actionPerformed() function.(Exp: totalSelected will add up all the selected items)
In the Order Class, how can I access to the live update variable totalSelected in order to retrieve the live update value? When I invoke getTotalSelected() function inside the Menu Class, I will only obtain a 0 value.
Thanks for your help ^^!
Please allow me to specify my question clearer.
public class MenuTab extends JPanel
{
private JLabel display;
private int totalSelected;
public MenuTab()
{
....
}
}
public getTotalSelected(){
return totalSelected;
}
private class SelectedListener implements ActionListener
{
public void actionPerformed()
{
.......
//Assume that totalSelected has been updated!
display = new JLabel("Total: " + totalSelected);
// OK to display totalSelected live value here.
}
}
// A new class is the confirmation of order
public class OrderConfirmedTab extends JPanel{
private JLabel displayTotal;
private MenuTab order = new MenuTab();
public OrderConfirmedTab()
{
......
int totalSelected = order.getTotalSelected();
displayTotal = new JLabel("Total: " + totalSelected);
// Problem to display totalSelected live value here.
// Will obtain 0;
// How can I obtain the live updated value from class MenuTab? Thanks!
}
}
If I read your code right, you need to make your variable be private static int totalSelected; You need to make it static so that it stays the same for all instances of the class.
I looks like your not updating the private int totalSelected; variable when a user makes a selection, so it is always 0.
Ya! I just realized that my JLabel
will not update the value
automatically. So how can I fix it?
Thanks! – Christine
If I understand you correctly you have two GUIs where changes in one (the MenuTab) will update the other (OrderConfirmedTab) in real time?
If so, you will need to increase the coupling between the two objects. If MenuTab has a reference back to OrderConfirmedTab then it can call methods to update the value as it changes.
For example, pass OrderConfirmedTab into MenuTabs constructor
MenuTab mt = new MenuTab(this); // from within OrderConfirmTabs costructor
Then when MenuTab has an actionPerformed event it can call back to OrderConfirmTab
orderConfirmTab.setTotalSelected(totalSelected); // you have to create this method in OrderConfirmTab
I hope this helps a little
You can use PropertyChangeListener and PropertyChangeSupport mechanisms to dispatch an event when the value is updated and to be notified when the variable has changed. Your JLabel is not going to update on its own; even if you were to use an object other than a primitive (note that primitives are merely values, while objects are actually implicit pointers); you will need to update your JLabel when the variable changes, since the JLabel simply stores a string, not a reference to the variables from which the string was constructed.
This is the concept of model-view-controller; your variable should be in some sort of class or classes that represent the model (the information) and which allow changes to be observed via property change events. Your view classes should simply provide display logic and no business or application-specific logic. It is the controller in which your application logic should reside; your controller should register for events on the model, and it should update the view whenever the model has changed, and it should likewise update the model when the view dispatches events that should result in the model being changed.

Categories