代码功能为:用两个按钮来控制组件的层次,一个是“往上一层”,另一个是“往下一层”,蓝色的代码为错误的!
package myswing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JLayeredPaneDemo implements ActionListener {
//JLabel label1 = null;
JButton jb = null;
public JLayeredPaneDemo() {
JFrame jf = new JFrame("JLayerdPaneTest");
Container cp = jf.getContentPane();
JLabel label1 = new JLabel("左Label", JLabel.CENTER);
label1.setVerticalAlignment(JLabel.TOP);
label1.setBackground(Color.red);
label1.setForeground(Color.black);
label1.setOpaque(true);
label1.setBounds(20, 20, 150, 150);
cp.add(label1, new Integer(10), 1);
JLabel label2 = new JLabel("右Label", JLabel.CENTER);
label2.setVerticalAlignment(JLabel.TOP);
label2.setBackground(Color.green);
label2.setForeground(Color.black);
label2.setOpaque(true);
label2.setBounds(50, 50, 150, 150);
cp.add(label2, new Integer(10), 2);
jb = new JButton("往上一层");
jb.addActionListener(this);
cp.add(jb);
jb = new JButton("往下一层");
jb.addActionListener(this);
cp.add(jb);
jf.pack();
jf.setVisible(true);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
if (((JButton) e.getSource()).getText() == "往上一层")
JLayeredPane.setLayer(label2, new Integer(15));
else
JLayeredPane.setLayer(label1, new Integer(5));
}
public static void main(String[] args) {
new JLayeredPaneDemo();
}
}
错误提示:label1 (label2)cannot be resolved。。。个人认为他是说label1(label2)是局部变量。。但是声明为类变量也有问题。。。。错误提示:Cannot make a static reference to the non-static method setLayer(Component, int) from the type JLayeredPane