I have two classes:
public class Screen1 extends javax.swing.JFrame {
...
//disables JButton1 after it is clicked on
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
setVisible(false);
....
}
}
And another class:
public class Screen2 extends javax.swing.JFrame {
...
//Clicking on JButton2 is supposed to enable JButton1 (from Screen1) again
...
}
Now, what is the easiest way to enable JButton1 again? I don't have direct access to JButton1 from Screen1 to set is visible again. I've looked into ActionListeners and Modal JDialogs which seemed from my Google search like some promising ways to solve this (possibly?).
But I can't really find an example that I would understand (I'm more of a Java beginner).
Any helpful input is appreciated!
Please find below this simple example
Screen2 contains a JButton disabled by default, and Screen1 contains another JButton that can enable the first button.
Screen2
public class Screen2 extends JPanel {
private JButton button;
public Screen2() {
button = new JButton("Button");
button.setEnabled(false); //the button is disabled by default
this.add(button);// add the button to the screen
}
// this method will be used to enable the button
public void changeButtonStatus(boolean flag) {
button.setEnabled(flag);
}
}
Screen1
public class Screen1 {
public static void main(String[] args) {
JFrame frame = new JFrame("Screen1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 200);
frame.setLocationRelativeTo(null);
JButton button = new JButton("Enable the button");
Screen2 screen2 = new Screen2();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
screen2.changeButtonStatus(true); //Call the method that enable the button
}
});
frame.add(screen2, BorderLayout.SOUTH);
frame.add(button, BorderLayout.NORTH);
frame.setVisible(true);
}
}
Output
First, the Screen2 JButton was disabled
When clicking on the Screen1 JButton, the Screen2 JButton will enable.
Related
In trying to read the text that is entered into a textField, I used the actionlistener for a button right next to it. In this actionlistener class, I had an action performed method in which I created a string that was set equal to the textField.getText();. This class however has a problem recognizing textField variable from the previous class.
It is necessary for the .getText() or reading of the textField entry to be in the actionlistener class. I do not know what to try besides the code that I have listed down below.
public class MainClass {
public static void main(String args[]) {
JFrame frame = new JFrame ("Welcome");
frame.setVisible(true);
frame.setSize(500, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JLabel label = new JLabel("...");
panel.add(label);
JTextField text = new JTextField(20);
panel.add(text);
JButton SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JFrame frame1 = new JFrame("Word Commonality");
frame1.setVisible(true);
frame1.setSize(500,200);
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
Error is present at second to bottom line of code. The error is "text cannot be resolved"
I expect that the text can be read and printed out in the console.
Your problem is revolved around function scoping to fix it you need a direct access to the JTextField object you can do so by instantiating a new action performed straight in the MainClass like this:
public class Main {
public static void main(String args[]) {
new MainClass();
}
}
Here I created a class only used to instantiate the window class
For the main class I suggest extending JFrame so you can inherit all of it methods.
//Imports
public class MainClass extends JFrame {
private JPanel panel;
private JLabel label;
private JTextField text;
private JButton SubmitButton;
public MainClass(){
super("Welcome");
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
add(panel);
label = new JLabel("...");
panel.add(label);
text = new JTextField(20);
panel.add(text);
SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
}
});
setVisible(true);
}
}
This is how your class should look like.
Side notes:
Set visible is at the end otherwise the items will not be see able.
The MainClass is inheriting from JFrame so it can use all its methods without instatiating it look at inheritance(https://www.w3schools.com/java/java_inheritance.asp)
The action performed now can acces the text JTextField because it is a class attribute.
If the solution is correct please think of marking this answer as final. Thank you
If you place the getText() outside the ActionListener, it will be read immediately after creating the panel. That is why it is empty. You can make the ActionListener assign a value to a variable, but it will be empty until the action is performed.
Also see here: Swing GUI doesn't wait for user input
Ok so I have 2 jPanels.
one of them has a number of buttons that when pressed should add text to the the textfield that is in the second jPanel.
I am brand spanking new to swing with previously only having to write back end code and web based code so I am having difficulty seeing how you would accomplish this.
I only have buttons created in one panel and a textfield in another so i suspect code would be irrelevant.
Any articles that someone could point me to or examples are greatly appreciated.
So I had this problem ones,
So Lets say you have two JFrame JFrame1 and JFrame2
In order to communicate with each other at runtime both has to have most recent initialized object of each individual frame.
Now lets say this is your first frame where is your textbox,
public class JFrame1 extends JFrame{
JTextField jTextField= null;
public JFrame1() throws HeadlessException {
super("JFrame");
setSize(200, 200);
jTextField = new JTextField();
add(jTextField);
setVisible(true);
}
public void setValueToText(String value){
jTextField.setText(value);
}
}
Then This is second and where is your Button,
public class JFrame2 extends JFrame{
JButton jButton= null;
JFrame1 frame1=null;
public JFrame2() throws HeadlessException {
super("JFrame");
frame1=new JFrame1();
jButton = new JButton("Clieck Me");
add(jButton);
setVisible(true);
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame1.setValueToText("Hi");
}
});
setVisible(true);
}
public static void main(String[] args) {
JFrame2 jf= new JFrame2();
jf.setSize(200, 200);
}
}
Now Just run second class file and click one button which will set hi on your textbox which is in second frame.
So As you see answer lay's in Initialized second object in frame.
My execution is like,
Run JFrame2
Initialized JFrame1 in JFame2 const.
you can make the JTextField an instance variable of the enclosing JFrame and make the two panels inner classes of it. By this, the two panels will have a reference to the same field which belongs to the outer class.
So, you will end up having something similar to:
public class Outer extends JFrame{
private JTextField text = new JTextField();
...
public Outer(){
this.add(new Inner1(), BorderLayout.NORTH);
this.add(new Inner2(), BorderLayout.SOUTH);
}
class Inner1 extends JPanel{
...
public Inner1(){
this.add(text);
}
}
class Inner2 extends JPanel implements ActionListener{
private JButton button = new JButton();
public Inner2(){
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button)
text.setText("Hello StackOverFlow");
}
}
}
add your code to change the text in another panel, when a button clicked in the first panel.
mybutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//do your logic to change the text in another panel
}
});
What is the best way to define the action a button will perform in the code? I want to be able to have one button do one action and the next button do a different action. Is this possible?
You can add action listener like this.
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
You can do this way.
JButton button = new JButton("Button Click");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//do your implementation
}
});
JButton subclasses AbstractButton, which has a method, addActionListener. By calling this method and passing it the action listener you wish to add, the action listener is added and will be called once an action is fired, either programatically, or by way of user interaction. Other listners can be added such as mouse listeners.
One way is to have your class implement ActionListener. Then implement the actionPerformed() method. Here is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Driver extends JFrame implements ActionListener {
private static final long serialVersionUID = 3549094714969732803L;
private JButton button = new JButton("Click");
public Driver(){
JPanel p = new JPanel(new GridLayout(3,4));
p.add(button);
button.addActionListener(this);
add(p);
}
public static void main(String[] args){
Driver frame = new Driver();
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked me!");
}
}
Have a little problem with some code i have writing to try out something. I have made a frame with a single button in it. When i click on this button, a new frame opens, which it should. I close down the new frame, and then click on the button again, to try see if it still works. The problem starts here, corse insted of opening a single new frame, it opens two new frames. Third time i click it opens 4 frames and so on. I have tried quite a few things, but sadly cant seem to find the reason why it is opening more frames. Please help.
package budget;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
String labelPrefix;
JButton button;
JButton button2;
JLabel label;
public static void main(String[] args) {
JFrame f = new GUI();
f.setExtendedState(f.MAXIMIZED_BOTH);
f.setVisible(true);
}
public GUI() {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
button = new JButton("Click Me");
label = new JLabel(labelPrefix);
p.add(button);
this.setTitle("Try");
getContentPane().add(p);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
button.addActionListener(new MyActionListener());
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
button.addActionListener(this);
labelPrefix = "Try";
JFrame f2 = new GUI(label, labelPrefix);
f2.setExtendedState(f2.MAXIMIZED_BOTH);
f2.setVisible(true);
}
}
public GUI(JLabel label, String labelPrefix) {
JPanel p2 = new JPanel();
button2 = new JButton("Close");
p2.add(label);
p2.add(button2);
this.setTitle("Try");
getContentPane().add(p2);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
button2.addActionListener(new MyActionListener2());
}
class MyActionListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
button2.addActionListener(this);
dispose();
}
}
}
Clearly, the problem is here:
button.addActionListener(this);
Every time you click the button, it adds the listener yet another time to the button.
Simply remove that line and the error will go away. Once a listener is added to a button, it stays there. It isn't "consumed" after being triggered.
Check the first line in the actionPerformed of MyActionListener which states:
button.addActionListener(this);
This line should be removed.
I would like that when I click on a button it open a Frame containing a combo box, but the frame does not appears. I'm using AWT.
public class ActionF extends Frame implements ActionListener {
public void actionPerformed(ActionEvent evt) {
setLayout(null);
setBackground(Color.blue);
setBounds(100, 200, 900, 450);
Choice choice = new Choice();
choice.addItem("Choice 1");
choice.addItem("Choice 2");
choice.addItem("Choice 3");
add(choice);
setVisible(true);
}
}
Can you tell me what's wrong?
Thanks in advance.
The code you provided is missing some essential information, e.g. the button that is supposed to open your frame.
A shot in the dark: Could it be possible, that you forgot to add the ActionListener to the actual button instance? This should do it:
public static void main(String[] args) {
Frame f = new Frame();
Button button = new Button();
ActionF actionF = new ActionF();
button.addActionListener(actionF);
f.add(button);
f.setVisible(true);
}