Swing 中控件添加问题, 求解.
// Swing 中控件添加问题, 求解.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bb
{
public static void main(String[] args)
{
Test t = new Test("内部类");
t.setSize(200, 200);
t.setVisible(true);
}
}
class Test extends JFrame
{
JPanel panel;
JButton button;
public Test(String str)
{
super(str);
panel = (JPanel)this.getContentPane(); // 这句语句到底是什么意思
// panel并没有被实例化, 它是怎样被添加到Frame上的. 这里的this指的是什么? 是Frame没错吧. 为什么要加 (JPanel)
button = new JButton("well");
// JButton button = new JButton("well"); 为什么会出现运行时异常
panel.add("North", button);
button.addActionListener(new Handle());
}
private class Handle implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
button.setBackground(Color.red); // 外壳类的数据成员可直接访问
panel.setBackground(Color.cyan);
}
}
}
/*
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bb
{
public static void main(String[] args)
{
Test t = new Test("匿名类");
t.setSize(200, 200);
t.setVisible(true);
}
}
class Test extends JFrame
{
JPanel panel;
JButton button;
public Test(String str)
{
super(str);
panel = (JPanel)this.getContentPane();
button = new JButton("well");
// JButton button = new JButton("well"); // 为什么这么竟然出现了编译错误
panel.add("North", button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
button.setBackground(Color.red);
panel.setBackground(Color.cyan);
}
});
}
}
*/