How to navigate to previous card with button in card layout? - java

I have created a Java application in Netbeans, and used CardLayout to make three cards, which appear when I click three buttons.
All that is fine but I want to make a 'back' icon that, when clicked on, brings the previous card, so that if I am in the third card, clicking on the 'back' icon brings the second card, and from the second card to the first and so on.
The problem is that I want the program to know that we are in the second card for example, so clicking the 'back' icon brings the first card.
Also the back icon is on another panel in the same JFrame. I hope someone helps!
The icon on the lower left is the back button
and cards are located inside-the white portion.

I suppose somewhere in your project you already have the following code pieces:
For building the panel on the right (the one with the CardLayout):
JPanel panel1 = ...;
JPanel panel2 = ...;
JPanel panel3 = ...;
JPanel rightPanel = new JPanel();
CardLayout cardLayout = new CardLayout();
rightPanel.setLayout(cardLayout);
rightPanel.add(panel1);
rightPanel.add(panel2);
rightPanel.add(panel3);
and for building the "back" button (the one with the <- icon):
JButton backButton = ...;
Then all you need to add is the following:
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.previous(rightPanel);
}
});
or equivalently, if you prefer the concise lambda-syntax of Java 8:
backButton.addActionListener(e -> cardLayout.previous(rightPanel));

Related

Java GUI Switching panels using Card Layout

Ok I'm using Card Layout to switch panels from 1 panel to a 2nd panel & then to a 3rd panel. I have been looking online but I can't find exactly what I'm looking for. I want my panels to be in different classes and to switch back and forth using buttons to the different panels. I found a couple of sources for this but all the panels are added to a an original panel and then it switch's to different panels using the same buttons from the original panel.
(i.e) Panel 2 uses buttons from Panel 1 to switch to Panel 3 and Panel 3 uses buttons from Panel 1 to switch to Panel 4 and Panel 4 uses buttons from Panel 1 to switch back to Panel 2.
But the way it should be is panel 1 uses buttons from panel 1 to switch to panel 2, panel 2 uses buttons from panel 2 to switch to panel 3 and panel 3 should use buttons from panel 3 to switch to panel 1 which means there should be no need for a 4th panel.
My issue is I want to use different buttons to switch back and forth and not the same buttons as I intend to write extra code in each button for each panel. Because I basically want to create 3 panels so that once details are added to the register form and the user clicks register the details are added to the database and then it switch's to a login panel and closes the register panel.
The login panel then takes in a username and a password if they match an entry in the database and the user clicks login go to new panel and close login panel.
Now I have the registering and login stages done it's just switching from 1 panel to the next is the issue. Is there a way to use card layout so you switch to different panels using different buttons for each panel to do this or is there some other method used to do this.
I can append my code if needed. but its connected to a database so it won't compile without the database.
You definitly need a 4. panel witch contains the 3 panels and has the cardLayout.
To change the cards from cards you need to hand over an actionlistener with the method next(). I made a small not visual nice example to show what I mean ;-)
public class CardExample{
private class panel extends JPanel{
private panel(ActionListener alNext, String text){
JButton buttonNext = new JButton("next");
buttonNext.addActionListener(alNext);
JLabel textLabel = new JLabel(text);
this.add(textLabel);
this.add(buttonNext);
}
}
public CardExample(){}
public static void main(String[] args){
CardExample ce = new Cardexample();
ce.myGUI();
}
private void myGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(200, 200);
CardLayout cardLayout = new CardLayout();
frame.getContentPane().setLayout(cardLayout);
ActionListener al = e -> cardLayout.next(frame.getContentPane());
frame.getContentPane().add(new panel(al, "Panel 1"));
frame.getContentPane().add(new panel(al, "Panel 2"));
frame.getContentPane().add(new panel(al, "Panel 3"));
frame.setVisible(true);
}
}
Whether the buttons are on the same panel or a different panel is irrelevant.
The button just executes a method from the layout manager. You can use:
next(...) - to go the next panel in the CardLayout, or
show(...) - to show a specific panel in the CardLayout.
If you don't have access to the panel using the CardLayout you can easily get this. In the ActionListener for your button you can do something like:
JButton button = (JButton)event.getSource();
JPanel buttonPanel = (JPanel)button.getParent();
JPanel cardPanel = (JPanel)buttonPanel.getParent();
CardLayout layout = (CardLayout)cardPanel.getLayout();
layout.next(cardPanel);

In JAVA, JButton, Button displayed only when cursor is on the button and works even on clicking anywhere in contentPane

I am a beginner into Java and OOPS in general. Am studyin Head First Java to start, and studying GUI and Swing concepts in it.
The below code is just for understanding purposes.
On running the code, The frame window is displayed with Button, and when I expand it I can see Radio Button too.
Issues-
Button works till the window size is not more than the button size . As soon as I increase the window size even slightly more than button's dimensions, then the button is displayed only when cursor is on it.
I am changing window size using mouse.
Also even if I set Frame size to be more than button. say frame.setSize(800,800); then the button covers whole contentPane. and still behaves same way on resizing.
And the button responds to clicking on mouse, irrespective of where I click in the contentPane. It should respond only when i click directly on the button.
Please inform me why it is behaving this way.
And if possible,corrections in code or additions to correct this.
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
public class Test1 implements ActionListener {
JFrame frame = new JFrame("Frame");
JButton button = new JButton("Button!");
JRadioButton radio = new JRadioButton("VideoKilledTheRadioStar!",true);
int j=0;
public static void main(String[] args) {
Test1 t = new Test1();
t.method1();
}
public void method1()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setSize(100,100);
button.setBackground(Color.ORANGE);
frame.add(button);
frame.setSize(100,100);
frame.setVisible(true);
button.addActionListener(this);
frame.getContentPane().add(radio);
radio.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{j++;
button.setText("clicked .. " + j);
if(button.getBackground()==Color.ORANGE)
button.setBackground(Color.BLUE);
else
button.setBackground(Color.ORANGE);
}
}
P.S I did not know which segment of code is important or more relevant to this question, so I have put complete code.
You are trying to add the JButton button and JRadioButton objects in the default layout(BorderLayout) of the JFrame.
Whenevery you add a component to JFrame having BorderLayout the components goes in the Middle Section and BorderLayout center section has tendency to occupy the complete space, so to position elements properly you will need to specify the location as well as set the PreferredSize of the component.
frame.add(radio, BorderLayout.SOUTH);
component.setPreferredSize(Dimension);
You are adding the JButton button and the JRadioButton both in the BorderLayout.CENTER location so only one is being displayed. Components at this location will be sized in the X and Y axis.
The JButton only displays when the cursor is over it due to the fact that it has its own MouseListener used for painting.
Also, the statements
frame.add(myComponent);
and
frame.getContentPane().add(myComponent);
both add the component to the frame's ContentPane & are equivalent but the first is chosen for convenience.
Note that components cannot co-exist in the same position in a BorderLayout. You could place the button at the BorderLayout.SOUTH position (& add directly to the frame):
frame.add(radio, BorderLayout.SOUTH);
BorderLayout disregards any preferred sizes for components so you would have to use a different layout manager such as BoxLayout to maintain a fixed size JButton.
See more about Layout Managers

Getting a button to switch cards

I have a log in GUI that when i click a button, it gets text from the username and password, and if it is correct, it moves on to a new panel. i have the panel called optionPanel and i want the button to go to it specifically. all of the panels are set up as cards, so i can switch between them smoothly. I know how to make the button move to the next panel/card in the sequence, but i don't know how to make it go to the panel/card called optionPanel.
EDIT:
I dont know if im being very clear, but in my head, this makes perfect sense. please tell me how i can be more clear so i can get an answer.
THANKS
I think what you want is:
// Create the panels
JPanel loginPanel = new JPanel();
JPanel someOtherPanel1 = new JPanel();
JPanel someOtherPanel2 = new JPanel();
JPanel optionPanel = new JPanel();
JPanel someOtherPanel3 = new JPanel();
// Add them to a card layout
JPanel cards = new JPanel(new CardLayout());
cards.add(loginPanel, "loginPanel");
cards.add(someOtherPanel1, "someOtherPanel1");
cards.add(someOtherPanel2, "someOtherPanel2");
cards.add(optionPanel, "optionPanel");
cards.add(someOtherPanel3, "someOtherPanel3");
...
// Switch to the optionPanel
cards.getLayout().show(cards, "optionPanel");
don't you just need
cardLayout.show(cards, "optionPanel");
or am i missing something completely non-obvious?

Switching panels and passing data in Swing

I'm just starting out with Swing - I'm sorry if this question is hard to follow, but I feel like this is a very simple thing but it seems surprisingly hard in Swing.
I have a panel with two text fields and a submit button.
I've added a listener on the submit button, when it's clicked I validate the data and such.
Now, I want the frame to display a new panel - get rid of the current panel with the text fields and submit button, and instantiate a new one based on the data entered in the text fields.
How can I send this data back to the frame, so the frame can remove the current panel and replace it with a new, different panel, created with the data from the first panel.
Though it's not what I'm doing, it could be thought of like a login.
Display login panel
Panel gets username and password, validates (validation could be done higher up, too)
If validated, replace login panel with real content panel
This is surprisingly hard to figure out in Swing. Should I be defining my own event type and making the frame a listener for that event?
If I understood your question, you can use callback logic like this;
MyLoginPanel login = new MyLoginPanel(new IMyCallback(){
public void processLogin(){
//frame can remove the current panel and replace it with a new
}
});
MyLoginPanel extended from Jpanel with Constructor public MyLoginPanel(IMyCallback callback)
IMyCallback is an interface which has public void processLogin() method.
You could call callback.processLogin(); from LoginPanel
Does it work for you?
You should look at the java.awt.CardLayout. This Layout can handle multiple panels which are stacked on top of each other. And you can choose which panel should be the topmost and therefore visible.
The following code shows the relevent parts from the tutorial mentioned above:
//Where instance variables are declared:
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
and to switch the visible panel:
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL);

Rich swing radiobutton

Developing a desktop application based on Java + Swing I faced the problem of creating a radio button which instead of text next to it, should have and image or, say, another widget like a spinner.
Clicking on the image or the spinner should select also the corresponding radioButton.
Is it possible? if so, how?
To me, the JRadioButton with icon given for constructor doesn't seem to work; it replaces the "native radio button icon" with given icon. I think to original asked wanted for radio button with icon in addition to the "radio button icon".
There has been some debate on the behaviour at Sun bug database with Bug #4177248 but no changes have been made.
Instead, one could try JRadioButtonMenuItem, even though there will probably be some non-wanted behaviour with that?
Short evaluation for both JRadioButton and JRadioButtonMenuItem:
public class IconRadioButtonEval {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
// Use some arbitrary working URL to an icon
URL url =
new URL(
"http://mikeo.co.uk/demo/sqlspatial/Images/RSS_Icon.png");
Icon icon = new ImageIcon(url);
JRadioButton button = new JRadioButton(icon);
panel.add(new JLabel("RadioButton with icon:"));
panel.add(button);
panel.add(new JLabel("RadioButtonMenuItem with icon:"));
panel.add(new JRadioButtonMenuItem(icon));
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Justin's suggestion for another component next to JRadioButton with empty string should probably work well in most cases.
Well, there is a constructor for JRadioButton that takes an Icon. You can use that to make it have an icon next to it.
JRadioButton(Icon icon)
-- Creates an initially unselected radio button with the specified image but no text.
Otherwise, it is fairly easy to make the JRadioButtons text empty, and place another component next to it. Then you will need to add a Listener to that component, so that the JRadioButton gets clicked if the other component gets clicked.

Categories