Adding text to a label from another class - Simple Logic Issue - java

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

Related

How do you close a JFrame window without closing another one?

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.

How to Dispose an opened Jframe from Other

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

Void is invalid for the variable main?

How do i fix the error, Void is invalid for the variable main? I tried looking this up online but couldn't find anything. Also I am kind of new to this so please take it easy on me. I am learning as I go.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public Text()
{
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt);
jp.add(jt2);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
jl.setText(input);
}
});
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
String input2 = jt2.getText();
jl.setText(input);
jl.setText(input2);
int day = Integer.parseInt(input2);
if ((input.equals("Test")) && (input2.equals(day >= 26)))//||(input2.equals("27")))))
JOptionPane.showMessageDialog(null, "" , "" ,JOptionPane.PLAIN_MESSAGE,aries);
}
});
add(jp);
}
}
}
You have placed your main method inside the constructor for class Text. It belongs outside the constructor, at the same level as the constructor. Move it outside the constructor.
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
...
}
public Text()
{
...
}
...
}
Java doesnt allow methods to be defined within other methods. Move the main method out of the Text constructor and remove the semi-colon which is terminating the statement early.
In addition you have a number of methods (e.g. setTitle and setVisible) which belong to the JFrame - these need to be moved to an instance code block to make them are accessible.
public class Text extends JFrame {
JPanel jp = new JPanel();
JLabel jl = ...
public Text() {
setTitle("Tutorial");
setVisible(true);
...
add(jp);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Text().setVisible(true);
}
});
}
}
Delete the ; after the main method declaration:
public static void main (String[] args);
^-------- Delete this
And put the main method out of the constructor:
public Text() {
...
}
public static void main(...) {
...
}

check event of panel in the main java class

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

why does my button not appear on my JPanel - Java

Or maybe my JPanel is not appearing at all.
I am trying to have a JPanel at the bottom of the screen that hold several buttons. Can someone set me strait?
public class MyAWTMenu extends java.awt.Frame// implements ActionListener
{
public void init() {
setBackground( Color.white );
JPanel bottom = new JPanel();
bottom.setBackground(Color.BLACK);
JButton b1 = new JButton("test");
b1.setVisible(true);
bottom.add(b1);
bottom.setVisible(true);
add(bottom,BorderLayout.CENTER);
}
public static void main( String args [] ) {
MyAWTMenu objAppFrame = new MyAWTMenu();
objAppFrame.addWindowListener( //Register an anonymous class as a listener.
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
objAppFrame.init();
objAppFrame.setSize( 760, 378);
objAppFrame.setVisible( true );
}
I'd better rewrite it as follows:
public class FooFrame extends JFrame {
public FooFrame() {
// your code, copy/pasted
setBackground(Color.white);
JPanel bottom = new JPanel();
bottom.setBackground(Color.BLACK);
JButton b1 = new JButton("test");
bottom.add(b1);
add(bottom, BorderLayout.CENTER);
// set size & pack
Dimension size = new Dimension(400, 400);
setPreferredSize(size);
setMinimumSize(size);
pack();
setLocationRelativeTo(null);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FooFrame().setVisible(true);
}
});
}
}
add(bottom,BorderLayout.SOUTH);
in your init()
Here's your code that i was running. It seems to work fine for me. I did add a call to pack();
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MyAWTMenu extends java.awt.Frame// implements ActionListener
{
public void init() {
setBackground(Color.white);
JPanel bottom = new JPanel();
bottom.setBackground(Color.BLACK);
JButton b1 = new JButton("test");
bottom.add(b1);
bottom.setVisible(true);
add(bottom, BorderLayout.SOUTH);
pack();
}
public static void main(String args[]) {
MyAWTMenu objAppFrame = new MyAWTMenu();
objAppFrame.addWindowListener( //Register an anonymous class as a listener.
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
objAppFrame.init();
objAppFrame.setSize(760, 378);
objAppFrame.setVisible(true);
}
}

Categories

Resources