-1

您好我试图创建一个程序,当单击按钮时,它将使用 CardLayout 切换 JPanel。

资源:

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CardDemo extends JFrame implements ActionListener {

CardLayout cl;
JPanel p1, p2, p3, p4, p5;
JButton b1, b2, b3;

public static void main(String args[]) {
    CardDemo d = new CardDemo();

p1 = new JPanel();
    p1.setBackground(Color.red);   //the top panel
    p2 = new JPanel();
    p2.setBackground(Color.blue);  //bottom panel - we never actually see this

    JButton b1 = new JButton("One");    //create the buttons with labels
    JButton b2 = new JButton("Two");
    JButton b3 = new JButton("Three");

    b1.addActionListener(d);     //this object listens for button clicks
    b2.addActionListener(d);
    b3.addActionListener(d);

    p1.add(b1);       //uttons added to the top panel
    p1.add(b2);
    p1.add(b3);

    cl = new CardLayout();     //create the CardLayout object
    p2.setLayout(cl);          //set p2 to use a CardLayout

    JPanel p3 = new JPanel();         //make the three panels that we
    p3.setBackground(Color.green);    //will put into the CardLayout panel
    JPanel p4 = new JPanel();
    p4.setBackground(Color.yellow);   //give them different colours
    JPanel p5 = new JPanel();
    p5.setBackground(Color.cyan);

    p2.add(p3, "One");
    p2.add(p4, "Two");
    p2.add(p5, "Three");

d.setSize(500,400);
d.setVisible(true);
d.getContentPane().setLayout(new GridLayout(2,2));
d.getContentPane().add(p1);
d.getContentPane().add(p2);
}

/** The actionPerformed method handles button clicks
 */
public void actionPerformed(ActionEvent e) {
    String buttonLabel = ((JButton)e.getSource()).getText();
    cl.show(p2, buttonLabel);
}
}

当我编译代码时,我得到了错误,我已经尝试了一切来让它工作,但似乎无法弄清楚我哪里出错了。顺便说一句,我是 Java 的初学者,我可能在某个地方犯了一个小小的业余错误。

错误信息如下:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-   static variable p1 cannot be referenced from a static context
at CardDemo.main(CardDemo.java:22)
Java Result: 1
4

1 回答 1

2

您正在尝试在静态方法中分配一个成员变量(主要在这个方法中)。那是行不通的。实例变量只能在实例上分配。

p1 = new JPanel(); //p1 is a member variable

你应该这样做: d.p1 = new JPanel();对于你的例子。

但这是艰难的道路。我建议创建一个成员方法并初始化其中的所有内容并在您的 main 方法中调用此 init 方法。

public static void main(String[] args) {
    CardDemo cd = new CardDemo();
    cd.init();
}

private void init() {
   p1 = new JPanel();
...
于 2013-11-02T22:18:33.543 回答