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!
Related
In the following code, I create a jtable with a custom cell editor for the first column and then add undo capabilities to the table. When you run the program, the program allows you to change the values in the first column (test by appending a "d" and then an "e" to the "abc" already there). Now enter control-z (undo) and enter control-z again. It works as expected. But now enter control-z (undo) again. This time the "abc" is erased. It looks like the swing system is setting the initial value of the column and creating an undo event for that action which the user can then undo. My question - how do I write my code so that the user only can undo the actions the user makes?
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
public class UndoExample extends JFrame {
private static final long serialVersionUID = 1L;;
static Boolean objEnableUndoRedoActions = true;
UndoExample rootFrame;
public UndoExample() {
// This procedure starts the whole thing off.
//Create table
final String[] tableColumns = {"Column 1", "Column 2"};
JTable tabUndoExample = new JTable(
new DefaultTableModel(null, tableColumns) {
private static final long serialVersionUID = 1L;
});
final DefaultTableModel tabUndoExampleModel = (DefaultTableModel) tabUndoExample
.getModel();
tabUndoExampleModel.addRow(new Object[]{"abc", true});
tabUndoExampleModel.addRow(new Object[]{"zyw", false});
// Create the undo/redo manager
UndoManager objUndoManager = new UndoManager();
// Create a cell editor
JTextField tfTabField = new JTextField();
TableCellEditor objEditor = new DefaultCellEditor(tfTabField);
// Make the cell editor the default editor for this table's first column
tabUndoExample.getColumnModel().getColumn(0)
.setCellEditor(objEditor);
// Create the undo action on the field's document for the column
tfTabField.getDocument().addUndoableEditListener(
new uelUndoRedoTableCellField(objUndoManager, tabUndoExample));
// Allow undo and redo to be entered by the user
UndoRedoSetKeys(this, "Example", objUndoManager);
tabUndoExample.setInheritsPopupMenu(true);
//Add the table to the frame and show the frame
this.add(tabUndoExample);
this.pack();
setLocationRelativeTo(null);
}
public static void main(final String[] args) {
// Launches the application. This is required syntax.
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final UndoExample rootFrame = new UndoExample();
rootFrame.setVisible(true);
} catch (final Exception e) {
}
}
});
}
#SuppressWarnings("serial")
static class aueUndoRedoTableCellField extends AbstractUndoableEdit {
// Wrap the text edit action item as we need to add the table
// row and column information. This code is invoked when the
// code sees an undo event created and then later when the
// user requests an undo/redo.
JTable objTable = null;
UndoableEdit objUndoableEdit;
int objCol = -1;
int objRow = -1;
public aueUndoRedoTableCellField(UndoableEdit undoableEdit,
JTable table, int row, int col) {
super();
objUndoableEdit = undoableEdit;
objTable = table;
objCol = col;
objRow = row;
}
public void redo() throws CannotRedoException {
// When the user enters redo (or undo), this code sets
// that we are doing an redo (or undo), sets the cursor
// to the right location, and then does the undo (or redo)
// to the table cell.
UndoRedoManagerSetEnabled(false);
super.redo();
#SuppressWarnings("unused")
boolean success = objTable.editCellAt(objRow, objCol);
objTable.changeSelection(objRow, objCol, false, false);
objUndoableEdit.redo();
UndoRedoManagerSetEnabled(true);
}
public void undo() throws CannotUndoException {
super.undo();
UndoRedoManagerSetEnabled(false);
#SuppressWarnings("unused")
boolean success = objTable.editCellAt(objRow, objCol);
objTable.changeSelection(objRow, objCol, false, false);
objUndoableEdit.undo();
UndoRedoManagerSetEnabled(true);
}
}
static class aUndoRedo extends AbstractAction {
// This code is bound to the undo/redo keystrokes and tells
// Java what commands to run when the keys are later entered
// by the user.
private static final long serialVersionUID = 1L;
Boolean objUndo = true;
UndoManager objUndoManager = null;
final String objLocation;
public aUndoRedo(Boolean Undo, UndoManager undoManager, String location) {
super();
objUndo = Undo;
objUndoManager = undoManager;
objLocation = location;
}
#Override
public void actionPerformed(ActionEvent ae) {
try {
// See if operation allowed
if (!objUndoManager.canUndo() && objUndo
|| !objUndoManager.canRedo() && !objUndo)
return;
UndoRedoManagerSetEnabled(false);
if (objUndo) {
objUndoManager.undo();
} else {
objUndoManager.redo();
}
UndoRedoManagerSetEnabled(true);
// Catch errors and let user know
} catch (Exception e) {
UndoRedoManagerSetEnabled(true);
}
}
}
static class uelUndoRedoTableCellField implements UndoableEditListener {
// This action is called when the user changes the table's
// text cell. It saves the change for later undo/redo.
private UndoManager objUndoManager = null;
private JTable objTable = null;
public uelUndoRedoTableCellField(UndoManager undoManager,
JTable table) {
objUndoManager = undoManager;
objTable = table;
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
// Remember the edit but only if the code isn't doing
// an undo or redo currently.
if (UndoRedoManagerIsEnabled()) {
objUndoManager.addEdit(new aueUndoRedoTableCellField(e
.getEdit(), objTable, objTable.getSelectedRow(),
objTable.getSelectedColumn()));
}
}
}
static public Boolean UndoRedoManagerIsEnabled() {
// See if we are currently doing an undo/redo.
// Return true if so.
return objEnableUndoRedoActions;
}
static public void UndoRedoManagerSetEnabled(Boolean state) {
// Set the state of whether we are in undo/redo code.
objEnableUndoRedoActions = state;
}
static void UndoRedoSetKeys(JFrame frame, final String location, UndoManager undoManager) {
// Allow undo and redo to be called via these keystrokes for this dialog
final String cntl_y = "CNTL_Y";
final KeyStroke ksCntlY = KeyStroke.getKeyStroke("control Y");
final String cntl_z = "CNTL_Z";
final KeyStroke ksCntlZ = KeyStroke.getKeyStroke("control Z");
JRootPane root = frame.getRootPane();
root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(ksCntlZ, cntl_z);
root.getActionMap().put(
cntl_z,
new aUndoRedo(true, undoManager, location));
root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(ksCntlY, cntl_y);
root.getActionMap().put(
cntl_y,
new aUndoRedo(false, undoManager, location));
}
}
When you press a key, a series of things occur. The JTable, process the key stroke, it checks to see if the cell is editable (as the TableModel), it then asks the editor for the currently selected cell if the event should edit the cell (CellEditor#isCellEditable(EventObject)).
If this method returns true, the editor is prepared, the value from the TableModel is applied to the editor (ie setText is called), and the editor is added to the JTable, finally, the event which triggered the edit mode is re-dispatched to the editor, in your case the Ctrl+Z, which then triggers and undo event, returning the editor it's initial state (before setText was called).
You can try and use something like...
TableCellEditor objEditor = new DefaultCellEditor(tfTabField) {
#Override
public boolean isCellEditable(EventObject anEvent) {
boolean isEditable = super.isCellEditable(anEvent); //To change body of generated methods, choose Tools | Templates.
if (isEditable && anEvent instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) anEvent;
if (ke.isControlDown() && ke.getKeyCode() == KeyEvent.VK_Z) {
isEditable = false;
}
}
return isEditable;
}
};
to prevent the JTable from been placed into edit when a specific key stroke occurs
Updated
So based on Andrew's answer from JTextArea setText() & UndoManager, I devised a "configurable" UndoableEditListener which can be set to ignore undoable actions, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
public class FixedField {
public static void main(String[] args) {
new FixedField();
}
public FixedField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class UndoableEditHandler implements UndoableEditListener {
private static final int MASK
= Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
private UndoManager undoManager = new UndoManager();
private boolean canUndo = true;
public UndoableEditHandler(JTextField field) {
Document doc = field.getDocument();
doc.addUndoableEditListener(this);
field.getActionMap().put("Undo", new AbstractAction("Undo") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
if (undoManager.canUndo()) {
undoManager.undo();
}
} catch (CannotUndoException e) {
System.out.println(e);
}
}
});
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, MASK), "Undo");
field.getActionMap().put("Redo", new AbstractAction("Redo") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
if (undoManager.canRedo()) {
undoManager.redo();
}
} catch (CannotRedoException e) {
System.out.println(e);
}
}
});
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, MASK), "Redo");
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
if (canUndo()) {
undoManager.addEdit(e.getEdit());
}
}
public void setCanUndo(boolean canUndo) {
this.canUndo = canUndo;
}
public boolean canUndo() {
return canUndo;
}
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(10);
UndoableEditHandler handler = new UndoableEditHandler(field);
handler.setCanUndo(false);
field.setText("Help");
handler.setCanUndo(true);
add(field);
}
}
}
Now, you're going to have to devices your own TableCellEditor to support this, for example...
public static class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
private JTextField editor;
private UndoableEditHandler undoableEditHandler;
public MyCellEditor(JTextField editor) {
this.editor = editor;
undoableEditHandler = new UndoableEditHandler(editor);
editor.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
#Override
public Object getCellEditorValue() {
return editor.getText();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
undoableEditHandler.setCanUndo(false);
editor.setText(value == null ? null : value.toString());
undoableEditHandler.setCanUndo(true);
return editor;
}
}
i am writing a simple BMI calculator program. The application includes ActionListener, which handles button click, check if textfields are filled in and executes calculations.
For now, the ActionListener method is as a subclass of a main class. And it looks like this:
BMICalc.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BMICalc extends JFrame {
private JMenuBar menuBar1;
private JMenu jMenu1;
private JMenuItem jMenuItem1, jMenuItem2;
private JButton jButton1;
private JPanel mainPanel, jPanel1;
private JLabel jLabel1, jLabel2;
private JTextField jTextField1, jTextField2;
private BMICalc() {
super("BMI Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(250, 300));
setLocationRelativeTo(null);
setLayout(new BorderLayout(10, 10));
mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(mainPanel);
jPanel1 = new JPanel(new GridLayout(6,2));
mainPanel.add(jPanel1, BorderLayout.CENTER);
menuBar1 = new JMenuBar();
jMenu1 = new JMenu("Help");
menuBar1.add(jMenu1);
jMenuItem1 = new JMenuItem("The purpose");
jMenu1.add(jMenuItem1);
jMenuItem2 = new JMenuItem("About");
jMenu1.add(jMenuItem2);
setJMenuBar(menuBar1);
jLabel1 = new JLabel("Enter weight in [kg]:");
jPanel1.add(jLabel1);
jTextField1 = new JTextField("");
jPanel1.add(jTextField1);
jLabel2 = new JLabel("Enter height in [cm]:");
jPanel1.add(jLabel2);
jTextField2 = new JTextField("");
jPanel1.add(jTextField2);
jButton1 = new JButton("Calculate");
mainPanel.add(jButton1, BorderLayout.SOUTH);
Handler handler = new Handler();
jButton1.addActionListener(handler);
jMenuItem1.addActionListener(handler);
jMenuItem2.addActionListener(handler);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BMICalc bmicalc = new BMICalc();
bmicalc.setVisible(true);
}
});
}
private class Handler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton1) {
if (jTextField1.getText().equals("") || jTextField2.getText().equals("")) {
JOptionPane.showMessageDialog(null, "All fields must be filled in!", "Error", JOptionPane.INFORMATION_MESSAGE);
}
else {
Calculations calcs = new Calculations();
calcs.calculateBMI(jTextField1.getText(), jTextField2.getText());
JOptionPane.showMessageDialog(null, "Your BMI: " +calcs.returnBMI());
}
}
else if (event.getSource() == jMenuItem1) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
else if (event.getSource() == jMenuItem2) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
Calculations.java
public class Calculations {
private double BMI;
private int weight, height;
public void calculateBMI(String sWeight, String sHeight) {
weight = Integer.parseInt(sWeight);
height = Integer.parseInt(sHeight);
BMI = weight/(height*height*0.0001);
}
public String returnBMI() {
return String.format("%.2f", BMI);
}
}
It works just fine, but I would like to make the code 'clenaer' and make the Handler a class, not a subclass, in another file. I've created a Handler.java and moved the whole Handler subclass, but the class doesn't see the jTextFields and jButton, as they are private (and as far as I'm concerned, they should be).
How can I separate ActionListener class, access these jObjects in it and still be fair with privacy stuff?
Thank you very much for answers.
You can pass the objects you need to the Handler class using the constructor:
public class Handler {
private JButton button;
private JTextField textField;
public Handler(JButton button, JTextField textField) {
this.button = button;
this.textField = textField;
}
}
And when you instantiate the class you just pass in the two variables you want:
Handler handler = new Handler(jButton1, jTextField1);
Explanation:
your Handler class is inner class of of BMICalc. When a nested class is not static (see also difference between static and non-static nested classes) it means that objects of those class exist within an object of the parent class. That's why your Handler class see private fields.
This is no problem for us when the class is static. You just have to pass in those variables to the Handler somehow (constructor or setter fields) and then you can reuse your class for other button-text field combinations.
Edit: Yet another way:
If your handler is to be used here, and only here, and nowhere else in the code, you could instantiate anonymous Handler and assign it to the field (no need to reuse somewhere else). So, in example:
jMenuItem1.addActionListener(new Handler() {
#Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
});
jMenuItem2.addActionListener(new Handler() {
#Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
});
Now you don't have to create one huge Handler with a lot of fields and ifs...
Note that the class Handler that you show is not a subclass of Main. To be a subclass means it inherits. What you have is an inner class.
You need to pass the references to the handler so it can refer to them. For example:
public class Handler implements ActionListener {
private final JTextField jTextField1;
private final JButton jButton1;
public Handler(final JTextField textField, final JButton button)
{
this.jTextField1 = textField;
this.jButton1 = button;
}
}
And create it like this:
Handler handler = new Handler(jTextField1, jButton1);
If you want to protect those JTextField and JMenuItem from the others classes while having the handler in another classe, then you need to add some methods to the BMICalc class:
public boolean isButton1(ActionEvent event) {
return event.getSource() == jButton1;
}
public boolean isJMenuItem1(ActionEvent event) {
return event.getSource() == jMenuItem1;
}
public boolean isJMenuItem2(ActionEvent event) {
return event.getSource() == jMenuItem2;
}
public String getJButton1Text() {
return this.jButton1.getText();
}
public String getJTextField1Text() {
return jTextField1.getText();
}
public String getJTextField2Text() {
return jTextField2.getText();
}
Then you need to have the following Handler class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class Handler implements ActionListener {
private final BMICalc calc;
public Handler(BMICalc calc) {
this.calc = calc;
}
public void actionPerformed(ActionEvent event) {
if (calc.isButton1(event)) {
if (calc.getJTextField1Text().equals("") || calc.getJTextField2Text().equals("")) {
JOptionPane.showMessageDialog(null, "All fields must be filled in!", "Error", JOptionPane.INFORMATION_MESSAGE);
}
else {
Calculations calcs = new Calculations();
calcs.calculateBMI(calc.getJTextField1Text(), calc.getJTextField2Text());
JOptionPane.showMessageDialog(null, "Your BMI: " +calcs.returnBMI());
}
}
else if (calc.isJMenuItem1(event)) {
JOptionPane.showMessageDialog(null, "The program calculates BMI based on information entered by user." , "The purpose of this program", JOptionPane.INFORMATION_MESSAGE);
}
else if (calc.isJMenuItem2(event)) {
JOptionPane.showMessageDialog(null, "BMI Calc v. 1.0 " , "About", JOptionPane.INFORMATION_MESSAGE);
}
}
}
And change on line in the BMICalc :
Handler handler = new Handler(this);
But as the handler is supposed to handle only button and input of this view (and BMICalc class), it would make more sense (for me) to keep this Handler class private and inside the BMICalc class).
Hope this helps !
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.
I have this code (this is all code). I want to write file path(choosing file) on JTextField. I run the program and i press button and file chooser open, i choose file but file path not write on JTextField.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Bilateral;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJText(), new Constraints(new Bilateral(12, 12, 4), new Leading(100, 10, 10)));
add(getJButton0(), new Constraints(new Bilateral(117, 117, 94), new Leading(57, 12, 12)));
setSize(328, 252);
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField();
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
fileChooser.setCurrentDirectory(new File(System.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You are creating a new JTextField inside the method (and you are modfying its contents), but it's not added anywhere.
Drop jTextField0 = new JTextField() and it should work (assuming you already created the text field beforehand).
The code works fine, when I do the following
Change layout manager default BorderLayout (why? Because I don't have GroupLayout, it's not a standard Layout Manager - so I don't know if it's a direct cause)
Add the componenst to corresponding BorderLayout positions.
Changed setSize() to pack(). This is the preferred way.
create the text field the the constructor (new JTextField(int columns)). For some weird reason I feel like this is the culprit (as without this, the text field has no preferred size, and maybe you just weren't seeing it. Not 100% sure, hell probably not even 50% sure, as I couldn't test the GroupLayout
Got rid of frame.getContentPane().setPreferredSize(frame.getSize());, another suspected culprit (not really necessary to delete, but not preferred to keep).
Got rid of this unnecessary line, as it's redundant fileChooser.showOpenDialog(null); and causing the file chooser to open twice.
Here's the result
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
//setLayout(new GroupLayout());
add(getJText(), BorderLayout.WEST);
add(getJButton0(), BorderLayout.EAST);
//setSize(328, 252);
pack();
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField(20);
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class. Note: This class is only created so that you can
* easily preview the result at runtime. It is not expected to be managed by
* the designer. You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
//fileChooser.showOpenDialog(null);
//fileChooser.setCurrentDirectory(new File(System
//.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
System.out.println(path);
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
//frame.getContentPane().setPreferredSize(frame.getSize());
((JPanel) frame.getContentPane()).setBorder(BorderFactory
.createEmptyBorder(20, 20, 20, 20));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You never added JTextField to your JFrame (or whatever window you want the text field to be).
Right after your JTextFIeld0 = new JTextField(); add: myWindow.add(jTextField0)
also, you are displaying two open dialogs. i dont think it is your desired behavior, remove the file fileChooser.showOpenDialog(null);
Here is a quick example of what you are trying to accomplish:
public static void main(String[] args)
{
// you should not need this, use the frame you already have, where the button is.
JFrame window = new JFrame();
// This is what you are doing in your code, however, you should add a text field
// whereever you create and populate your jframe, and add the button etc, and simply
// set the jtextfield value here
JTextField tf = new JTextField();
// again in your case you should have this somewhere else, i assume if you are
// displaying a button, you must have a JFrame somewhere
window.setSize(100, 100);
window.add(tf);
window.setLocationRelativeTo(null);
/***** you DO NEED this code **************/
// create file chooser and open the dialog.
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
// get selected file object
File f = fc.getSelectedFile();
// disply file path in the text field
tf.setText(f.getAbsolutePath());
/****** end of the code you need *********/
// display a JFrame with the text field (dont need this obviously you
// already are displaying the frame)
window.setVisible(true);
}
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