我试图在单击单选按钮后在void方法中设置一个可以“重新选择”的按钮,但是该按钮的变量不能在actionPerformed方法中使用?
public class SelectionForm extends WindowAdapter implements ActionListener {
void select() {
JFrame frame = new JFrame("Selection Form");
JPanel leftPanel = new JPanel();
// JPanel has BoxLayout in x-direction
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
JRadioButton rd1 = new JRadioButton("Laptop");
JRadioButton rd2 = new JRadioButton("Desktop");
//submit button
JButton reselect = new JButton(" Re-select ");
reselect.setVisible(false);
// adding radio buttons in the JPanel
leftPanel.add(rd1);
leftPanel.add(rd2);
leftPanel.add(reselect);
rd1.addActionListener(this);
rd2.addActionListener(this);
//reselect button
reselect.addActionListener(this);
// add JLabels in the frame
frame.getContentPane().add(leftPanel);
frame.setSize(300, 200);
//frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Selected: " + e.getActionCommand());
if(e.getActionCommand().equals("Laptop") ||
(e.getActionCommand().equals("Desktop"))){
//OnlineShop oS = new OnlineShop();
// oS.onlineShop();
reselect.setVisible(true);
}
}
}
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Closing window!");
System.exit(0);
}
}
答案 0 :(得分:2)
将按钮的变量放在方法之外。那样:
public class SelectionForm extends WindowAdapter implements ActionListener
{
private JButton reselect;
void select() {
...
//submit button
reselect = new JButton(" Re-select ");
reselect.setVisible(false);
....
}
public void actionPerformed(ActionEvent e) {
System.out.println("Selected: " + e.getActionCommand());
if(e.getActionCommand().equals("Laptop") || (e.getActionCommand().equals("Desktop"))){
//OnlineShop oS = new OnlineShop();
// oS.onlineShop();
reselect.setVisible(true);
}
}
}
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Closing window!");
System.exit(0);
}
}