Hi i was wondering how to Dispose a jFrame from another one, cause i want to create a new instance of that class with new values in its textfields, so the First jFrame is this:
public class Frame1 extends javax.swing.JFrame implements ActionListener {
Frame2 f;
public Frame1() {
initComponents();
this.setLocationRelativeTo(null);
}
private void rbtnShowFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
f = new Frame2();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
this.dispose(); //I TRIED TO DISPOSING IT HERE BUT DOESN'T WORK
}
}
So i want in the other jFrame Dispose the jFrame1 only if i trigger the event action performed of a botton, if this doesn't happen i do't want to dispose it, i don't know if i can do it with ActionListener, this is the Second jFrame:
public class Frame2 extends javax.swing.JFrame {
public Frame2() {
initComponents();
this.setLocationRelativeTo(null);
Frame1 f1 = new Frame1();
this.cmdOk.addActionListener(cGUI);
}
private void cmdOkActionPerformed(java.awt.event.ActionEvent evt) {
//Here is where i want to dispose() the other jFrame1
//to create a new instance and pass the value using public static jTextFields
f1.labelNumeroCotizacion.setText(this.labelNumCotizacionEnviar.getText());
f1.setVisible(true);
}
}
Sorry for my Code, i am newbie using OOP! thanks for all guys....
Here is an example of how to dispose a JFrame from another JFrame:
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
FrameA one = new FrameA();
FrameB two = new FrameB(one);
one.setVisible(true);
two.setVisible(true);
}
});
}
}
class FrameA extends JFrame
{
private static final long serialVersionUID = 1812279930292019387L;
public FrameA()
{
super("Frame A");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
setResizable(false);
}
}
class FrameB extends JFrame
{
private static final long serialVersionUID = 5126089271972476434L;
public FrameB(final JFrame otherFrame)
{
super("Frame B");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
setLocationRelativeTo(otherFrame);
JButton button = new JButton("Dispose Other");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
otherFrame.dispose();
}
});
add(button);
setResizable(false);
}
}
Related
I am new to Java Swing and I am trying to learn how to close one frame without closing the other one using button. For example I have a frame1/window that just have a button called login. Once I click on login button, another window appear frame2. On frame2 I just have a sample JLabel "Hello And Welcome", button called Logout. I want to be able to click on the Logout button on frame2 and frame2 window should close, but frame1 window show still be open. I have try setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE), but it only work if I click on the x icon on the top right of the frame2 window. Does anyone know of a way to close a frame when you click on a button?
public class Frame1 extends JFrame implements ActionListener{
private static JButton login = new JButton("Login");
private static JFrame f = new JFrame("Login");
Frame1(){
f.setSize(1000,750);
f.setLocation(750, 250);
login.setBounds(250, 350, 150, 30);
f.add(login);
f.setLayout(null);
f.setVisible(true);
login.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == login){
Frame2.frame2windown();
}
}
public static void main(String [] args){
Frame1 login1 = new Frame1();
}
}
public class Frame2 extends JFrame implements ActionListener{
private static JButton logout = new JButton("Logout");
private static JLabel jb1 = new JLabel ("Hello And Welcome");
private static JFrame f = new JFrame("Log Out");
Frame2(){
f.setSize(1000,750);
f.setLocation(750, 250);
jb1.setBounds(250, 150, 350, 30);
logout.setBounds(250, 350, 150, 30);
f.add(logout);
f.add(jb1);
f.setLayout(null);
f.setVisible(true);
logout.addActionListener(this);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent a){
if(a.getSource() == logout){
dispose();
WindowEvent closeWindow = new WindowEvent(this, JFrame.DISPOSE_ON_CLOSE);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closeWindow);
}
}
public static void frame2windown(){
Frame2 f2 = new Frame2();
}
}
So, there are a whole bunch of concepts your need to try and learn.
It's generally recommended NOT to extend from top level containers (like JFrame). You're not adding any new functionality too them; they are complicated, compound components; you lock yourself into a single use case (what happens if you want to include the UI in another UI or use a dialog instead of frame?!)
Multiple frames aren't always a good idea and can be confusing to the user. Generally, with login workflows though, I might argue a login dialog is generally a better solution, but you need to understand the use cases to make those determinations.
Swing is a large, rich and diverse API, it has a LOT of inbuilt functionality, which you can use, to make your life easier (although it doesn't always seem this way)
Layout managers are an absolutely required feature and you really need to take the time to learn them, see Laying Out Components Within a Container for more details.
So, a really quick example of using a CardLayout and a basic "observer pattern", which decouples and separates responsibility.
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new NavigationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class NavigationPane extends JPanel {
protected enum NavigationTarget {
LOGIN, MAIN;
}
private LoginPane loginPane;
private MainPane mainPane;
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
loginPane = new LoginPane();
loginPane.addLoginListener(new LoginPane.LoginListener() {
#Override
public void loginDidFail(LoginPane source) {
JOptionPane.showMessageDialog(NavigationPane.this, "You are not unauthroised", "Error", JOptionPane.ERROR_MESSAGE);
}
#Override
public void loginWasSuccessful(LoginPane source) {
navigateTo(NavigationTarget.MAIN);
}
});
mainPane = new MainPane();
add(loginPane, NavigationTarget.LOGIN.name());
add(mainPane, NavigationTarget.MAIN.name());
navigateTo(NavigationTarget.LOGIN);
}
protected void navigateTo(NavigationTarget target) {
cardLayout.show(this, target.name());
}
}
public static class LoginPane extends JPanel {
public static interface LoginListener extends EventListener {
public void loginDidFail(LoginPane source);
public void loginWasSuccessful(LoginPane source);
}
public LoginPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton btn = new JButton("Login");
btn.addActionListener(new ActionListener() {
private Random rnd = new Random();
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
if (rnd.nextBoolean()) {
fireLoginWasSuccessful();
} else {
fireLoginDidFail();
}
}
});
add(btn);
}
public void addLoginListener(LoginListener listener) {
listenerList.add(LoginListener.class, listener);
}
public void removeLoginListener(LoginListener listener) {
listenerList.remove(LoginListener.class, listener);
}
protected void fireLoginDidFail() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
for (LoginListener listener : listeners) {
listener.loginDidFail(this);
}
}
protected void fireLoginWasSuccessful() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
for (LoginListener listener : listeners) {
listener.loginWasSuccessful(this);
}
}
}
public static class MainPane extends JPanel {
public MainPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("Welcome"));
}
}
}
JDialog based login workflow
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
NavigationPane navigationPane = new NavigationPane();
JFrame frame = new JFrame();
frame.add(navigationPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
if (LoginPane.showLoginDialog(navigationPane)) {
navigationPane.didLogin();
} else {
frame.dispose();
}
}
});
}
public static class NavigationPane extends JPanel {
protected enum NavigationTarget {
SPLASH, MAIN;
}
private SplashPane splashPane;
private MainPane mainPane;
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
mainPane = new MainPane();
splashPane = new SplashPane();
add(splashPane, NavigationTarget.SPLASH.name());
add(mainPane, NavigationTarget.MAIN.name());
navigateTo(NavigationTarget.SPLASH);
}
protected void navigateTo(NavigationTarget target) {
cardLayout.show(this, target.name());
}
public void didLogin() {
navigateTo(NavigationTarget.MAIN);
}
}
public static class LoginPane extends JPanel {
private Random rnd = new Random();
private boolean isAuthorised = false;
public LoginPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
add(new JLabel("User name and password fields go here"));
}
protected void authenticate() {
// Authenticate
isAuthorised = rnd.nextBoolean();
if (!isAuthorised) {
JOptionPane.showMessageDialog(this, "You are not authorised", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// So this should return some kind of "session" or something so
// can identify the user, but for now, we'll just use
// a boolean
public boolean isAuthorised() {
return isAuthorised;
}
public static boolean showLoginDialog(Component parent) {
LoginPane loginPane = new LoginPane();
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPane = new JPanel(new GridBagLayout());
JButton okayButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
buttonPane.add(okayButton);
buttonPane.add(cancelButton);
panel.add(loginPane);
panel.add(buttonPane, BorderLayout.SOUTH);
JDialog dialog = new JDialog(SwingUtilities.windowForComponent(parent));
dialog.add(panel);
okayButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loginPane.authenticate();
if (loginPane.isAuthorised()) {
dialog.dispose();
}
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.setModal(true);
dialog.pack();
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
return loginPane.isAuthorised();
}
}
public static class SplashPane extends JPanel {
public SplashPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("This is a splash panel, put some nice graphics here"));
}
}
public static class MainPane extends JPanel {
public MainPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new JLabel("Welcome"));
}
}
}
You duplicated the JFrame, created a JFrame field f inside the JFrame.
Do not use static components like the button.
public class Frame1 extends JFrame implements ActionListener {
private final JButton login = new JButton("Login");
Frame1() {
setTitle("Login");
setSize(1000, 750);
setLocation(750, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
login.setBounds(250, 350, 150, 30);
add(login);
login.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == login) {
Frame2.frame2windown();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Frame1 login1 = new Frame1();
}
}
}
Use the swing/awt event queue (invokeLater) as on this thread window events are handled and dispatched further.
And Frame2:
public class Frame2 extends JFrame implements ActionListener {
private JButton logout = new JButton("Logout");
private JLabel jb1 = new JLabel("Hello And Welcome");
Frame2() {
setTitle("Logout");
setSize(1000, 750);
setLocation(750, 250);
setLayout(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jb1.setBounds(250, 150, 350, 30);
logout.setBounds(250, 350, 150, 30);
add(logout);
add(jb1);
logout.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
if (a.getSource() == logout) {
setVisible(false); // <--- ALL
}
}
public static void frame2windown() {
Frame2 f2 = new Frame2();
}
}
JFrame.setVisible does it all. Especially setVisible(true) should maybe even done after the constructor is called, so it always is last.
Another remark, dive into layout managers fast. Absolute layouts (null) are a PITA.
I'm trying to add an Image button to my GUI but all I get is a blank screen. Can anyone show me whats wrong with my code? This is what I have so far.
package fallingStars;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame
{
private JLabel label;
private JButton button;
private JPanel buttonPanel;
public static void startButton()
{
ImageIcon start = new ImageIcon("Start.png");
JButton play = new JButton(start);
play.setBounds(150,100,100,50);
}
public static void main(String args[])
{
GUI gui = new GUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 500);
gui.setVisible(true);
gui.setResizable(false);
gui.setTitle("Falling Stars");
JPanel panel = new JPanel();
startButton();
}
}
You have to add the JButton to the container using container.add(JButton);
You're going to get a blank screen if you don't actually add it :)
First of all just insert an ImageIcon in JLabel. If you want an image act as button, you have to add MouseListener & implement mouseClicked() as I did.
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class MyFrame extends JFrame{
private JLabel label;
private static MyFrame frame;
public MyFrame(){
initComponent();
label.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent arg0) {
JOptionPane.showMessageDialog(frame, "You just clicked the image");
}
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent arg0) {}
#Override
public void mouseReleased(MouseEvent arg0) {}
});
}
private void initComponent() {
this.setSize(400, 400);
this.setLocationRelativeTo(null);
label = new JLabel();
label.setIcon(new ImageIcon(getClass().getResource("res/image.png")));
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible (true);
}
public static void main(String[] args) {
frame = new MyFrame();
}
}
I want to check the event of panel class which is being added on the JFrame class. In this sample program there is a button on a panel.
I want to monitor the click event of the button from the source frame.
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class test extends JFrame implements ActionListener {
test() {
Container cp = this.getContentPane();
JButton b1 = new JButton("add");
cp.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("add")) {
panel1 frm = new panel1();
cp.add(frm);
}
}
public static void main(String args[]) {
test t1 = new test();
t1.show(true);
}
}
class panel1 extends JPanel {
panel1() {
JButton b1 = new JButton("ok");
add(b1);
}
}
You need to make the JButton available to the "out side" world some how.
I, personally, would be reluctant to make the button itself available, instead, I would allow the outside world the ability to to attach a ActionListener to it...
public class Test extends JFrame implements ActionListener {
public Test() {
Container cp = this.getContentPane();
JButton b1 = new JButton("add");
cp.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("add")) {
TestPane frm = new TestPane();
frm.addActionListener(...); // Add your new action listener here
cp.add(frm);
}
}
public static void main(String args[]) {
test t1 = new test();
t1.show(true);
}
}
public class TestPane extends JPanel {
private JButton b1;
public TestPane() {
b1 = new JButton("ok");
add(b1);
}
public void addActionListener(ActionListener listener) {
b1.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
b1.removeActionListener(listener);
}
}
whatever you put in frame it just put into the center of the frame. So use BorderLayout for this to be visible as below
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("add")) {
System.out.println("in actionPerformed");
panel1 frm = new panel1();
// this.removeAll();
add(frm,BorderLayout.NORTH);
this.validate();
}
}
I have a label and a button in a class called FrameTest, when i press the button, a method named buttonpressed get's executed from the class Test. In this buttonpressed method i will set a text to the label found in the FrameTest class.
The problem i have is that, the text for the label is not getting set. The reason is that i am creating a separate object to call the buttonpressed method;
public void actionPerformed(ActionEvent arg0) {
Test t = new Test();
t.buttonpress();
}
and i am creating a separate object in the main method of the Test class to create the UI.
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
The full code as follows;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
private FrameTest ft = this;
//private FrameTest frame;
/**
* Launch the application.
*/
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//FrameTest frame = new FrameTest();
//setVisible(true);
FrameTest frame = ft;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress();
}
});
contentPane.add(btnNewButton, BorderLayout.WEST);
//pack();
setLocationByPlatform(true);
}
}
Test Class
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
public void buttonpress(){
FrameTest f = new FrameTest();
f.writeLabel("Button was pressed");
}
1) Dont extend JFrame class unnecessarily.
2) dont use setContentPane() unless thats what you want. Rather just simply JFrame#add(..).
3) Steer away from EventQueue and use SwingUtilities block rather
4) Dont forget to call JFrame#pack(); before setting JFrame visible.
5) Java naming convention is CamelCase so buttonPress() is correct not buttonpress()
Here is an example I made (basically your code fixed):
Test.java: (This is the main class which will create an instance of your FrameTest and has the method to change JLabel text)
import javax.swing.SwingUtilities;
public class Test {
private static FrameTest f;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
f = new FrameTest();
f.mainScreen();
}
});
}
void buttonPress() {
f.writeLabel("Hello");
}
}
FrameTest.java: (This class will show the JFrame and create a new instance of class Test to call buttonPress()):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class FrameTest {
private JPanel panel;
private JLabel lblLabel;
private JFrame frame;
private void initComponents() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(0, 0));
lblLabel = new JLabel("LABEL");
panel.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonPress();
}
});
panel.add(btnNewButton, BorderLayout.WEST);
frame.add(panel);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public void writeLabel(String k) {
this.lblLabel.setText(k);
}
void mainScreen() {
initComponents();
}
}
Pass your FrameTest object to the buttonpress method and use it there, instead of creating a new object:
public void buttonpress(FrameTest f) {
f.writeLabel("Button was pressed");
}
Change the invocation of the method like so:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress(FrameTest.this);
}
});
You have to use FrameTest.this here, as you're inside of an anonymous class implementing ActionListener, so the normal this would reference to that anonymous class.
- Well the first approach is using Composition Principle, where you create an instance of FrameTest.java in Test.java class and then access the Label (use Getter Setters for this label in FrameTest) in FrameTest.java class using this instance.
- Second approach is a dirty and quick fix one, make the Label static in FrameTest.java class and directly set the value from Test.java class. Voila its done.....
- The reason your code is not working, cause you have created a very new instance of the FrameTest class. So now you either pass the FrameTest Object Reference Variable to buttonpress() method or make the label static.
Eg:
public class FrameTest extends JFrame {
private JPanel contentPane;
public static JLabel lblLabel;
.....
.....
}
Or
public void buttonpress(FrameTest f) {
f.writeLabel("Button was pressed");
}
/////////////////////////// Edited Part ///////////////////////////////////
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
private FrameTest ft = this;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = ft;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k) {
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress(FrameTest.this); // Passing the current object to
// the Test class
// You can use just "this" , but
// as we are in an Anonymous
// Inner Class here,
// we have to use
// "Class_name.this"
}
});
contentPane.add(btnNewButton, BorderLayout.WEST);
// pack();
setLocationByPlatform(true);
}
}
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
public void buttonpress(FrameTest f) { // Receiving the reference to the
// current frame, but remember
// THOUGH IT SEEMS that we are passing the
// reference but still in
// Here and in Java its always pass
// by copy.( ie pass by value).
f.writeLabel("Button was pressed");
}
}
Just change your Test class like below
package com.test;
public class Test {
private static FrameTest f;
public static void main(String[] args) {
f = new FrameTest();
f.mainScreen();
}
public void buttonpress() {
f.writeLabel("Button was pressed");
}
}
The actual problem was
You created a FrameTest variable f in main and shown the UI to user.
Then on button press you again created another FrameTest instance f, which does not map the original/first f
Now i treat the variable as a class variable and it works as expected
I am using the following code:
class ButtonPanel extends JPanel implements ActionListener
{
public ButtonPanel()
{
yellowButton=new JButton("Yellow");
blueButton=new JButton("Blue");
redButton=new JButton("Red");
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
Color color=getBackground();
if(source==yellowButton) color=Color.yellow;
else if (source==blueButton) color=Color.blue;
else if(source==redButton) color=Color.red;
setBackground(color);
repaint();
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(400,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Container contentPane=getContentPane();
contentPane.add(new ButtonPanel());
}
}
public class ButtonTest
{
public static void main(String args[])
{
JFrame frame=new ButtonFrame();
frame.show();
}
}
In actionperformed() I want to modify my panel and add some more component, is there any way to do this?
Yes.
Just call add() for the panel and then revalidate() and repaint();
but in actionperformed() i want to modify my panel and want to add some more component... Is there any way to do this....
Yes, you can add the components to the JPanel or "this" via the add(...) method, and you'll need to call revalidate() and then sometimes repaint() (especially if you also remove components) on the JPanel (this). But before you do this, if you haven't already done so, I think that you'll want to read the tutorials on using the layout managers so you can add components that are well situated.
hmmm I hard to comment anything, there are lots of mistakes, please start with this code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
public ButtonPanel() {
yellowButton = new JButton("Yellow");
yellowButton.addActionListener(this);
blueButton = new JButton("Blue");
blueButton.addActionListener(this);
redButton = new JButton("Red");
redButton.addActionListener(this);
add(yellowButton);
add(blueButton);
add(redButton);
setPreferredSize(new Dimension(400, 400));
}
#Override
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton) {
color = Color.yellow;
} else if (source == blueButton) {
color = Color.blue;
} else if (source == redButton) {
color = Color.red;
}
setBackground(color);
revalidate();
repaint();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("ButtonTest");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.add(new ButtonPanel());
frame.pack();
frame.setVisible(true);
}
});
}
}