Swing 中控件添加问题, 求解.

ioio88 ioio88 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
// 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);
}
});
}
}
*/
...全文
评论 2
收藏 已收藏
分享
返回顶部
ioio88
Java SE 62,621 成员 307,251 内容