我如何将我的代码更改为cardLayout

时间:2015-02-19 21:14:05

标签: java jpanel cardlayout

package garage;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author Jela
 */
public class VehicleParts extends JPanel {

    public VehicleParts() {
        JPanel card0 = new JPanel();
        //card0.setPreferredSize(new Dimension(800, 600));
        JPanel card1 = new JPanel(new BorderLayout());
        JPanel card2 = new JPanel(new BorderLayout());
        JPanel card3 = new JPanel(new BorderLayout());

        JLabel zero = new JLabel("0");
        JLabel one = new JLabel("1");
        JLabel two = new JLabel("2");
        JLabel three = new JLabel("3");

        card0.add(zero);
        card1.add(one);
        card2.add(two);
        card3.add(three);

        card1.setVisible(false);
        card2.setVisible(false);
        card3.setVisible(false);
        card0.setVisible(false);


        JButton buttonZero = new JButton("Repair");
        JButton buttonOne = new JButton("Parts");
        JButton buttonTwo = new JButton("Stock");
        JButton buttonThree = new JButton("Supplier");

        //JButton buttonback = new JButton("Parts");

        buttonZero.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                card0.setVisible(true);
                card1.setVisible(false);// shows card1 when button is clicked                    
                card2.setVisible(false);
                card3.setVisible(false);
            }
        });

        buttonOne.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                card1.setVisible(true);// shows card1 when button is clicked                    
                card2.setVisible(false);
                card3.setVisible(false);
                card0.setVisible(false);
            }
        });

        add(buttonZero);
        add(buttonOne);
        add(buttonTwo);
        add(buttonThree);

        add(card0);
        add(card1);
        add(card2);
        add(card3);



    }

}

我不知道如何将此代码更改为CardLayout。如果有人能给我提示我如何改变它,请告诉我。这不是我的主要课程。我尝试过cardlayout,但每当我使用它时,我再也看不到我的按钮了。

1 个答案:

答案 0 :(得分:0)

为了确保使用所有卡片可以看到按钮,您只需将面板分成两个面板 - 一个面板将包含按钮,另一个面板将包含这些卡片。

所以 - 你的主面板(VehicleParts)将有一个 BorderLayout

您可以添加两个面板。一个是卡片面板。它将有一个 CardLayout 。使卡片面板参考变量最终,以便您可以从按钮'事件监听器(匿名类)。虽然卡片面板本身具有卡片布局,但您可以使用BorderLayout.CENTER将其添加到主面板。

另一个面板是按钮面板。例如,它可以有GridLayout。使用BorderLayout.SOUTH将其添加到主面板,将其放在底部。

将卡添加到面板。不要忘记给他们起名字。

然后创建按钮,并在每个按钮的监听器中,使用CardLayout.show()方法更换卡片。将每个按钮添加到按钮面板。