How to parse and get String to Another Jframe - JAVA - java

I'm trying to parse String to another frame Using JAVA
i have 2 jFrames. jFrame1 have 1 text field and jFrame 2 have 1 text field. i want to parse jFrame1 text filed's text to jframe2's text field.
It's look like this : But this is not code :(
jFrame2.textfield1.setText(jFrame1.textfield1.gettext());
Anyone know how to parse String to another frame Using JAVA?
Thanks in advance!

Assuming that you have two separate GUIs on the screen at the same time because both textFields have the same reference, each JFrame will be a Object in its own right.
Therefore the only way to access another objects variables is with its methods.
Create a setter method in jFrame2 to change the textField in question.
See Working code below.
import java.awt.*;
import javax.swing.*;
import javax.swing.BoxLayout;
import java.awt.event.*;
public class JframeLink {
public static void main(String[] args)
{
new JframeOneGui();
new JframeTwoGui();
}
//JFrame one Object
public static class JframeOneGui extends JFrame implements ActionListener
{
JPanel jPanelOne = new JPanel();
JTextField textField1 = new JTextField("Message for transfer");
JButton buttonOne = new JButton("Transfer");
public JframeOneGui()
{
//setup swing components
textField1.setSize(100,10);
buttonOne.addActionListener(this);
//setup jPanelOne
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
jPanelOne.add(buttonOne);
//setup JframeOneGui
this.add("Center",jPanelOne);
this.setLocation(25,25);
this.setTitle("JframeOneGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonOne)
{
//Here we are calling JframeTwoGui's Setter method
JframeTwoGui.setTextFieldOne(textField1.getText());
}
}
}
//JFrame two Object
public static class JframeTwoGui extends JFrame
{
JPanel jPanelOne = new JPanel();
static JTextField textField1 = new JTextField();
public JframeTwoGui()
{
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
this.add("Center",jPanelOne);
this.setLocation(300,25);
this.setTitle("JframeTwoGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
//Setter to change TextFieldOne in this Object
public static void setTextFieldOne(String text)
{
textField1.setText(text);
}
}
}

Related

Why can´t I click on the JButtons?

Hey I am a beginner and I have wrote the following code in java, but I can´t click on the JButtons. The program includes three clases - Main, Frame and Actionhandler. My goal was to create a Frame with two buttons: Singleplayer and Mulitplayer. I wanted to test if they work, but I can´t click them. Can anyone help me please?
This is the Main class:
public class Main {
public static void main (String [] args) {
new Frame ();
}
}
This is the Frame class:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame {
public static Object multi;
public static Object single;
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton("Singleplayer");
JButton multi = new JButton("Multiplayer");
// specify single button
single.setBounds(200,100,250,80);
single.setForeground(Color.GREEN);
single.setBackground(Color.LIGHT_GRAY);
single.setOpaque(true);
single.setBorder(BorderFactory.createLineBorder(Color.BLACK));
single.setFont(new Font("Comic Sans",Font.BOLD,25));
single.addActionListener(new ActionHandler());
//specify multi button
multi.setBounds(800,100,250,80);
multi.setForeground(Color.GREEN);
multi.setBackground(Color.GRAY);
multi.setOpaque(true);
multi.setFont(new Font("Comic Sans",Font.BOLD,25));
multi.setBorder(BorderFactory.createLineBorder(Color.BLACK));
multi.addActionListener(new ActionHandler());
// add Buttons to Frame
this.add(single);
this.add(multi);
}
}
This is the ActionHandler class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Frame.multi) {
System.out.println("You have clicked on Singleplayer");
if(e.getSource() == Frame.single) {
System.out.println("You have clicked on Multiplayer");
}
}};
}
You can click on the buttons fine. They just won't do anything because of how you've wired the program:
public class Frame extends JFrame {
public static Object multi; // this is null
public static Object single; // and so is this
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton("Singleplayer"); // this is a new *local* variable
JButton multi = new JButton("Multiplayer"); // and so is this:
You are initializing local variables that have the same name as your static class fields, and you're leaving the same static class fields null, a situation known as "variable shadowing", and so in your listeners, you check if the source is the null static field. Which won't work.
So in your listener:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Frame.multi) {
You're testing if a null variable is the button that was pressed, and this will not work.
One simple solution is to not re-declare the multi and single variables, to assign your JButtons to these public static fields by changing this:
JButton single = new JButton("Singleplayer");
JButton multi = new JButton("Multiplayer");
to this:
single = new JButton("Singleplayer");
multi = new JButton("Multiplayer");
This would sort-of work. You'd have do do some casting to add these JButton objects to the container since the variables are Object, not JButton. But this would be a bad idea because you'd be throwing out the OOPs baby with the bathwater, discarding encapsulation completely.
Best not to throw out OOPs rules with public static (non-constant) fields and instead work with them. Better to use constant Strings to be passed into your JButtons and then test for them using the ActionEvent's actionCommand property:
public class Frame extends JFrame {
public static String SINGLE_PLAYER = "Single Player";
public static String MULTI_PLAYER = "Multi Player";
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton(SINGLE_PLAYER); // this is a new *local* variable
JButton multi = new JButton(MULTI_PLAYER); // and so is this:
in the listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(Frame.MULTI_PLAYER)) {
System.out.println("You have clicked on Multi Player");
} else {
// ...
}
}};
}
Other problems with your code include:
Don't name your class Frame since this clashes with the name of class in the core Java library, java.awt.Frame. Name it something unique to avoid confusion
Avoid setting bounds, sizes and such. Let the GUI, its layout managers and component preferred sizes do the sizing by calling pack() on the top-level window (JFrame, JDialog,...) after adding components
Call .setVisible(true) on the top-level window after adding all components.
This looks like it will display as a sub-window or dialog window, and you might want to show this portion of the GUI in a modal JDialog, not in a JFrame.

Type a text in JTextArea from another class

I have a problem with updating a textArea from another class.
I need a textArea to show a text while pressing a button.
So when I press a buton I make a method actionPerformed() in ParceListener to print a text in a textArea which is located in MainFormAppearance class. But it doesn't do that. Could you please help me?
public class Main {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame jFrame = new JFrame("Title");
MainFormAppearance demo = new MainFormAppearance();
jFrame.setContentPane(demo.createContentPanel());
jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
jFrame.setSize(400,300);
jFrame.setVisible(true);
}
}
MainFormAppearance
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFormAppearance {
public JPanel totalGui;
public JTextArea frame;
public JLabel blueLabel;
public JButton parceButton;
public JButton mailButton;
public ParceListener parceListener;
public JPanel createContentPanel(){
totalGui = new JPanel();
frame = new JTextArea();
blueLabel = new JLabel("Some program");
parceButton = new JButton("Button 1");
mailButton = new JButton("Button 2");
parceListener = new ParceListener();
totalGui.setLayout(null);
//set program window
blueLabel.setLocation(10,10);
blueLabel.setSize(400,20);
blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
blueLabel.setForeground(Color.blue);
totalGui.add(blueLabel);
//set Button 1
parceButton.setLocation(270, 50);
parceButton.setSize(100,30);
totalGui.add(parceButton);
//Pressing the Button 1
parceButton.addActionListener(parceListener);
//set Button 2
mailButton.setLocation(270, 100);
mailButton.setSize(100, 30);
totalGui.add(mailButton);
frame.setLocation(20, 115);
frame.setSize(200, 15);
totalGui.add(frame);
totalGui.setOpaque(true);
return totalGui;
}
public void setTextArea(String myString){
frame.append(myString);
}
}
ParceListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ParceListener implements ActionListener {
public String text = "some text";
MainFormAppearance mainFormAppearance = new MainFormAppearance();
public void actionPerformed(ActionEvent e) {
mainFormAppearance.setTextArea(text);
}
}
It shows NullPointerException at frame.append(myString); in MainFormAppearance class.
Calling MainFormAppearance mainFormAppearance = new MainFormAppearance(); in your ParceListener is creating a new instance of MainFormAppearance which has nothing to do with what is actually been presented on the screen.
You need some way to return information back to the main UI from ParceListener.
This is best accomplished using an Observer Pattern, where ParceListener generates notifications/events when something changes. It shouldn't care about "who" is interested, only that they are.
Let's start with a simple interface...
public interface ParceObserver {
public void parceChanged(String text);
}
MainFormAppearance can now implement this interface and make what ever updates it needs.
public class MainFormAppearance implements ParceObserver {
//...
public void parceChanged(String text) {
frame.append("\n" + text);
}
}
Then thing here is, ParceListener, doesn't care what happens after it's posted the notification.
Now, you just need to pass an instance of ParceObserver to ParceListener
parceListener = new ParceListener(this);
And update ParceListener to make use of it...
public class ParceListener implements ActionListener {
private ParceObserver observer;
public String text = "some text";
public ParceListener(ParceObserver observer) {
this.observer = observer;
}
public void actionPerformed(ActionEvent e) {
if (observer == null) {
return null;
}
observer.parceChanged(text);
}
}
Now it's nicely de-coupled and re-usable.
And, if someone tells you to just pass a reference of the JTextArea or MainFormAppearance to ParceListener, please don't listen to them. It's inappropriate, tightly couples your code and exposes the components to the risk of been modified in ways you never intended them to be

I have a small eror in my code here (swing-java-JFrame)

First I am a beginner in java. I'm making a window with small button and a label (with 0 in default position), when I click on the button the label will change to 1 and when I tap another click the button will be 2. But, I have an error in calling the method.
my code:
package prototype;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Prototype {
public static int count;
public static JLabel l;
public void Proto()
{
JFrame f = new JFrame();
JButton b = new JButton("click");
JLabel lo = new JLabel("0");
JPanel p = new JPanel();
f.setBounds(120,120,500,500);
b.addActionListener(new MyAction());
p.add(lo);
p.add(b);
f.getContentPane().add(p,BorderLayout.CENTER);
f.show();}
public class MyAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
count++;
l.setText(Integer.toString(count));}
public static void main(String[] args) {
//I want to call the proto method but it give me an eror
new proto();
}}}
public class Prototype extends JFrame{
private static int count;
private JLabel l;
public Prototype() {
super();
JButton b = new JButton("click");
l = new JLabel("0");
JPanel p = new JPanel();
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
count++;
l.setText(Integer.toString(count));
}
});
p.add(l);
p.add(b);
this.getContentPane().add(p, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
}
public static void main(String...args){
Prototype p=new Prototype();
}
}
I changed the method to a constructor, to have the possibility of creating a object of type Prototype and directly create a frame with it. Also I extended the class with JFrame to not need to create an extra JFrame. Next step was to remove the ActionListener class and creating a new ActionListener while adding it to the button. In my eyes this is useful if you have several buttons with different functionalities, so you can see the function of the button directly just by looking at the code of the button. and the last step was to create a new Object of type Prototype in the main method
If I we're you use a SwingWorker instead of manually setting the text of JLabel. Because this is not a proper way updating your GUI. This should be done using SwingWorker. Please read about publish and processmethod.

Can't access JtextField Values in second JPanel

I am trying since 1 hour but I can't access my jtextField from JPanel to Jpanel1.
I am working on a course project in which I have to show the name of the log in user in the JPanel using jlabel but I can't access the jTextField in JPanel from jpanel1.
I make my JTextField1 public Static using this Answer but still unable to catch the values
I am using this code to fetch the values from JPanel in JPanel1. What I am doing is creating a object of JPanel in JPanel1 and then try to fetch the value.
LoginPanel s = new LoginPanel();
String sc=s.jTextField1.getText();
this.jLabel3.setText(sc);
Don't make a variable static for this purpose as you're breaking OOPs rules for no good reason.
Don't create a completely new object if you want to get the state of another object of the same type, since the two objects will be completely different instances.
If you need to have one object query the state of another (here the state being the text held within the JTextField), then give the the object with the JTextField a public getter field that will return the text in its JTextField and have the first object call this method when needed.
The first object will of course need a valid reference to the displayed object with the text field. How this is done will depend on the structure of your program, something we have no idea of at the moment.
Often the problem is when to obtain the text, since if you try to obtain the text before the user has had a chance to enter anything, then your code won't work. To avoid this, this is usually done in an event listener, and again the details will depend on the structure of your program and on code not shown.
Sometimes the timing is achieved by displaying the 2nd JPanel within a modal dialog window such as a JDialog or JOptionPane. This method is used most often when trying to get log on information from a user.
For better and more specific help, please make your question more informative. Show actual code, not an image of code. How much code? best would be if you could create and show us a minimal code example program.
For example, using a JOptionPane to display one JPanel and obtain text in a modal fashion:
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TwoPanels extends JPanel {
private MyPanel1 panel1 = new MyPanel1();
private MyPanel2 panel2 = new MyPanel2();
public TwoPanels() {
add(panel2);
add(new JButton(new AbstractAction("Get Name") {
#Override
public void actionPerformed(ActionEvent arg0) {
Component parent = TwoPanels.this;
String title = "Enter Name";
int messageType = JOptionPane.PLAIN_MESSAGE;
int optionType = JOptionPane.OK_CANCEL_OPTION;
int result = JOptionPane.showConfirmDialog(parent, panel1, title, optionType, messageType);
if (result == JOptionPane.OK_OPTION) {
String name = panel1.getNameText();
panel2.setNameText(name);
}
}
}));
}
private static void createAndShowGui() {
TwoPanels mainPanel = new TwoPanels();
JFrame frame = new JFrame("TwoPanels");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyPanel1 extends JPanel {
private JTextField nameField = new JTextField(10);
public MyPanel1() {
add(new JLabel("Name:"));
add(nameField);
}
public String getNameText() {
return nameField.getText();
}
}
class MyPanel2 extends JPanel {
private JTextField nameField = new JTextField(10);
public MyPanel2() {
nameField.setFocusable(false);
nameField.setEditable(false);
add(new JLabel("Name:"));
add(nameField);
}
public void setNameText(String text) {
nameField.setText(text);
}
}

JLabel tooltiptext not showing

I expected this to be very simple and straightforward, but tooltiptext is not showing upon hovering the mouse over. I tried printing the text and it prints correctly. Any comments what I'm doing wrong?
public class gui2 extends JFrame {
private JLabel item1;
public gui2() {
super("The title bar");
setLayout(new FlowLayout());
item1 = new JLabel("label 1");
item1.setToolTipText("This is a message");
String str = item1.getToolTipText();
System.out.println(str);
add(item1);
}
class gui {
public static void main(String[] args) {
gui2 g2 = new gui2();
g2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g2.setSize(400, 200);
g2.setVisible(true);
}
}
}
Your code does not compile even if you add the imports. Here is your code corrected and working :
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui {
public static void main(String[] args) {
Window window = new Window();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);
window.setVisible(true);
}
}
class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jlabel;
public Window() {
super("The title bar");
setLayout(new FlowLayout());
jlabel = new JLabel("label 1");
jlabel.setToolTipText("This is a message");
String str = jlabel.getToolTipText();
System.out.println(str);
add(jlabel);
}
}
As mentioned by #restricteur your code does not compile.
This is due to the fact that your class gui which holds the main(..) is nested within another class, hence no static declaration of method is allowed unless the nested class is marked static. ( I simply moved/un-nested Gui out from Gui2)
Besides that your code does work, I think you are being hasty - hold the mouse over JLabel for like 3-4 seconds and you should see the ToolTip appear:
(using your code with no compilation error of course):
Suggestions on code:
1) Please watch java naming conventions i.e class names should begin with a capital letter and each new word thereafter should also i.e gui becomes Gui or GUI but I prefer the former.
2) Dont call setSize on JFrame use and= appropriate LayoutManager and call pack() on JFrame before setting it visible (but after components have been added).
3) Dont extend JFrame unnecessarily simply create an instance and use that.
4) Always create and manipulate Swing Components on Event Dispatch Thread via SwingUtilities.invokeLater(Runnable r) block.
5) Opt for setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); unless using Timers as this will allow main(..) to continue regardless if GUI is exited.
Here is code with above fixes:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
class Gui2 {
private JLabel item1;
private JFrame frame;
public Gui2() {
frame = new JFrame("The title bar");
frame.setLayout(new FlowLayout());
item1 = new JLabel("label 1");
item1.setToolTipText("This is a message");
String str = item1.getToolTipText();
System.out.println(str);
frame.add(item1);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Gui {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui2();
}
});
}
}

Categories

Resources