有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

awt在Java中以CardLayout显示面板

我编写了下面的代码,用于显示三个面板,具体取决于单击了三个按钮中位于底部的按钮

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class cart extends Frame implements ActionListener {

Panel cardPanel;
Panel firstP, secondP, thirdP;
Panel buttonP;

Button b1, b2, b3;

CardLayout cLayout;

cart() {
    cardPanel = new Panel();
    cLayout = new CardLayout();
    cardPanel.setLayout(cLayout);

    firstP = new Panel();
    firstP.setBackground(Color.blue);

    secondP = new Panel();
    secondP.setBackground(Color.red);

    thirdP = new Panel();
    thirdP.setBackground(Color.yellow);

    b1 = new Button("first");
    b2 = new Button("Second");
    b3 = new Button("Third");

    b1.addActionListener(this);
    b2.addActionListener(this);
    b3.addActionListener(this);

    buttonP = new Panel();
    buttonP.add(b1);
    buttonP.add(b2);
    buttonP.add(b3);

    add(buttonP, BorderLayout.SOUTH);
    add(cardPanel, BorderLayout.CENTER);

    cardPanel.add("first", firstP);
    cardPanel.add("second", secondP);
    cardPanel.add("third", thirdP);

    setSize(400, 500);
    setVisible(true);

    addWindowListener(new WindowAdapter() {
        public void WindowClosing(WindowEvent e) {
            System.exit(0);
        }

    });

}// constructor ends here

public void actionPerformed(ActionEvent e) {

    if (e.getSource() == b1) {
        cLayout.show(cardPanel, "firstP");

        System.out.print("first");
    }

    else if (e.getSource() == b2) {
        cLayout.show(cardPanel,"secondP");

        System.out.print("second");
    }

    else if (e.getSource() == b3) {
        cLayout.show(cardPanel, "thirdP");

    }

}

public static void main(String args[]) {
    new cart();

}

 }

处理这三个按钮的方法会被调用,并且它们会打印到终端上单击哪个按钮,但面板不会改变。这只是第一个可见的P


共 (0) 个答案