一个关于背景颜色改变的问题

magicshop magicshop 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这是一个改变背景颜色的程序,但运行后颜色没改变阿?
请帮忙看看。谢谢

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class FirstPanel extends JPanel
implements ActionListener
{ public FirstPanel()
{ JButton redButton = new JButton("Red");
JButton blueButton = new JButton("Blue");
JButton yellowButton = new JButton("Yellow");

add(redButton);
add(blueButton);
add(yellowButton);

redButton.addActionListener(this);
blueButton.addActionListener(this);
yellowButton.addActionListener(this);
}

public void actionPerformed(ActionEvent evt)
{ Object source = evt.getSource();
Color color = getBackground();
if (source == redButton) color = Color.red;
else if (source == blueButton) color = Color.blue;
else if (source == yellowButton) color = Color.yellow;
setBackground(color);
repaint();
}
private JButton redButton;
private JButton blueButton;
private JButton yellowButton;
}
class FirstFrame extends JFrame
{ public FirstFrame()
{ setTitle("FirstFrame");
setSize(300, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});

Container contentPane = getContentPane();
contentPane.add(new FirstPanel());
}
}

public class FirstTest
{ public static void main(String[] args)
{ JFrame frame = new FirstFrame();
frame.setVisible(true);
}
}
...全文
评论 8
收藏 已收藏
分享
返回顶部
magicshop
Java SE 62,621 成员 307,251 内容