这题怎么改?

来源:百度知道 编辑:UC知道 时间:2024/06/11 10:33:00
要在面板上做一个按钮,点一下背景颜色变蓝
import java.awt.event.*;
import javax.swing.*;
class ButtonFrameC extends JFrame implements ActionListener
{
ButtonFrameC()
{
JPanel jp=new JPanel();
JButton jb=new JButton("OK");
jp.add(jb);
jb.addActionListener(this);
add(jp);
Container con=getContentPane();
con.setBackground(Color.RED);
}
public void actionPerformed(ActionEvent e)
{
Container con=getContentPane();
con.setBackground(Color.BLUE);
}
}
public class Java
{
public static void main(String[] args)
{
ButtonFrameC f=new ButtonFrameC();
f.setTitle("颜色变化");
f.setSize(250,200);
f.setLocation(400,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
回复许零星:可为什么刚开始的颜色就没了呢

因为组件是不透明的,你设置了frame的颜色,但在frame上add了一个panel后,颜色被panel挡住,所以你把颜色set在panel上就可以了,即con.setBackground(Color.BLUE); 改为jp.setBackground(Color.BLUE);

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.color.*;
class Java extends JFrame
implements ActionListener
{
private JButton login;
JPanel pane;
public Java(String str){
super(str);
login=new JButton("登录");
pane=new JPanel();
pane.setLayout(null);
pane.add(login);
login.setBounds(10,160,60,20);
this.getContentPane().add(pane).setBackground(Color.white);
this.getContentPane().add(pane);
login.addActionListener(this);
this.setResizable(false);
this.setSize(245,240);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
JButton jb=(JButton)e.getSource();
if(jb==login) {