0

このコードを教えてください。ボタンをクリックすると 2 つ目のボタンが表示されるようにするにはどうすればよいですか? すでにアクションリスナーを追加して2番目のボタンを作成しましたが、それができないようです。みんな本当にありがとう!!!

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 を作成/構築することはできません。

また、参照できるようにするために、UI メソッド内のローカル オブジェクトではなくクラス オブジェクトにする必要がありますpanelbutton2

そして、少なくとも を に追加する必要がありActionListenerますbutton

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 に答える