新手请教如何动态改变java中JPanel的背景颜色啊

代码如下:

 package extends1;

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

public class Main extends JFrame implements ItemListener{
    private ButtonGroup bg=new ButtonGroup();
    private JRadioButton rbColorr=new JRadioButton("red");
    private JRadioButton rbColorg=new JRadioButton("green");
    private JRadioButton rbColorb=new JRadioButton("blue");
    private JPanel jpl=new JPanel();
    public Main()
    {
        bg.add(rbColorr);
        bg.add(rbColorg);
        bg.add(rbColorb);
        jpl.add(rbColorr);
        jpl.add(rbColorg);
        jpl.add(rbColorb);
        rbColorr.addItemListener(this);
        rbColorg.addItemListener(this);
        rbColorb.addItemListener(this);
        this.add(jpl);
        this.setSize(300,300);
        this.setVisible(true);
    }
    public void itemStateChanged(ItemEvent e)
    {
        Object color=e.getItemSelectable();
        if(color==rbColorr)
            this.getContentPane().setBackground(Color.red);
        else if(color==rbColorg)
            this.getContentPane().setBackground(Color.green);
        else
            this.getContentPane().setBackground(Color.blue);;
    }
    public static void main(String[] args)throws Exception
    {
        new Main();
    }
}



2个回答

额,懂了,在JFrame上设置JPanel为ContentPane;

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问