This question already has answers here:
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 8 years ago.
How can I change the Value of a JTextfield inside an ActionLIstener?
cmdAnzeigen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/* Cannot refer to a non-final variable TextOutput inside an
inner class defined in a different method*/
TextOutput.setText("Hello");
}
});
Here,You can write another method and put your TextField value change code in this method. like,
public class Demo {
static JTextField txtName;
static JButton jbSubmit;
public Demo()
{
txtName = new JTextField(10);
jbSubmit = new JButton("Submit");
jbSubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
change("XYZ");
}
});
}
public static void change(String name)
{
txtName.setText(name);
}
public static void main(String[] args) {
Demo d = new Demo();
JFrame jf=new JFrame();
jf.add(txtName);
jf.add(jbSubmit);
jf.setLayout(new FlowLayout());
jf.setVisible(true);
jf.setSize(500,200);
}
}
Related
This question already has answers here:
Value Change Listener to JTextField
(14 answers)
Closed 2 years ago.
I want to know if there is a way to notice if a listener is changing the text of a JTextField or if it is done by .setText(); I need to seperate between both cases, beacause it need to do different things when accesed by a user or by the programm.
I assume you use a DocumentListener to hook into user's input. You can remove this document listener while you call the setText from your program.
Take a look at the following example. When the button is pressed, the text is changed without the printing message.
public class DocumentListenerExample extends JFrame {
private JTextField textField;
private DocumentListener textFieldDocumentListener;
public DocumentListenerExample() {
super("");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textField = new JTextField(20);
textFieldDocumentListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
System.out.println("Text changed by user");
}
#Override
public void insertUpdate(DocumentEvent e) {
System.out.println("Text changed by user");
}
#Override
public void changedUpdate(DocumentEvent e) {
System.out.println("Text changed by user");
}
};
textField.getDocument().addDocumentListener(textFieldDocumentListener);
add(textField);
JButton button = new JButton("Change text");
button.addActionListener(e -> {
textField.getDocument().removeDocumentListener(textFieldDocumentListener);
textField.setText(String.valueOf(Math.random()));
textField.getDocument().addDocumentListener(textFieldDocumentListener);
});
add(button);
pack();
setLocationByPlatform(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new DocumentListenerExample().setVisible(true);
});
}
}
I'm writting a program and the GUi Class (main class) is overloaded.
I want to know if it's possible to split the class in several classes.
for example I made a class of constaints.
The main question is if I can keep all interface code in one class(where I'll addd and initialize JTetxFields,JButtons and other Jobjects) and then use them in another class.
for example:
in interface class there will be:
JTextField field = new JTextField(12);
JButton button = new JButton("Click");
and in main class I do smthng like this:
add(field);
add(button);
button.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if(e.getSource==button){
field.setVisible(false);
}
if it's possible with creating new JFrame,then please tell me how to create new Frame and use it in main class.
Your main question -- can you create a class that is a repository of your GUI components and use them elsewhere, and the answer is yes you can, but I don't think that you should, at least not for simple components. You should keep your JTextFields, JButtons in the GUI classes that use them, but any major subsection of your GUI, such as a JPanel that contains components and that has a unique functionality, that can go in its own class.
More important is to separate out different functional parts of your program, especially you should try to separate out the logical or "model" part of your program from the GUI or "view" part. The details of how you do this will depend on the details of your program and overall problem.
For example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SeparateClasses {
private static void createAndShowGui() {
SeparateClassView mainPanel = new SeparateClassView();
new SeparateClassControl(mainPanel);
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
public class SeparateClassView extends JPanel {
private JTextField field1 = new JTextField(12);
private JTextField field2 = new JTextField(12);
private JTextField resultField = new JTextField("false", 5);
private JButton button = new JButton("Click");
public SeparateClassView() {
resultField.setEditable(false);
resultField.setFocusable(false);
add(new JLabel("Field 1:"));
add(field1);
add(new JLabel("Field 2:"));
add(field2);
add(button);
add(new JLabel("Two texts equivalent?:"));
add(resultField);
}
public void addButtonListener(ActionListener listener) {
button.addActionListener(listener);
field1.addActionListener(listener);
field2.addActionListener(listener);
}
public String getField1Text() {
return field1.getText();
}
public String getField2Text() {
return field2.getText();
}
public void setField1Text(String text) {
field1.setText(text);
}
public void setField2Text(String text) {
field2.setText(text);
}
public void setResult(boolean result) {
resultField.setText(String.valueOf(result));
}
}
public class SeparateClassControl implements ActionListener {
private SeparateClassView view;
public SeparateClassControl(SeparateClassView view) {
this.view = view;
view.addButtonListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
String text1 = view.getField1Text();
String text2 = view.getField2Text();
boolean result = SeparateClassModel.stringsEquivalent(text1, text2);
view.setResult(result);
}
}
public class SeparateClassModel {
public static boolean stringsEquivalent(String text1, String text2) {
return text1.equalsIgnoreCase(text2);
}
}
I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)
I have a task to create a Fahrenheit to Celsius converter, I've written the program as follows, it's the way that teacher has taught us, so I'm obliged to follow it, I know it's even very rudimentary but I have no other choice to follow his stupid way.
All I need help with is that I want to replace that JOptionPane in the last line with "JLabel", I want the result to be showed in a JLabel. What can I do?
Converter.java
public class Converter extends JFrame implements ActionListener{
JTextField Textbox = new JTextField (20);
JButton button1 = new JButton("Submit");
int x;
public Converter()
{
setLayout(new FlowLayout());
add(button1);
add(Textbox);
button1.addActionListener(this);
setVisible(true);
setSize(800,600);
}
public void actionPerformed(ActionEvent arg0)
{
String s=Textbox.getText();
int res=Integer.parseInt(s);
JOptionPane.showMessageDialog(null,(res-32)*(5)/(9)); ///I need help here
}
}
WindowFrame.java
public class WindowFrame {
public static void main(String[] args) {
Converter x = new Converter();
}
}
Create a new JLabel then add it to your container (JFrame), then in the actionPerformed you can do:
public void actionPerformed(ActionEvent arg0)
{
String s = Textbox.getText();
int res = Integer.parseInt(s);
String result = String.valueOf((res-32)*(5)/(9));
label.setText(result);
}
Do the changes in Converter.java as given in image,
I'm not used to Java and JFrame as I'm just starting to learn.
My question is that, I have error at the method actionPerformed. The error given is at the e.getsource == b I believe.
From what I understand, the button I created at the public static void main(String[] args) doesn't passed the value of the button to the actionPerformed.
I'm sorry if my question is not clear.
Here is my code
public static void main(String[] args){
JButton b = new JButton("Click here");
JFrame newWindow = new JFrame("Test");
newWindow.setVisible(true);
newWindow.setSize(250,250);
newWindow.setLayout(null);
newWindow.add(b);
b.addActionListener(this);
}
Here is another part of my code
public void actionPerformed(ActionEvent e)
{
if ( e.getSource() == b )
{
//do something
}
}
From what I understand, the button I created at the public static void
main(String[] args) doesn't passed the value of the button to the
actionPerformed.
Yes, you are right. The JButton object b is not visible at actionPerformed method. You need declare b globally.
class MyClass extends JFrame implements ActionListener{
// Declare here to make visible to actionPerformed
JButton b = new JButton("Click here");
MyClass(){
super("Test");
b.addActionListener(this);
add(b);
setVisible(true);
setSize(250,250);
}
public void actionPerformed(ActionEvent e){
if ( e.getSource() == b ){
//do something
}
}
public static void main(String[] args){
new MyClass();
}
}
It is e.getSource(). It is a method and all methods end in parentheses ().
Also, b is not visible in actionperformed(). Make it a global variable i.e. define it outside of main() and make it static so as to be able to access it in main()
Plus, as Masud asked, did your class implement the ActionListener interface ?