I have this code that I am referencing in Java Eclipse:
public class ClassWithButton extends JFrame{
private final JPanel Your_Panel_name;
public void enableButtons() {
for (Component c : Your_Panel_name.getComponents()) {
if (c instanceof JButton)
c.setEnabled(true);
}
}
}
Then there is a class which implements ActionListener.java
public class ActionListenerImpl implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
I have a button in a class that extends JFrame and I have a panel in which I disabled two buttons on it. I have another class that extends ActionListener, when I press another button on the panel, I want the 2 disabled buttons to be enabled, how would I go about doing so?
I would suggest you define your own Listener
class to achieve your goal.
First, define a Listener
class.
public interface ButtonEnabledListener {
void buttonEnabled(boolean isEnabled);
}
Second, implement this Listener
for your JFrame
or JPanel
class.
public YourJPanel extends JPanel implements ButtonEnabledListener {
void buttonEnabled(boolean isEnabled) {
for (JButton button : buttons) {
button.setEnabled(isEnabled);
}
}
}
Last, in another class, pass in your frame or panel and fire the event. Since your class implements ActionListener, so fire the event in the implemented method.
public AnotherClass implements ActionListener {
JButton yourButton;
ButtonEnabledListener listener;
public AnotherClass(ButtonEnabledListener yourPanel) {
yourButton = new JButton("enable buttons in my panel");
yourButton.addActionListener(this);
listener = yourPanel;
}
public void actionPerformed(ActionEvent e) {
listener.buttonEnabled(true);
}
}
With the code you've given, here's a quick example of how the reference works, but this is not the way I would implement it.
public class ClassWithButton extends JFrame{
private final JPanel Your_Panel_name;
ActionListenerImpl act;
JButton otherButton;
public ClassWithButton()
{
act = new ActionListenerImpl(this);
otherButton = new JButton("Click to enable");
otherButton.addActionListener(act);
}
public void enableButtons() {
for (Component c : Your_Panel_name.getComponents()) {
if (c instanceof JButton)
c.setEnabled(true);
}
}
}
public class ActionListenerImpl implements ActionListener{
ClassWithButton b;
public ActionListenerImpl(ClassWithButton b)
{
this.b = b;
}
public void actionPerformed(ActionEvent e){
b.enableButtons();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.