unable to setText in Java Frame - java

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
}

Related

How to update values of a JFrame main after using a JDialog of Java Swing?

I have a main window called MainFrame which is a jForm to which I update the data depending on a timer, but the problem is that I cannot update the data in the same MainFrame after using the jdialog, since I end up creating another duplicate window, but with the data changed, one with the original timer and the other with the new timer, I know that I can close the first window with dispose() and then keep the second, but I would like to avoid changing windows so much
the code with which I create another window when pressing the jDialog button is the following
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String textoFieldTimer = jTextField1.getText();
int timeUserConfig = Integer.parseInt(textoFieldTimer);
Timer timeDefault = new Timer(timeUserConfig, null);
TokenAccess token = new TokenAccess();
token.access_code = code;
MainFrame mainFrame = new MainFrame(token);
mainFrame.setVisible(true);
mainFrame.timeDefault.stop();
mainFrame.timeDefault = timeDefault;
mainFrame.setUpdateTime(timeUserConfig);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
Is there any alternative to update the window? something like mainFrame.update(); or maybe send the value of the jTextField from the jDialog to mainFrame? since the previous code creates another MainFrame for me.
Method main setLabel and Timer.start/stop
public void setUpdateTime(int timeUserConfig) {
this.timeUserConfig = timeUserConfig;
if (timeUserConfig == 0) {
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeDefaultInt);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
} else {
timeDefault.stop();
timeDefault = new Timer(timeUserConfig, null);
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeUserConfig);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
}
}
setLabelText is a method set of label
public void setLabelText() {
String humedadStr = String.valueOf(humedad);
String temperaturaStr = String.valueOf(temperatura);
String presionStr = String.valueOf(co2);
temporalHum.setText(humedadStr);
temporalTemperatura.setText(temperaturaStr);
temporalPresion.setText(presionStr);
}
Any help would be appreciated.
Thanks for the update, and I found another solution without using an OptionPane from this question: programmatically close a JPanel which is displayed in JDialog.
I cannot replicate your codings
Start with the MainFrame, assuming you opened the JDialog by clicking on a button and wants to setText() to label lbSomething:
private void btInputActionPerformed(java.awt.event.ActionEvent evt) {
// Open new JDialog when button is clicked
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame, true);
dialog.setVisible(true);
// Get user input from JDialog
String temp = dialog.getInput();
if (temp != null) {
/*
* Perform jButton1ActionPerformed() content here
* Including timeUserConfig, timeDefault and setUpdateTime() here
* so that you don't have to access mainFrame in the JDialog.
*/
lbSomething.setText(temp);
}
}
Then about the JDialog (with simple input detection):
public class NewJDialog extends javax.swing.JDialog {
// Set the variable as class variable
private String textTOFieldTimer;
public NewJDialog(java.awt.Frame parent, boolean modal) {
// default contents
}
#SupressWarinings("unchecked")
private void initComponents() {
// default contents
}
private void btSaveAction Performed(java.awt.event.ActionEvent evt) {
// Check if input correct and whether to disable JDialog
if (tfInput.getText.length() != 0) {
input = tfInput.getText();
// Connect to the whole JDialog by getWindowAncestor()
Window window = SwingUtilities.getWindowAncestor(NewJDialog.this);
// Just setVisible(false) instead of dispose()
window.setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "Wrong Input");
}
}
public String getInput() {
return textToFieldTimer;
}
// default variables declarations
}
Hope this answer helps you well.
Would be better if you displayed the source code, but a simple solution to update values to an existing JFrame is by using setText() and getText().
For example:
String input = JOptionPane.showInputDialog(this, "Nuevo valor");
lbPresionActual.setText(input);
If you created a self-defined JDialog, it is about to transfer the input value when closing the JDialog, and that could be a different question.

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.

List of Values in Java Swing Form

How can I display an LoV in a Java Swing form as shown in Oracle Forms?
I have data concerning user identifiers and user names. And I want to display the user names in LoV, but if a user selects a name corresponding to a user, its identifier should be returned.
EDIT 1:
Here is the form code that I've used to display 'Lov'
import db.DBHelper;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class LovForm extends JDialog implements ActionListener {
private Connection conn;
private DBHelper db;
private JList list;
private DefaultListModel model;
private UserDetail userDetail;
private JButton btnOk;
public LovForm(Connection c, UserDetail u) {
this.conn = c;
this.userDetail = u;
initComponents();
}
private void initComponents() {
db = new DBHelper(this.conn);
btnOk = new JButton("Ok");
btnOk.addActionListener(this);
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
model = new DefaultListModel();
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
model.addElement(name);
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
list.setPreferredSize(new Dimension(150, 250));
JScrollPane listScroller = new JScrollPane(list);
JLabel lbl = new JLabel("Select an application user");
c.add(lbl);
c.add(listScroller);
c.add(btnOk);
this.setTitle("List of Users");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(new Dimension(200, 250));
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setModal(true);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
String selectedItem = (String) list.getSelectedValue();
userDetail.setUserName(selectedItem);
this.dispose();
}
}
}
I would add a wrapper class for the User, which contains its name and its id.
Do not forget to override the toString() method of the User (that method will be used when rendering the list).
While populating the list, create User objects, and therefore you will have access to both its name and its id.
See code bellow:
private void initComponents() {
// your code....
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
int id = rs.getInt("ID");
model.addElement(new User(name, id));
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
// your code...
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
User selectedItem = (User) list.getSelectedValue();
userDetail.setUserName(selectedItem.getName());
int id = selectedItem.getId();
this.dispose();
}
}
public class User {
private String name;
private Integer id;
public User(String name, Integer id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
#Override
public String toString() {
return name;
}
}
You could use a JComboBox.
You would create a custom Object to store both pieces of data. Then you would create a custom renderer to display whatever data you want in the combo box. Your processing code would then use the other property.
Check out Combo Box With Custom Renderer for an example of the rendering code you would use. This renderer is more complete than most rendering code you will find in the forum because it will still support selection of the item from the combo box using the keyboard.
I see you updated your question to show you are using a JList. Well the answer is still the same. You need a custom renderer for your JList. You can base your renderer off the example from the above link except you would extend the DefaultListCellRenderer.

Text of JTextArea not being retrieved?

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();
}

Change background of JLabel in runtime using reflection

I need to change background of JLabels dynamically.
I've 70 JLabels in a class. All JLabels represent some specific items. The items names are same as the variable of JLabel. The Sold Items names are saved in database. If I run a query that will return an array of the sold items. The sold items that are same as the JLabel should change the background. Rest will not change.
I've got the variables of all fields like this:
Field fld[] = BlueLine.class.getDeclaredFields();
for (int i = 0; i < fld.length; i++)
{
System.out.println("Variable Name is : " + fld[i].getName());
}
How can I cast my fld to a JLabel and change background of the JLabel when certain condition meets ? for example:
if(fld[i] == label5){
label5.setBackground.(Color.red);
} // or something like this. ?
Any outline will help.
Currently you're just looking at the fields themselves - you're interested in the values of those fields. For example:
Object value = fld[i].get(target); // Or null for static fields
if (value == label5) {
...
}
Here target is a reference to the object whose fields you want to get the values from. For static fields, just use null, as per the comment.
It's not at all clear that all of this is a good idea, however - problems which can be solved with reflection are often better solved in a different way. We don't really have enough context to advise you of specifics at the moment, but I would recommend that you at least try to think of cleaner designs.
Try it using Jcomponent.putClientProperty() and Jcomponent.getClientProperty().
Steps to follow:
First set the name of the JLabel same as its variable name
Put it as client property of JPanel where JLabel is added
Get it back using client property from JPanel using name of JLabel
Note: you can access it by using Field.getName() as defined in your question.
Sample code :
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.addContainerListener(new ContainerListener() {
#Override
public void componentRemoved(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " removed");
panel.putClientProperty(name, null);
}
}
#Override
public void componentAdded(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " added");
panel.putClientProperty(name, e.getChild());
}
}
});
MyLabels myLabels = new MyLabels();
panel.add(myLabels.getProduct1());
panel.add(myLabels.getProduct2());
panel.add(myLabels.getProduct3());
JButton btn = new JButton("Product1 and Product3 are sold");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] soldItems = new String[] { "Product1", "Product3" };
for (String soldItem : soldItems) {
Object obj = panel.getClientProperty(soldItem);
if (obj instanceof JLabel) {
((JLabel) obj).setForeground(Color.RED);
}
}
}
});
panel.add(btn);
frame.add(panel);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MyLabels.java:
class MyLabels {
private JLabel Product1;
private JLabel Product2;
private JLabel Product3;
public MyLabels() {
Product1 = new JLabel("Product1");
Product1.setName(Product1.getText());
Product2 = new JLabel("Product2");
Product2.setName(Product2.getText());
Product3 = new JLabel("Product3");
Product3.setName(Product3.getText());
}
public JLabel getProduct1() {
return Product1;
}
public void setProduct1(JLabel product1) {
Product1 = product1;
}
public JLabel getProduct2() {
return Product2;
}
public void setProduct2(JLabel product2) {
Product2 = product2;
}
public JLabel getProduct3() {
return Product3;
}
public void setProduct3(JLabel product3) {
Product3 = product3;
}
}

Categories