I have here a sample of a program here. I have 3 panels and I want to stop the user in pressing the previous button if the panel is in panel_1
and also stop at the
"Is there any way to like disable the button if the user is at the start of the panel or at end of the panel?"
According to How to Use CardLayout and CardLayout API there's no direct way to do it.
But you can implement this feature easily keeping an int variable with current card number and checking its value againts 0 (for first card) or container's component count (for last card). For instance:
public class GridBagLayoutDemo { // note code convention!
int currentCard = 0;
Action backAction, nextAction;
...
public GridBagLayoutDemo() {
...
backAction = new AbstractAction("< Back") {
@Override
public void actionPerformed(ActionEvent e) {
currentCard--;
GridBagLayoutDemo.this.evaluateActions();
}
};
nextAction = new AbstractAction("Next >") {
@Override
public void actionPerformed(ActionEvent e) {
currentCard++;
GridBagLayoutDemo.this.evaluateActions();
}
};
JButton btnBack = new JButton(backAction);
...
JButton btnNext = new JButton(nextAction);
...
}
private void evaluateActions() {
backAction.setEnabled(currentCard > 0);
nextAction.setEnabled(currentCard < container.getComponentCount() - 1);
}
...
}
Looking closer at CardLayout
implementation, it would be really easy to have this feature implemented by default (unless I'm missing something):
public class CardLayout implements LayoutManager2,
Serializable {
/*
* This creates a Vector to store associated
* pairs of components and their names.
* @see java.util.Vector
*/
Vector vector = new Vector();
/*
* Index of Component currently displayed by CardLayout.
*/
int currentCard = 0;
...
/*
* Hypothetical implementations
*/
public boolean isDisplayingFirstCard() {
return currentCard == 0;
}
public boolean isDisplayingLastCard() {
return currentCard == vector.size() - 1;
}
}
Don't know why they didn't provide such useful feature.
Check out Card Layout Actions for a simple extension of the CardLayout
.
It provides "Next" and "Previous" actions that you can use to create buttons or menu items and the Actions will automatically be disabled when you are at the end/beginning of the cards.