Java 将按钮设置为可见
我试图在单击单选按钮后,将按钮设置为在void方法中可见的“重新选择”,但按钮的变量不能用于actionPerformed方法Java 将按钮设置为可见,java,swing,scope,visibility,jbutton,Java,Swing,Scope,Visibility,Jbutton,我试图在单击单选按钮后,将按钮设置为在void方法中可见的“重新选择”,但按钮的变量不能用于actionPerformed方法 public class SelectionForm extends WindowAdapter implements ActionListener { void select() { JFrame frame = new JFrame("Selection Form"); JPanel leftPanel = new J
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);
}
}
将按钮的变量置于方法之外。就像这样:
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);
}
}
如果你想成为一名成功的程序员,你需要了解基础知识,包括变量范围。这是你的第一个java程序吗?谢谢,你也可以看看这个吗?