java swings to display different panel in same frame (java) - java

the below given is a java class which get invoked on clicking "next" button in first frame .and i send a parameter is i send getContentPane() to this given below program , here ill access the parameter and set its visibality to false , here i use "Back" button to go to previous page dats for ma first frame , but on clicking Back its not showing the previous frame for me , plz help me out with dis
its just a simple program , if i need to take some text input from second frame and again i need to come back to home screen so, how can i achieve this in this program
public class firstframe extends JFrame{
public firstframe()
{
getContentPane().setLayout(null);
JButton next=new JButton("Next");
next.setBounds(100,100,100,100);
getContentPane().add(next);
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
Container c=getContentPane();
}
new signup(c);
});
}
public static void main(String ar[]){
firstframe f=new firstframe();
f.setVisible(true);
f.setSize(1365,740);
f.show();
}
}
public class signup extends JFrame{
public signup(Container d)
{
final Container c=d;
c.setVisible(false);
final Container e;
e=c.getParent();
e.setLayout(null);
JButton back=new JButton("Back");
back.setBounds(100,100,100,100);
e.add(back);
e.setVisible(true);
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
e.setVisible(false);
d.setVisible(true);
}
});
}
}//

Sorry, but your code style is not good. Too many unnecessary assignments which prevents me to understand code meaning and too short variables names.
Look what you do. In signup() method you assign e=c.getParent(); it means e is parent component of c and d. Then in back action listener you make e unvisible and try to make d visible. But so as e is parent of d, d never becomes visible while its parent is unvisible.
Quick fix for this code is change back button action listener to
back.setVisible(false);
d.setVisible(true);
And of course make back final
final JButton back=new JButton("Back");

Related

ActionListener interface

public class myWindow extends JFrame implements ActionListener{
if i have this code my class will be a JFrame where where I can add component and add actionlistener to them in my constructor as followed
public MyWindow()
{
JButton b = new Jbutton("button");
b.addActionListener(this);
}
this keyword will work as an anonymous actionlistener object(which is my class) right ?
later on i will override the actionPerformed method with the heading:-
public void ActionPerformed(ActionEvent ae)
{ :
:
}
I really have a big confusion here .. my book says "the listener object invokes an event handler method with the event as an argument "
listener object : this
event handler method :ActionPerformed(ActionEvent ae)
argument: my event is the JButton b .. how come when it's not of EventAction type ? And if so why we are using :
ae.getActionCommand();
I thought it's a method to tell which component fired the event,why we need it when the component is passed as an argument then?
this keyword will work as an anonymous actionlistener object(which is my class) right ?
No this will be an Object of class which is implementing the actionsListener. In your case it is "MyWindow".
my event is the JButton b .. how come when it's not of EventAction type ? And if so why we are using :
JButton b is a component not an event. Events describes the changed in state of the source. When users interact with GUI, events are generated like clicking of button, moving the mouse.
Reference from Click here
Event Handling is a mechanism that controls the event and decides what should happen if an event occurs.
Steps involved in event handling:-
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.
I thought it's a method to tell which component fired the event,why we need it when the component is passed as an argument then?
Now you would have understood that there could be many buttons registered to the same ActionsListerner. Now to perform different actions for different events,
e.getActionCommand() comes handy, it will tell you which button is the source of firing the event.
Hope this helps.
I have tried to give you can example of a simple JButton program.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonSwing {
private int numClicks = 0;
public Component createComponents() {
//Method for creating the GUI componenets
final JLabel label = new JLabel("Clicks: " + "0"); //final so that i can access inside inner class
JButton button = new JButton("Simple Button");
button.addActionListener(
//inner class for ActionListener. This is how generally it is done.
new ActionListener() {
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText("Clicks: " + numClicks);
System.out.println(e.getActionCommand());
System.out.println(e.getModifiers());
System.out.println(e.paramString());
}
}
);
JPanel pane = new JPanel(); //using JPanel as conatiner first.
pane.setLayout(new FlowLayout());
pane.add(button); // adding button to the JPanel.
pane.add(label); // adding label to the JPanel.
return pane;
}
public static void main(String[] args) {
JFrame frame = new JFrame("SwingApplication");
ButtonSwing obj = new ButtonSwing();
Component contents = obj.createComponents();
frame.getContentPane().add(contents);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack(); //It will cause the window to be sized to fit the preferred size
//and layouts of its subcomponents.
frame.setVisible(true);
}
}
Your JButton is a component not an event. Events are generated by some action on components in this case When you click your button, an ActionEvent will be fired and it will be passed to all the listeners who subscribed to that event in this case it is your MyWindow object which is serving as an ActionListener

Close windows without closing Application

Good afternoon!
I have this code:
private static class ClickListener implements ActionListener {
public ClickListener() {
}
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame();
JLabel label = new JLabel("Opção Indisponivel");
JPanel panel = new JPanel();
frame.add(label, BorderLayout.CENTER);
frame.setSize(300, 400);
JButton button = new JButton("Voltar");
button.addActionListener(new CloseWindowListener());
panel.add(button);
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
private static class CloseWindowListener implements ActionListener {
public CloseWindowListener() {
}
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
What I want to do is when i click on the button "voltar" (which is in another window, not on the "main" one as you can see) it closes the windows but not the app itselft. The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?
EDIT: Changed JFrame to JDialog but still no sucess. Both windows are shutdown.
Thanks in advance,
Diogo Santos
The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?
You can access the component that generated the event. Then you can find the window the component belongs to. This will give you generic code to hide any window:
//setVisible(false);
JButton button = (JButton)e.getSource();
Window window = SwingUtilities.windowForComponent(button);
window.setVisible(false);
You can also check out Closing an Application. The ExitAction can be added to your button. Now when you click the button it will be like clicking the "x" (close) button of the window. That is whatever default close operation your specify for the window will be invoked.

how to make a button run a loop in java

I understand how to create a button and it's application in Java. Would anyone be able to show me the code to be able to make the button in the code below be able to print something as simple as hello world in the terminal. I am using bluej if that is of any matter. I am very sorry I am a beginner coder.
JButton button = new JButton();
button.setActionListener(e -> System.out.println("Clicked"));
This uses a lambda expression. Inside it, you can add as much code as you like, but add it between {} if it's more than a line.
More on buttons here
You need a listener for your button.
JButton button= new JButton("Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Hello World");
}
});
the button will 'listen' for the action and preform whatever task you define for it.
ActionListener is what you are looking for. There is a very nice guide on Oracle's website. You should look into this tutorial and understand different ways of creating ActionListeners. I will give you a simple example which doesn't involve Anonymous Classes because I am not sure of how much you know about them.
public class Frame extends JFrame implements ActionListener {
public Frame() {
super("Test"); // calling the superclass
setLayout(new FlowLayout()); // creating a layout for the frame
setDefaultCloseOperation(EXIT_ON_CLOSE);
// create the button
JButton jbTest = new JButton("Click me!");
/* 'this' refers to the instance of the class
because your class implements ActionListener
and you defined what to do in case a button gets pressed (see actionPerformed)
you can add it to the button
*/
jbTest.addActionListener(this);
add(jbTest);
pack();
}
// When a component gets clicked, do the following
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Hello!");
}
}

Performing action when closing JFrame

In my program I have a main JFrame that holds a button. When this button is clicked a new JFrame appears in which I can change some information. Whenever I finish editing I press a save button on the new JFrame which saves the changes and disposes the JFrame. Now when this is done, I'd like to perform an action in the main JFrame as well, but only if something changed. If I open the new JFrame and just close it again without using the save button, I don't want to do anything in the main frame.
I've tried searching the web for a solution, but just don't seem to be anything useful out there..
An example of the code I've got so far:
Main Frame...
public class MainFrame extends JFrame
{
public MainFrame()
{
super("Main Frame");
JButton details = new JButton("Add Detail");
add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
new DetailFrame().setVisible(true);
}
});
}
}
Detail Frame...
public class DetailFrame extends JFrame
{
public DetailFrame()
{
super("Detail Frame");
JButton save = new JButton("Save");
add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
dispose();
}
});
}
}
So when I click the "Save" button on the Detail Frame, I want to do something in the Main Frame, whereas when the "x" is clicked on the Detail Frame, I don't want to do anything..
Hope someone is able to help me, and sorry for my english..
You can pass a MainFrame handle to the DetailFrame constructor. Then, on clicking the Save button, the DetailFrame would call a function in MainFrame and pass the changes to it.
Another way is to create a public boolean variable in DetailFrame and set it to true when the Save button is clicked. This way MainFrame will know whether the DetailFrame was closed or Save'd.
EDIT: Some more ideas:
Use JDialog instead of JFrame. JDialog.setVisible is modal, i.e. it will block the calling function until the dialog is closed; this way you can process the results of the dialog in the same "Details" button listener.
To access the dialog after it is called, store the dialog in a separate variable. First construct the dialog, then show it, and then process the result by analyzing its variables.
Store the results of editing in other public variables of DetailFrame (or let's call it DetailDialog). This should happen only when the "Save" button is clicked. This may even allow to go without the boolean variable (depends on the types of values you are editing).
DetailDialog dlg = new DetailDialog();
dlg.setVisible(true);
if(dlg.approvedResult != null) {
// process the result...
}
EDIT: Sorry, JDialog is not modal by default. Need to call a special super constructor to make it modal.
Also, here you will have to pass the reference to MainFrame to the dialog constructor, but you still can declare it as a simple JFrame and avoid unnecessary dependencies.
To get the reference to the enclosing MainFrame from within the anonymous ActionListener, use MainFrame.this.
To be able to change the button text after it was created, you will have to store the button in a member variable.
Main Frame...
public class MainFrame extends JFrame
{
private JButton details = new JButton("Add Detail");
public MainFrame()
{
super("Main Frame");
getContentPane().add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
DetailDialog dlg = new DetailDialog(MainFrame.this);
dlg.setVisible(true);
if(dlg.approved){
details.setText("Edit Detail");
}
}
});
}
}
Detail Dialog... (not Frame)
public class DetailDialog extends JDialog
{
public boolean approved = false;
public DetailDialog(JFrame parent)
{
super(parent,"Detail Dialog",true); // modal dialog parented to the calling frame
JButton save = new JButton("Save");
getContentPane().add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
approved = true;
dispose();
}
});
}
}
Create the detail frame in the main frame, and add a windowlistener to it, using the windowadapter class. Implement the windowclosing event by checking for changes, handle those, and then dispose the detail frame. This is all done in the mainframe.
The detail frame should have do nothing on close set to prevent the detail frame being disposed before you recorded the changes.
You may wish to implement checking for changes in the detailframe as a method returning a class holding the interesting data. That way your windowlistener can be small an to the point.
Forget the 2nd JFrame. use a modal dialog instead. It will block input until dismissed. Once dismissed, the only thing to do is decide whether to update the original data. JOptionPane has some inbuilt functionality that makes that easy. If the user presses Cancel or the esc key, the showInputDialog() method will return null as the result.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class EditInfo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("Uneditable");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout(10,10));
final JTextField tf = new JTextField("Hello World!", 20);
tf.setEnabled(false);
p.add(tf, BorderLayout.CENTER);
JButton edit = new JButton("Edit");
edit.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
String result = JOptionPane.showInputDialog(
f,
"Edit text",
tf.getText());
if (result!=null) {
tf.setText(result);
}
}
} );
p.add(edit, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10,10,10,10));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If it is necessary to edit a number of fields all at once in the JOptionPane, use a JPanel to contain them all, and put them in a showMessageDialog() call. Check the integer based return result to determine if the user OK'd the changes.

How to disable javax.swing.JButton in java?

I have created a swings application and there is a "Start" button on the GUI. I want that whenever I clicked on that "Start" button, the start button should be disabled and the "Stop" button be enabled.
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
startButton.setEnabled(false);
stopButton.setEnabled(true);
But the above code is not creating the desired affect on the GUI.
Is the above code correct for what I want to do?
It's not working with "repaint()" too.
Edit:
The code is very long so I can't paste all the code. I can tell, though, more about the code.
In the "ActionPeformed" method of "start" button, after calling the above two statements, I am executing a "SwingWorker" thread.
Is this thread creating any problem?
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.
You can add a simple ActionListener like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.
The code is very long so I can't paste
all the code.
There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.
You need to create a SSCCE to post on the forum.
So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.
Learn how the basice work first before writing a 200 line program.
Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.
This works.
public class TestButton {
public TestButton() {
JFrame f = new JFrame();
f.setSize(new Dimension(200,200));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
final JButton stop = new JButton("Stop");
final JButton start = new JButton("Start");
p.add(start);
p.add(stop);
f.getContentPane().add(p);
stop.setEnabled(false);
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(true);
stop.setEnabled(false);
}
});
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
stop.setEnabled(true);
}
});
f.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
new TestButton();
}
}

Categories

Resources