adding to a textfield in panel1 from a button in panel2 - java

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
}
});

Related

Updating JLabel when JButton Clicked on from another class

I want to update JLabel's text when clicking on JButton.
The problem is that they are on different classes.
I minimized my code as much as I can, so this code doesn't contain every code that I actually have.
Below is the 1st Panel's code, which contains a button that will trigger the text updating method.
public class CultureCategorySelectPanel extends JPanel {
public CultureCategorySelectPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JButton bookCategoryBtn = new JButton("Book");
// When Clicking on JButton
bookCategoryBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mf.getContentPane().removeAll();
CultureListPanel myPanel = new CultureListPanel(mf);
mf.getContentPane().add(myPanel);
String text = “This text will be shown”;
myPanel.updateLabel(text);
mf.setVisible(true);
mf.repaint();
}
});
}
}
And the below is the 2nd Panel's code, which has a textLabel that will be updated.
private JLabel plzSelectLabel;
public CultureListPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JLabel plzSelectLabel = new JLabel(“This text soon be changed”);
plzSelectLabel.setHorizontalAlignment(SwingConstants.CENTER);
plzSelectLabel.setBounds(138, 89, 367, 34);
rightPanel.add(plzSelectLabel);
// 'rightPanel' is on the top of CultureListPanel, I put plzSelectLabel on the panel called 'rightPanel'
}
public void updateLabel(String text) {
plzSelectLabel.setText(text);
}
When I run, I got Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at com.kh.mini_Project.view.CultureListPanel.updateLabel(CultureListPanel.java:169) error.
I also tried with getter/setter but it shows the same error.
EDIT
The code below is MainFrame.
import javax.swing.JFrame;
public class MainFrame extends JFrame{
public MainFrame() {
this.setTitle("--");
this.setSize(1000, 600);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.getContentPane().add(new WelcomPage(this));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
EDIT
The Driver class is here.
public class Run {
public static void main(String[] args) {
new MainFrame();
}
}
Your constructor defines a variable plzSelectLabel which has a local (constructor) scope. Therefor the class level variable (with the same name) will not be initialized hence the NPE.
Hint: read some information about variable scopes ;-)

.getText(); not working for textField variable that is declared in another class

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

JButton in separate class won't change JTextField(Area) text in different class

I have a JFrame which contains 3 JPanels (each in a separate class). The first JPanel contains two JTextFields in which I write the name of the file to be read from and the condition to be fulfilled respectively. This doesn't really affect my question, so let's move on.
The second JPanel has a JTextArea.
The third JPanel has two JButtons (Load, Sort) which are supposed to load a list of entries that suffice the condition from the first JPanel and then reorganize them according to some rules (respectively).
THE PROBLEM:
Ok so, the first class is the JFrame class in which i just do the standard look and feel of the window.
The second class is the first JPanel with two JTextFields.
I won't give code for this one because the second JPanel code is shorter and has the same problem so I imagine that the same solution would apply.
Third class contains the JTextArea in which I should display certain entries from the text-file.
Code:
public class SecondPanel extends JPanel {
JPanel panel;
JTextArea lista;
public SecondPanel() {
panel = new JPanel();
list = new JTextArea("List");
list.setPreferredSize(new Dimension(200, 150));
this.add(list);
}
}
Moving on, the fourth class contains the Jbuttons and the ActionListener(Button listener). Ok so here is the part of the code from the button listener class
CODE:
private class ButtonListener implements ActionListener {
SecondPanel secondPanel = new SecondPanel();
FirstPanel firstPanel = new FirstPanel();
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Load")) {
//calls method that loads data from the text in a firstPanel field
loadData(firstPanel.theFile.getText());
for(int i = 0; i< students.length; i++) {
if(students[i]!=null) {
// doesn't write anything tried with .setText etc.
secondPanel.list.append(students[i]+"\n");
}
}
}
}
}
So the program won't get text when i type in the JTextField designated for the file path. And when i do it manually in the code, It won't write the changes to the list on the Window (JTextArea). But when i System.out.print to the console it prints the changes and lists entries correctly as well as any setText changes I make. It just won't write or read to and from the Window..
What should I do?
The problem is that you are calling your setText methods on the wrong objects.
In your listener class, you declared two new panels as class variables, and then you call your methods on them, but i think those panels are not the ones you really want to change.
You should first add your panels to your Jframe object, and refer to them on your ActionListener.
Here i provide you a minimal code which modifies a JTextArea when a JButton is pressed. (same for a JTextField)
import java.awt.*;
import javax.swing.*;
public class MyJFrame extends JFrame {
SecondPanel sPanel;
public MyJFrame() {
super("main");
Container c = getContentPane();
c.setLayout(new BorderLayout());
JButton button = new JButton("load");
button.addActionListener(new LoadListener());
c.add(sPanel = new SecondPanel(), BorderLayout.NORTH);
c.add(button, BorderLayout.SOUTH);
pack();
setVisible(true);
}
class SecondPanel extends JPanel {
public JTextArea list;
public SecondPanel() {
super();
list = new JTextArea("List");
list.setPreferredSize(new Dimension(200, 150));
add(list);
}
}
class LoadListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
sPanel.list.setText("new text for the jtext area");
}
}
public static void main(String[] args) {
new MyJFrame();
}
}

How can I use Button to Close Frame and Open New Frame?

That's My Code Down Here. I want the answer for java.awt.Button and java.awt.Frame.
Can any one help me with it?
import java.awt.*;
import java.awt.event.*;
public class TestGUI extends Frame implements ActionListener, WindowListener{
private Label lbl;
private Label lbl1
private Label lbl2;
private Label lbl3;
private TextField tf;
private TextField tf1;
private TextField tf2;
private Button btn;
private Button btn1;
private Frame frame;
public TestGUI() {
setLayout(new FlowLayout());
lbl = new Label("Hi Guys! That's My First GUI Program and is made by me too");
add(lbl);
lbl1 = new Label("Enter Your Name Please ~");
add(lbl1);
tf1 = new TextField(30);
tf1.setEditable(true);
add(tf1);
lbl2 = new Label("Enter Your Age Please ~");
add(lbl2);
tf2 = new TextField(30);
tf2.setEditable(true);
add(tf2);
lbl3 = new Label("Enter Your School/College Name Please ~");
add(lbl3);
tf = new TextField(28);
tf.setEditable(true);
add(tf);
btn = new Button("Cancel");
add(btn);
btn.addActionListener(this);
addWindowListener(this);
setTitle("My own GUI");
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args){
TestGUI app = new TestGUI();
}
#Override
public void actionPerformed(ActionEvent evt){
}
#Override
public void windowClosing(WindowEvent evt){
System.exit(0);
}
#Override public void windowDeactivated(WindowEvent evt){}
#Override public void windowActivated(WindowEvent evt){}
#Override public void windowOpened(WindowEvent evt){}
#Override public void windowClosed(WindowEvent evt){}
#Override public void windowIconified(WindowEvent evt){}
#Override public void windowDeiconified(WindowEvent evt){}
}
Thanks in Advance.
You're just complicating the things. Instead of extending the frame & implementing those interfaces, just extend JFrame.
public class TestGUI extends JFrame{...}
In your TestGUI frame create another JFrame say otherFrame and create two bottons say Open & Close and then bind ActionListener to them.
openBtn.addActionListener(new ActionListener(){
otherFrame.setVisible(true);
});
closeBtn.addActionListener(new ActionListener(){
otherFrame.setVisible(false);
});
The setVisible() method accepts boolean & this is what you actually need.
Much simpler & cleaner code.
It might make more sense for you to use a JFrame instead of a Frame (I recomend you read Kumar Vivek Mitra's answer here to get a better idea of why).
If you use a JFrame, you'll need to call yourJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) to stop your program when you close the window.
To respond to your button clicks, simply pass Anonymous Classes to your buttons addOnClickListener() method, like this:
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do stuff here
}
});
Then you should be able to remove your existing actionPerformed() method.
For opening a new frame and closing your existing one, you should be creating two JFrame objects instead of extending Frame (or JFrame). Then, when you want to open your second frame, just call secondFrame.setVisable(true), and close your first one with firstFrame.dispose. However, I'd have a look at JDialogs and JOptionPanes first to see if they might work better for you.
After all this you should be able to remove all your WindowListener stuff, as that's for something slightly different. (Have a look here if you're interested)
Finally, don't forget to add a semicolon after your lbl1 label. ;)
Good luck!
You may use ActionListener interface.
However for a little addition to above guys commented. You may add animation to your frame by adding for loop and setSize method within the loop and the height width of the corresponding loop's variable.

How to enable button from otherJFrame after disabeling it in Main JFrame?

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.

Categories