0

你能帮我这个代码吗?我怎样才能使它在单击按钮时出现第二个按钮?我已经添加了动作监听器并创建了第二个按钮,但我似乎无法做到这一点。太感谢大家了!!!

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
    
    public static void main(String[] args) {

        JFrame frame = new JFrame("Skeleton");
        JPanel panel = new JPanel();
        JButton button = new JButton("This is a button.");
        JButton button2 = new JButton("Hello");

        frame.setSize(600,600);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        
        frame.setContentPane(panel);
        panel.setLayout(new FlowLayout());
        panel.add(button);        
    }

    public void actionPerformed(ActionEvent e) {

        panel.add(button2); //Whenever I compile with this line 
                            //of code inserted, it tells
                            //me cannot find Button 2 
    }    
}

再次感谢!

4

1 回答 1

1

您的代码有很多问题。首先,您无法在main()创建类实例并从那里调用该方法所需的方法中创建/构建您的 UI。

为了让您能够引用panel并且button2您需要使它们成为类对象而不是 UI 方法内的本地对象。

而且您至少需要ActionListenerbutton

最后你只需要调用panel.revalidate()面板来显示添加的按钮:

    public class Skeleton extends JFrame implements ActionListener {

    public static void main(String[] args) {

        new Skeleton().buildUI();
    }

    JPanel panel;
    JButton button2;

    public void buildUI() {

        JFrame frame = new JFrame("Skeleton");
        panel = new JPanel();
        JButton button = new JButton("This is a button.");
        button2 = new JButton("Hello");

        frame.setSize(600, 600);
        frame.setResizable(false);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        frame.setContentPane(panel);

        panel.setLayout(new FlowLayout());
        panel.add(button);

        button.addActionListener(this);

        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        panel.add(button2); 
        panel.revalidate();

    }
  }
于 2013-07-06T21:35:39.263 回答