-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();あなたの例のために。

しかし、これは難しい方法です。メンバー メソッドを作成し、内部のすべてを初期化し、メイン メソッドでこの 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 に答える