java Passing variables from one class to another - java

I have an error for the code below. Sorry if this is too basic as I am new to java.
Basically, I cannot retrieve the String "44418" from the class CityChange.
I know the reason is because I created a new instance cc in the class MainPanel.
However I do not know any other way of doing it.
public class CityChange extends JPanel {
public CityChange() {
JButton btn1 = new JButton("London")
this.add(btn1);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//London Yahoo Weather Code 44418
setCitySelected("44418");
}
});
}
public void setCitySelected(String citySelected) {
this.citySelected = citySelected;
}
public String getCitySelected() {
return citySelected;
}
private String citySelected;
}
public class MainPanel extends JPanel {
public MainPanel() {
CityChange cc = new CityChange();
System.out.println(cc.getCitySelected()); //returns null instead of 44418
}
}
Please give some advice. Thank you.

For timing reasons, the value has no choice but to be null.
What happens here "immediately" (at init time) is that a new CityChange object is created and its citySelected is gotten and printed. As nobody set it otherwise, it is null.
Only after firing the event (clicking the button), it gets a value, and if you print the value then, you'll see the new value.

The code setCitySelected("44418"); is only executed when you call the method public void actionPerformed(ActionEvent evt) which is not happening at the moment. This Method is only called via a Button in a GUI so you first need at least a simple Window with a Button. Here is a good example http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Related

Passing a selected value to a new listener

since i need an action listener that has a kinda big size of code, i decided to make a new listener as a class.
My problem is that i need to pass the selected value from a scroll pane so i can take actions based on that item, it passes a null pointer since the listener is made even before i click the button that takes the action
My class is:
public class RecipeListener implements ActionListener{
//rest code
My new class constructor is:
public RecipeListener(ArrayList<Food> foodList, String aSelectedRecipe){
this.recipesList = foodList;
this.selectedRecipe = aSelectedRecipe;
}
And my implementation of listener is:
RecipeListener checkRecipeListener = new RecipeListener(breakfastArrayList, breakfastList.getSelectedValue());
press the button, having selected an item first from the list
EDIT: Here is the solution, which is passing the jlist as a parameter to the constructor and making a string inside the actionPerfomed method.
private JList tList;
public RecipeListener(ArrayList<Food> foodList, JList tempList){
/*construction arguments*/
}
public actionPerfomed(ActionEvent arg0){
String selectedRecipe = (String) tList.getSelectedValue();
//rest code
}
You should define your listener as following:
public class RecipeListener implements ActionListener{
//rest code
public RecipeListener(ArrayList<Food> foodList){
this.recipesList = foodList;
}
public void actionPerformed(ActionEvent e) {
String selectedReceipe = breakfastList.getSelectedValue();
// other processing code
}
In this case value will be taken after user pressed the button.

Passing data from one jframe to another jframe java

I have two JFrames.One Jframe has one Jtabel , when i selectedrow and press the JButton, second Jframe set string acd get text from jframe1
code in jframe1
int i = tblschdule.getSelectedRow() ;
String a = (String) tblschdule.getValueAt(i, 0) ;
String b = (String) tblschdule.getValueAt(i, 1) ;
Fisimonitoring form1 = new Fisimonitoring();
form1.acd=a;
form1.setVisible(true);
jframe2
public String acd;
code form1.acd=a; not work, String acd always null. how to solve it ?
your question is very incomplete bt here is an example to send data to another
frame
//a jframe
public class Aframe extends javax.swing.JFrame {
private Bframe bframe;
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
if (bframe==null) {
bframe = new Bframe();
}
String text = jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn()).toString();
bframe.setText(text);
bframe.setVisible(true);
}
}
//b jframe
public class Bframe extends javax.swing.JFrame {
public void setText(String text){
this.textField.setText(text);
}
}
in your case if you have already opened Bjframe you should make sure that same instance of Bjframe is shared by Ajframe.
It's quiet late for this answer but the solution for your problem is pretty simple.
You Need to send the value across the frame's.
Like if you are on jFrame1 and on click you are calling JFrame2
function actionPerformedOnButtonClick(){
String text = valueOfTheLabel;
new YourFrameName(text).setVisible(true);
}
And on JFrame2, You need to write a parameterized contructor like this..
public JFrame2(String textFromFrame1) {
initComponents();
}
And You can Access It on Frame2.

java restrict switching of window/Jpanel

I have JFrame with 3 JPanel(basically three tabs). one of the panel has a textbox. there is value restriction on textbox. it means, user can enter only 1-1000 number in it. If he enters number >1000, it throws the warning message.
Now I am using focuslistener to save the entered number as soon as it looses the focus. But if the user enters 1200 and click on another tab(panel), it gives me expected warning message but also goes to the another tab. I need to remain in same panel if there is warning box. I don't want to loose the focus from the current panel.
mMaxLabelLength = new JTextField();
mMaxLabelLength.addActionListener(this);
public void focusGained(FocusEvent fe)
{
// do NOTHING
}
#Override
public void focusLost(FocusEvent fe)
{
saveActions();
}
public void actionPerformed(ActionEvent e)
{
//Do something
}
private void saveActions()
{
// error message
JOptionPane.showMessageDialog(this,
"Please enter an integer value between 1 and 1000.",
"Invalid Entry", JOptionPane.INFORMATION_MESSAGE);
SwiftApplication APP = SwiftApplication.getInstance();
int nMaxLabel = APP.getMaxPieLabel();
mMaxLabelLength.setText(new Integer(nMaxLabel).toString());
mMaxLabelLength.requestFocus();
}
The code block in the question does not offer too many details, but as far as I understand it, you need to use a VetoableChangeListener to prohibit focus change.
Here an example from Java2s:
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class Main {
public static void main(String[] argv) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener(
new FocusVetoableChangeListener());
}
}
class FocusVetoableChangeListener implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
Component oldComp = (Component) evt.getOldValue();
Component newComp = (Component) evt.getNewValue();
if ("focusOwner".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
} else if ("focusedWindow".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
}
boolean vetoFocusChange = false;
if (vetoFocusChange) {
throw new PropertyVetoException("message", evt);
}
}
}
But, the more I think about it, maybe using InputVerifier and public boolean shouldYieldFocus(JComponent input) is more appropriate. See "Validating Input" in the "How to Use the Focus Subsystem" of the Java Tutorial.
Looks like you are looking for an InputVerifier.
Abstract class that allows input validation via the focus mechanism. When an attempt is made to shift the focus from a component containing an input verifier, the focus is not relinquished until the verifier is satisfied.
As the oracle page describes, it can be used to write own verifiers, which reject invalid inputs and keeps the focus meanwhile on the associated JComponent.
Therefore you just need to do two things:
Write your own InputVerifier, e.g. MyVerifier or take one of the already existing ones and create an instance of it. (See below for a small complete verifiable example)
Register your verifier instance on the target JComponent using calls to the Input Verification API.
This means, to register an...
InputVerifier call the setInputVerifier method of the JComponent class. For example, the InputVerificationDemo has the following code:
private MyVerifier verifier = new MyVerifier();
...
amountField.setInputVerifier(verifier);
Note For some reason I can't find a source for the java8 InputVerifier right now, it seems that the link is broken.
Small Verifiable Complete Example (from here)
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
// This program demonstrates the use of the Swing InputVerifier class.
// It creates two text fields; the first of the text fields expects the
// string "pass" as input, and will allow focus to advance out of it
// only after that string is typed in by the user.
public class VerifierTest extends JFrame {
public VerifierTest() {
JTextField tf1 = new JTextField ("Type \"pass\" here");
getContentPane().add (tf1, BorderLayout.NORTH);
tf1.setInputVerifier(new PassVerifier());
JTextField tf2 = new JTextField ("TextField2");
getContentPane().add (tf2, BorderLayout.SOUTH);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
}
class PassVerifier extends InputVerifier {
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
return "pass".equals(tf.getText());
}
}
public static void main(String[] args) {
Frame f = new VerifierTest();
f.pack();
f.setVisible(true);
}
}

Java Alter Swing Element from Child Class

I'm having a problem with something I don't understand. I have a java class that is building up my program and another class full of functions called by action listeners.
I'm hoping to use the the child's class functions to alter the contents of a JLabel (just an example) using a setter function which doesn't seem to be doing anything and not crashing.
My main class has
public class Parent extends JFrame {
static JPanel dummyPanel = new JPanel();
static JLabel dummyLabel = new JLabel("label");
static JButton dummyButton = new JButton("button");
static Child child = new Child();
public Parent() {
// main setup goes here
// add elements goes here
ActionListener alterLabel = new ActionListener() {
public void actionPerformed(ActionEvent dummyButton) {
child.childFunc();
}
}
dummyButton.addActionListener(alterLabel);
}
// main function goes here
public void newText() {
dummyLabel.setText("altered");
System.out.println("new text function has been executed");
}
}
Then the child I am using to call the function to change the text contains
public class Child {
public void childFunc() {
Parent parent = new Parent();
parent.newText();
}
}
When I click the button it runs and I see it outputs the string which I expect but it does not seem to change the label.
Why is this and is there a way to fix it?

Java - Cannot find the symbol of an inner class that implements an ActionListener

I'm going off of what I saw in a textbook to make an action listener for a button. To do it, I made an inner class. When I try to call the inner class, the error comes up: cannot find symbol.
Here's the code:
package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMGUI extends GUI
{
public ATMGUI()
{
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new WithdrawListener());
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
class WithdrawListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
}
}
//------------------------------------------------------------------
public void makeFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public void makePane()
{
pane = new JPanel();
pane.setLayout(new GridLayout(3,3));
pane.setVisible(true);
}
public void makeButton(String buttonName)
{
button = new JButton(buttonName);
}
public void makeText(String addText)
{
text = new JLabel(addText);
}
public void makeTextField(String addText)
{
field = new JTextField(addText);
}
}
This is the particular bit that is giving me trouble
button.addActionListener(new WithdrawListener());
I saw somewhere else that it had to be instantiated in a certain way.
I tried something like:
ATMGUI a = new ATMGUI();
ATMGUI.WithdrawListener w = a.new WithdrawListener();
and then put w in for the argument, but that didn't really work for me either.
Not sure if it is because I'm working in a subclass. Also not really sure if things need to be done differently because I'm working with an interface.
Place the WithdrawListener outside of the constructor context
public class ATMGUI extends GUI {
public ATMGUI() {
//...
button.addActionListener(new WithdrawListener());
//...
}
class WithdrawListener implements ActionListener {
public void actionPerformed(ActionEvent click) {
System.out.println("This is a test.");
}
}
Add listener to button after local class declaration.
public void abc(){
PQR pqr = new PQR(); // incorrect
class PQR {
}
}
Correct way is
public void abc(){
class PQR {
}
PQR pqr = new PQR(); //correct
}
It seems like you must declare the local class before you use it. The follwing code snippets I tested:
This one showed no errors:
public void testFunc() {
class Test {
}
Test test = new Test();
}
But this one does:
public void testFunc() {
Test test = new Test();
class Test {
}
}
Edit: Sorry for posting nearly at the same time, next time I will check three times if someone already posted.
Use of anonymous type is recommended when you are not reusing a class.
Have a look at it (frequently used with listeners) - It's a great answer!!
quoted from above link
Using this method makes coding a little bit quicker, as I don't need
to make an extra class that implements ActionListener -- I can just
instantiate an anonymous inner class without actually making a
separate class.
I only use this technique for "quick and dirty" tasks where making an
entire class feels unnecessary. Having multiple anonymous inner
classes that do exactly the same thing should be refactored to an
actual class, be it an inner class or a separate class.
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new ActionListener() { //starts here
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
});//ends
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);

Categories