I have two jframes,
I want to get value from opened another jframe to other opened jframe.
when click jframe1 open button showing jframe2 and type some text in text field and click ok button, text field value want to get jframe1 jlable. how to do this i tried but i can't find a way to do this.
Is this possible ?
Use a callback,
add this code to your project:
Define an interface
public interface ICallbackListener{
void onNewEvent(String msg);
}
add to jframe 2:
private ICallbackListener myListener;
public void addCallback(ICallbackListener myListener){
this.myListener = myListener;
}
...
if(myListener!=null){
myListener.onNewEvent("myMessage");
}
...
add to jframe 1:
private ICallbackListener myListener;
ICallbackListener i = new ICallbackListener() {
#Override
public void onNewEvent(String msg) {
// TODO Auto-generated method stub
}
};
public void setCallback( ){
jframe2.addCallback(myListener);
}
now, every thime the jframe2 call the interface method you will get asynchronous a call to the TODO label in the jframe1
Try This
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
class TestFrameExample extends JFrame implements ActionListener{
static JLabel label ;
public static TestFrameExample test;
TestFrameExample()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
label = new JLabel("This is a label!");
JButton button = new JButton("Open");
button.setText("Press me");
button.addActionListener(this);
panel.add(label);
panel.add(button);
add(panel);
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
new TestFrameExample1();
}
public static void main(String s[]) {
test=new TestFrameExample();
}
}
class TestFrameExample1 extends JFrame implements ActionListener {
JTextField t;
TestFrameExample test;
public TestFrameExample1()
{
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
t=new JTextField();
t.setBounds(100,20,150,20);
JButton button=new JButton("oK");
button.setBounds(100,50,100,30);
button.addActionListener(this);
add(t);
add(button);
}
public void actionPerformed(ActionEvent a)
{
test.label.setText(t.getText());
}
}
create a method that takes jframe1 in the jframe2
in the open button action event create a object from jframe2 and call that method that take jframe1.
so when u click Ok button in the jframe2 pass that text field value to the jframe1 object (that u passed to the jframe2) via a methdo
public class jframe1 {
public void actionPerformed(ActionEvent a){
jfame2 jf2 = new jframe2();
jf2.setJframe1(this);
}
public void updateLable(String value){
lblIdk.setText(value);
}
}
public class jframe2 {
private jframe1 jf1;
public void setJframe1(jframe1 jf1){
this.jf1 = jf1;
}
public void actionPerformed(ActionEvent a){
this.jf1.updateLable(txtidk.getText());
}
}
Related
I am new(ish) to Java Swing but I have not been able to find an elegant solution to my issue so I thought I'd raise a question here.
I am trying to make my current JPanel change to another JPanel based on a button click event from within the current JPanel. In essence just hiding one panel and displaying the other. I feel this can be done within my MainFrame class however I'm not sure how to communicate this back to it. Nothing I am trying simply seems to do as desired, I'd appreciate any support. Thanks
App.java
public static void main(final String[] args) {
MainFrame mf = new MainFrame();
}
MainFrame.java
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
// First Page Frame switch
getContentPane().add(new FirstPage());
}
}
FirstPage.java
public class FirstPage extends JPanel {
public FirstPage() {
setVisible(true);
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Change to SecondPage JPanel here.
}
});
add(clickBtn);
}
}
SecondPage.java
public class SecondPage extends JPanel {
public SecondPage() {
setVisible(true);
add(new JLabel("Welcome to the Second Page"));
}
}
Any more information needed, please ask thanks :)
I think the best way is to use CardLayout. It is created for such cases. Check my example:
public class MainFrame extends JFrame {
private CardLayout cardLayout;
public MainFrame() {
super("frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
getContentPane().setLayout(cardLayout);
getContentPane().add(new FirstPage(this::showPage), Pages.FIRST_PAGE);
getContentPane().add(new SecondPage(this::showPage), Pages.SECOND_PAGE);
setLocationByPlatform(true);
pack();
}
public void showPage(String pageName) {
cardLayout.show(getContentPane(), pageName);
}
public static interface PageContainer {
void showPage(String pageName);
}
public static interface Pages {
String FIRST_PAGE = "first_page";
String SECOND_PAGE = "second_page";
}
public static class FirstPage extends JPanel {
public FirstPage(PageContainer pageContainer) {
super(new FlowLayout());
JButton button = new JButton("next Page");
button.addActionListener(e -> pageContainer.showPage(Pages.SECOND_PAGE));
add(button);
}
}
public static class SecondPage extends JPanel {
public SecondPage(PageContainer pageContainer) {
super(new FlowLayout());
add(new JLabel("This is second page."));
JButton button = new JButton("Go to first page");
button.addActionListener(e -> pageContainer.showPage(Pages.FIRST_PAGE));
add(button);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
CardLayout is the right tool for the job.
You can simply create the ActionListener used to swap pages in JFrame class, and pass a reference of it to FirstPage:
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
//Create card layout and set it to the content pane
CardLayout cLayout = new CardLayout();
setLayout(cLayout);
//create and add second page to the content pane
JPanel secondPage = new SecondPage();
add("SECOND",secondPage);
//create an action listener to swap pages
ActionListener listener = actionEvent ->{
cLayout.show(getContentPane(), "SECOND");
};
//use the action listener in FirstPage
JPanel firstPage = new FirstPage(listener);
add("FIRST", firstPage);
cLayout.show(getContentPane(), "FIRST");
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
class FirstPage extends JPanel {
public FirstPage(ActionListener listener) {
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(listener);
add(clickBtn);
}
}
class SecondPage extends JPanel {
public SecondPage() {
add(new JLabel("Welcome to the Second Page"));
}
}
To be short, I create a class Something witch have a function with a JFrame where I have a label and a button on it. On the button I have an addActionListener(new changeLabel()).
I did class changeLabel in the src package for the listener but when I start the application and I click the button throw an NullPointerException on the changeLabel at
nameLabel.setText("Name changed");
line. I want to mention that if I create this listener class in Something class, work perfectly.
I don't know why throw null exception because the label is initialized firstly and after that, the button just want to change the text.
I tryed to make a getFunction, to call that label, I tryed with object Something, with object changeLabel etc... but doesn't work.
Here is some code
package trying;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
public class Something {
JFrame frame;
JLabel changeName;
JButton button;
public void gui(){
frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//is just an example
changeName = new JLabel("Stefan");
//is just an example
button = new JButton("Change");
button.addActionListener(new changeLabel());
frame.getContentPane().add(changeName, BorderLayout.NORTH);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String args[]){
new Something().gui();
}
}
The listener class
package trying;
import java.awt.event.*;
public class changeLabel extends Something implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
changeName.setText("Andrei");
}
}
How can I solve this problem?
The problem is that because the changeLabel class extends Something, it will contain it's own changeName variable which is not initialized == null.
You can:
make the changeLabel implementation private class of Something (good practice) or
pass the JLabel to its constructor.
In both ways changeLabel should not extend Something.
Code Sample #1:
public class Something {
JFrame frame;
JLabel changeName;
JButton button;
public void gui(){
frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//is just an example
changeName = new JLabel("Stefan");
//is just an example
frame.getContentPane().add(changeName, BorderLayout.NORTH);
button = new JButton("Change");
button.addActionListener(new changeLabel());
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String args[]){
new Something().gui();
}
class changeLabel implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
changeName.setText("Andrei");
}
}
}
Code Sample #2:
public class Something {
...
public void gui() {
...
button.addActionListener(new changeLabel(changeName));
}
}
public class changeLabel implements ActionListener {
private final JLabel label;
public changeLabel(JLabel label) {
this.label = label;
}
#Override
public void actionPerformed(ActionEvent e) {
label.setText("Andrei");
}
}
I have problem understanding how is actionListener used in the following code and what is the addWindowListener method doing in the code below:
kindly help me with it .
public class SwingListenerDemo {
private JFrame mainFrame;
private JLabel statusLabel;
public SwingListenerDemo(){
prepareGUI(); }
public static void main(String[] args){
SwingListenerDemo swingListenerDemo = new SwingListenerDemo();
swingListenerDemo.showActionListenerDemo();}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
mainFrame.setVisible(true);
}
private void showActionListenerDemo(){
JButton okButton = new JButton("OK");
okButton.addActionListener(new CustomActionListener());
mainFrame.add(okButton);
mainFrame.setVisible(true); }
class CustomActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button Clicked.");
}
}
}
When you click on ok button, your actionPerformed method will get called as you registered callback on ok button as okButton.addActionListener(new CustomActionListener());
When you close your awing window from top right 'X' button, your program will exit with a return code of 0 and that's what your window listener is doing in windowClosing method.
I have a JFrame that has a textfield and a button. It should become visible at the start of program and when I click on the button, It should become invisible and send the text of textfield to another class. but It send nothing and when I click on the button the IDE goes to the debug mode.
public class JframeFoo extends JFrame {
private String username = new String();
public JframeFoo() {
// --------------------------------------------------------------
// Making Frame for login
final JTextField usernameFiled = new JTextField();
this.add(usernameFiled);
JButton signinButton = new JButton();
// ------------------------------------------------------------
signinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
username = usernameFiled.getText();
setVisible(false);
Main.mainpage.setVisible(true);
}
});
// --------------------------------------------------------------------------
}
public String getuserName() {
return this.username;
}
}
my another class calls Jframe:
System.out.println(JframeFoo.getusername);
Ignoring for a moment that having multiple JFrames jumping out at the user is not a great user interface design, for one object to communicate with another object, it must have a valid reference to the other object. (sorry interrupted by daughter).
So for one JFrame class to get information from the other, it must have a reference to the first object that gets the text, and I don't see you passing that reference, such as in a constructor or setter method.
So for instance if an object of Class1 has information that an object of Class2 needs, then one way to pass it is to give Class2 a reference to the valid instance of Class1, and then have Class2 get the information from the Class1 instance. e.g.,
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ClassMain {
private static void createAndShowGui() {
ClassMain mainPanel = new ClassMain();
JFrame frame = new Class1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Class1 extends JFrame {
private JTextField textfield = new JTextField(10);
public Class1() {
JPanel contentPane = (JPanel) getContentPane();
contentPane.setLayout(new FlowLayout());
add(textfield);
add(new JButton(new AbstractAction("Open Window") {
#Override
public void actionPerformed(ActionEvent arg0) {
Class2 class2 = new Class2(Class1.this);
Class1.this.setVisible(false);
class2.pack();
class2.setVisible(true);
class2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}));
}
public String getTextfieldText() {
return textfield.getText();
}
}
class Class2 extends JFrame {
private Class1 class1;
private JLabel label = new JLabel("");
public Class2(Class1 class1) {
this.class1 = class1;
label.setText(class1.getTextfieldText());
add(label);
}
}
I am trying to call the actionPerformed() in normal method of class. I know that it get automatically executed on whenever button get pressed. But I want to call that method when ENTER button get pressed on Specific textfield. Is it possible to call actionPerformed() in keyPressed() or in normal function/method.
The following code will give you rough idea what I want to do.
void myFunction()
{
actionPerformed(ActionEvent ae);
}
public void actionPerformed(ActionEvent ae)
{
//my code
}
Thanks in advance
If you want, some actionPerformed() method of a JButton to be executed on pressing ENTER inside a JTextField, then I guess you can use the doClick(), method from AbstractButton class to achieve this. Though this approach, might can override the original behaviour of the JTextField on press of the ENTER key :(
Please have a look at this code pasted below, to see if this is what, stands fit for your needs :-) !!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonClickExample
{
private JTextField tfield;
private JButton button;
private JLabel label;
private ActionListener actions = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == button)
{
label.setText(tfield.getText());
}
else if (ae.getSource() == tfield)
{
button.doClick();
}
}
};
private void displayGUI()
{
JFrame frame = new JFrame("Button Click Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
tfield = new JTextField("", 10);
button = new JButton("Click Me or not, YOUR WISH");
tfield.addActionListener(actions);
button.addActionListener(actions);
centerPanel.add(tfield);
centerPanel.add(button);
contentPane.add(centerPanel, BorderLayout.CENTER);
label = new JLabel("Nothing to show yet", JLabel.CENTER);
contentPane.add(label, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ButtonClickExample().displayGUI();
}
});
}
}
I know this is an old thread, but for other people seeing this my recomendation is something like this:
// This calls the method that you call in the listener method
void performActionPerformedMethod(){
actionPerformed(ActionEvent e);
}
// This is what you want the listener method to do
void actionPerformedMethod(){
// Code...
}
// This is the interface method
public void actionPerformed(ActionEvent e){
actionPerformedMethod()
}