Basic JAVA variable reach from different files - java

I have this code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class pruebaframe extends JFrame
{
public static String elurl="wut";
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(50);
JButton jb = new JButton("Enter");
public pruebaframe()
{
setTitle("Inserte el URL");
setVisible(true);
setSize(600, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt);
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
elurl=input;
jl.setText(input);
}
});
jp.add(jl);
add(jp);
}
public static String getElurl() {
return elurl;
}
public static void setElurl(String elurl) {
pruebaframe.elurl = elurl;
}
}
Now i want to use the elurl variable in another class like this:
String url1;
pruebaframe t = new pruebaframe();
url1 = t.getElurl();
so everytime i type something on the Jtextfield url1 changes it values. The thing is its not working. It does not change the value. I know it's a simple problem i just cant find where am i wrong.

Pass peuebaframe object when action performed. Either by using constructor or method of another class. Then you can get updated value of your jTextField.
AnotherClass.java
public class AnotherClass {
private pruebaframe t;
public AnotherClass(pruebaframe t) {
this.t= t;
}
public void print() {
System.out.println("Printing From Another Class: " + t.getElurl());
}
}
And do follwoing.
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = jt.getText();
elurl = input;
jl.setText(input);
AnotherClass anotherClass = new AnotherClass(pruebaframe.this);
anotherClass.print();
}
});
Output:
Printing From Another Class: <your updated jTextValue>

When you click the button after changing the text in JTextField a new String object is assigned to elurl. If you want url1 to change everytime you should update it too.
Instead of assigning to a variable, call t.getElurl();everytime you need the elurl value. With this you will always get the latest value of elurl

You static variable usages should be
String url1;
url1 = Pruebaframe.elurl;
But I do not recommend to use static variable to pass a parameter because of concurrent issue.

Related

basic java Main method and update

Im new to pure java after been coding in javabased processing (processing.org) a lot. In processing you have a setup method (the constructor) and a draw method in the main class.
The draw method loops over and over again untill you close the program. In draw i run my methods from other classes.
How do I do this in java? For example in this code below for getting the counter to count?
public class Testing3 {
public static void main(String[] args) {
MyClass c = new MyClass();
System.out.println("c = " + c.getCount());
}
}
And the class:
public class MyClass {
private int value;
public MyClass() {
}
public void setCount(int startV) {
value = startV;
}
public int getCount() {
value++;
int counter = value % 10;
return counter;
}
}
I know I of course can put the printmessage in a while loop and loop it that way but I guess there are other ways?
I have also been using swing a bit through the GUI builder in netbeans. There I cannot reach my objects within the main method, getting the "non static variable cannot be referenced from a static content". only through functions like the one below. But what if I want to get my counter without pushing on a button i created in the builder etc?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {}
I know its a newby question but Im a bit confused.
I didn't exactly understand your question (assuming there's only one question) , but I think this is what you're looking for
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Listener implements ActionListener{
int n;
JLabel label;
public Listener(int n,JLabel label){
this.n=n;
this.label=label;
}
#Override
public void actionPerformed(ActionEvent arg0) {
n++;
label.setText(""+n);
}
}
public class SwingTest {
public static void main(String[] args) {
int n=0;
JFrame frame= new JFrame("My First JAVA SWING App");
frame.setLayout(new FlowLayout());
JLabel label=new JLabel("value here");
JButton button=new JButton("click!!!");
button.addActionListener(new Listener(n,label));
frame.add(button);
frame.add(label);
frame.setSize(200, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
this should be on a file called SwingTest.java

Get boolean value from a class to main method. JAVA

I've been trying for hours to get the boolean value from a class to my main method. I want the variable GeneralFrame.
Also is it correct to use JDialog to ask the user if he is new or returned and then run my JFrame? Here is my code:
package portofoliexpense;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author AlexandrosAndreadis
*/
public class PortofoliExpenseDialog extends JDialog implements ActionListener {
boolean GeneralFrame = false;
//dimiourgia minimatos
JPanel messagePane = new JPanel();
JPanel buttonPanel = new JPanel(); // ftiaxnw button
JButton existinguser = new JButton("Existing User");
JButton newuser = new JButton("New User");
public PortofoliExpenseDialog (JFrame parent, String title) {
super(parent, title);
setLocationRelativeTo(null);
//dimiourgia minimatos
messagePane.add(new JLabel("Hello, click one of the above to continue!"));
getContentPane().add(messagePane);// ypodoxeas gia ola ta //components
buttonPanel.add(existinguser);
buttonPanel.add(newuser);
getContentPane().add(buttonPanel, BorderLayout.PAGE_END); // border //layout sto telos tou dialog
newuser.addActionListener(this);
existinguser.addActionListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false); // den allazei megethos
pack();
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == existinguser) {
GeneralFrame = true;
}
if (source == newuser){
GeneralFrame = false;
}
}
}
I tried lot things. I also used return but couldn't get it.
You can use a JOptionPane for this instead of a JDialog.
Here is an example:
static boolean isNewUser;
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
isNewUser = isNewUser();
}
});
System.out.println("Is new user: " + isNewUser);
}
public static boolean isNewUser() {
Object[] options = { "Existing User", "New User" };
int resp = JOptionPane.showOptionDialog(null, "Hello, click one of the above to continue!", "User Type", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
return resp == JOptionPane.NO_OPTION;
}
In the main method are you calling the variable GeneralFrame as "instance name".GeneralFrame ?
Main method only takes in a string array:
public static void main(String[] args) {
So, the only data you can send to the main method is, of course, an array. But, you want to pass in a boolean.
You know how to pass a paramater, but here it only takes in a string array. Since we want to pass a boolean, lets just pass that boolean in the array.
After you pass the boolean into the main method through the string array, retrieve it doing the following:
boolean boolean1 = Boolean.parseBoolean(ArrayWhereIPutMyBoolean(0));
Now, boolean1 is the boolean that you passed in from main method!

Why is my output null every time?

Hello I have a class that opens a JFrame and takes in a text. But when I try getting the text it says its null.
Everytime I click the button I want the System.out to print the text I entered in the textArea.
This is my first class :
public class FileReader {
FileBrowser x = new FileBrowser();
private String filePath = x.filePath;
public String getFilePath(){
return this.filePath;
}
public static void main(String[] args) {
FileReader x = new FileReader();
if(x.getFilePath() == null){
System.out.println("String is null.");
}
else
{
System.out.println(x.getFilePath());
}
}
}
This is a JFrame that takes in the input and stores it in a static String.
/*
* This class is used to read the location
* of the file that the user.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.event.*;
import javax.swing.*;
public class FileBrowser extends JFrame{
private JTextArea textArea;
private JButton button;
public static String filePath;
public FileBrowser(){
super("Enter file path to add");
setLayout(new BorderLayout());
this.textArea = new JTextArea();
this.button = new JButton("Add file");
add(this.textArea, BorderLayout.CENTER);
add(this.button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
System.exit(0);
}
});
}
}
But everytime I run these programs I get
String is null.
You are mistaken by the way how JFrames work. A JFrame does not stall the execution of the code until it is closed. So, basically, your code creates a JFrame and then grabs the filePath variable in that object, before the user could have possibly specified a file.
So, to solve this, move the code that outputs the filepath to stdout to the ActionListener you have. Get rid of the System.exit() call, and use dispose() instead.
Update: You should have this code for the ActionListener:
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
if(filePath == null){
System.out.println("String is null.");
}
else
{
System.out.println(filePath);
}
dispose();
}
});
And as main method:
public static void main(String[] args)
{
FileBrowser x = new FileBrowser();
}
Your main does not wait until the user has specified a text in the textArea. You could prevent this behaviour by looping until the text in the textArea is set or you could place the logic of the main function into the ActionListener to handle the event.
Following the second way the main function only creates a new FileBrowser object.

Java JTextField information access from another class

I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects

Add to array with actionlistener

I am a beginner with java and has got a problem that I just cant solve.
I am trying to add strings to my array, I have tested my array so that work. But my problem is that I have created an actionlistener and trying to get the text from another class and then add it to the array.
My Buttonlistener:
public class ButtonListener extends AddToLibrary implements ActionListener {
public void actionPerformed(ActionEvent e) {
Database dt = new Database();
dt.add(textType, textTitle, textSort, textDesc);
} }
I got a friend who told me that I am creating a new database every time I pushes the button, but how do I do if I just want to "load" it? Can clear that database is the classname for my array.
The more "funny" part of this is that when I run it in eclipse it goes to debugger without showing me anything clear that is wrong, and because of my limited knowledge in java this is too much to me.
My buttonlistener is geting the information from AddToLibrary and it looks like this:
public class AddToLibrary extends JPanel{
public String textTitle;
public String textSort;
public String textDesc;
public String textType;
public AddToLibrary() {
// Förklarande text
JLabel titel = new JLabel("Titel");
JLabel sort = new JLabel("Genre");
JLabel desc = new JLabel("Beskriving");
// Textrutor
JTextField textTitel = new JTextField(null, 20);
textTitel.setToolTipText("ex. Flickan som lekte med elden");
JTextField textSort = new JTextField(null, 10);
textSort.setToolTipText("ex. Skräck, Action");
JTextField textDesc = new JTextField(null, 15);
textDesc.setToolTipText("ex. Stieg Larsson");
// Knappar
JButton addButton = new JButton("Lägg till");
addButton.addActionListener(new ButtonListener()); //Lyssna på knapp
// Combobox
JComboBox comboBox = new JComboBox();
comboBox.addItem("Film");
comboBox.addItem("CD");
comboBox.addItem("Bok");
comboBox.addItem("Annat");
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
public String getTitelText(JTextField titelText) {
textTitle = "" + titelText.getText();
return textTitle;
}
public String getDescText(JTextField descText) {
textDesc = "" + descText.getText();
return textDesc;
}
public String getSortText(JTextField sortText) {
textSort = "" + sortText.getText();
return textSort;
}
public String getTypeText(JComboBox comboBox) {
return textType = "" + (String) comboBox.getSelectedItem() + ".png";
}
}
But it do not work and I cant understand why it isnt working, so if anyone has some time over to help me I would be pleased.
Thanks!
One fault is here:
public class ButtonListener extends AddToLibrary implements ActionListener {
extending AddToLibrary creates a weird inheritance problem.
The simple solution is to define the ButtonListener inline:
final Database dt = new Database();
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dt.add(getTypeText(comboBox), getTitelText(textTitel), getSortText(textSort), getDescText(textDesc));
}
}); // Lyssna på knapp
One important change is to create one instance of Database to which the strings are added (as Amit Kumar already pointed out).
There were a lot of problems with your code, mostly illegal constructions. My advice is to get a good Java tutorial/book and take notice of how they solve the problems. Also if you use Eclipse (or another modern IDE) it will notify you of any illegal constructions and will try to propose solutions.
One last note, the public Strings and the JTextFields have the same name, this creates a problem for the computer as it does not know which one you are referring to (this is called shadowing). Define unique names for each variable within a class so you do not confuse the compiler or yourself.
=====================================
I have done a little work on your code and I arrived at the following. (It may be improved even further, but this is at least a lot better in terms of legality and readability)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddToLibrary extends JPanel {
private static final long serialVersionUID = 1L;
private Database database = new Database();
private JComboBox comboBox = new JComboBox(new String[]{"Film", "CD", "Bok", "Annat"});
private JButton addButton = new JButton("Lägg till");
private JTextField textTitel = new JTextField(null, 20);
private JTextField textSort = new JTextField(null, 10);
private JTextField textDesc = new JTextField(null, 15);
private JLabel titel = new JLabel("Titel");
private JLabel sort = new JLabel("Genre");
private JLabel desc = new JLabel("Beskriving");
public AddToLibrary() {
textTitel.setToolTipText("ex. Flickan som lekte med elden");
textSort.setToolTipText("ex. Skräck, Action");
textDesc.setToolTipText("ex. Stieg Larsson");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database.add(comboBox.getSelectedItem() + ".png",
textTitel.getText(),
textSort.getText(),
textDesc.getText()
)
}
}); // Lyssna på knapp
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
}
public class ButtonListener extends AddToLibrary implements ActionListener {
private Database dt = new Database();
public void actionPerformed(ActionEvent e) {
dt.add(textType, textTitle, textSort, textDesc);
}
}
should work. Or better, the database should be created in AddToLibrary and passed to ButtonListener in its constructor. Sorry I do not have the time to check the code for you, but if this does not work, you can notify.

Categories