JAVA范例 十九) 多媒体与图像处理

a多媒体

实例349 测试音频播放器

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class OggPlay extends JFrame {
    private JPanel contentPane;
    private JTextField jtextField = new JTextField();// 用于输入声音文件的地址
    private JLabel jLabel = new JLabel();            // 用于显示播放器的状态信息
    private JPanel jPanel = new JPanel();        // 用于包容下面两个JButton对象
    // 用于控制播放和停止声音文件
    private JButton jbutton1 = new JButton();
    private JButton jbutton2 = new JButton();
    private AudioClip clip;                    // 用于播放声音文件
    private void init() throws Exception {
        contentPane = (JPanel) this.getContentPane();
        this.setSize(new Dimension(418, 118));
        this.setTitle("音频片断播放器");
        jLabel.setFont(new Font("Dialog", 0, 12));
        jLabel.setToolTipText("");
        jLabel.setText("准备就续");// 播放器的初始状态信息
        jbutton1.setFont(new Font("Dialog", 0, 12));
        jbutton1.setText("播放");
        jbutton1.addActionListener(new ActionListener() {// 添加ActionListener
                    public void actionPerformed(ActionEvent e) {
                        jbutton1_actionPerformed(e);
                    }
                });
        jbutton2.setEnabled(false);// "停止"按钮初始为不可访问
        jbutton2.setFont(new Font("Dialog", 0, 12));
        jbutton2.setText("停止");
        jbutton2.addActionListener(new ActionListener() {// 添加ActionListener
                    public void actionPerformed(ActionEvent e) {
                        jbutton2_actionPerformed(e);
                    }
                });
        // 设置初始的声音文件路径,读者可以自定义路径和设备名称
        jtextField.setText(ClassLoader.getSystemResource("aa.wav").toString());
        contentPane.add(jLabel, BorderLayout.SOUTH);
        contentPane.add(jPanel, BorderLayout.CENTER);
        jPanel.add(jbutton1, null);
        jPanel.add(jbutton2, null);
        contentPane.add(jtextField, BorderLayout.NORTH);
        clip = null;// 声音剪辑对象初始化为null
        this.show();
    }
    public void jbutton1_actionPerformed(ActionEvent e) {
        try {
            jbutton1.setEnabled(false);
            jbutton2.setEnabled(true);
            // 实例化一个AudioClip对象clip,将声音文件的数据存入clip对象中
            clip = Applet.newAudioClip(new URL(this.jtextField.getText()));
            System.out.println(this.jtextField.getText());
            // 开始播放clip对象中的声音数据
            clip.play();
            // 显示播放器的状态信息
            this.jLabel.setText("正在播放:" + this.jtextField.getText());
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
    public void jbutton2_actionPerformed(ActionEvent e) {
        try {
            jbutton1.setEnabled(true);
            jbutton2.setEnabled(false);
            // 停止播放clip对象中的声音数据
            clip.stop();
            // 显示播放器的状态信息
            this.jLabel.setText("准备就绪");
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        new OggPlay().init();
    }
}


实例350 测试视频播放器
import java.awt.*;
import java.io.IOException;

import javax.media.*;
import javax.swing.*;

public class RealOnePlayer extends JFrame implements ControllerListener {
    private JPanel jp;

    private BorderLayout bl = new BorderLayout();

    Component cp1 = null;// 创建一个视频播放组件

    Component cp2 = null;// 创建一个视频播放组件

    Player player = null;// 播放器对象

    public RealOnePlayer(String url) {
        this.setTitle("JMF视频播放器");
        try {
            Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));// 这一行很重要,可以解决Swing组件和AWT组件混用带来的麻烦
            player = Manager.createPlayer(new MediaLocator(url));
        } catch (NoPlayerException e) {
            exitProc("找不到播放器!");// 显示消息并退出程序
        } catch (IOException e) {
            exitProc("不能创建播放器!");// 显示消息并退出程序
        }
        if (player == null) {
            exitProc("不能创建播放器!");// 显示消息并退出程序
        }
        player.addControllerListener(this);// 添加ControllerListener监听器
        player.prefetch();// 获取媒体数据
    }

    public void controllerUpdate(ControllerEvent e) {
        if (e instanceof ControllerClosedEvent) {// 如果控制事件是关闭,就退出程序
            System.exit(0);
        }
        if (e instanceof EndOfMediaEvent) {// 如果控制事件是媒体数据播放完毕,则player设置新的媒体时间,重新开始播放
            player.setMediaTime(new Time(0));
            player.start();
            return;
        }
        if (e instanceof PrefetchCompleteEvent) {// 如果控制事件是获得媒体数据完成,则开始播放
            player.start();
            return;
        }
        // 如果控制事件是Realize完成,则播放器player获得播放画面的组件,用于媒体可视化播放,并将组件加到MediaDemo_2窗口中,同时获得播放控制组件,也添加到MediaDemo_2窗口上,用于控制媒体的播放
        if (e instanceof RealizeCompleteEvent) {
            Component vc = player.getVisualComponent();
            if (vc != null) {
                this.getContentPane().add(vc, BorderLayout.CENTER);
                Component cc = player.getControlPanelComponent();
                if (cc != null) {
                    this.getContentPane().add(cc, BorderLayout.SOUTH);
                    this.pack();
                    this.setResizable(false);// 窗口大小适合媒体画面,并不可改变
                    this.setVisible(true);// 显示页面
                }
            }
        }
    }

    private void exitProc(String str) {
        System.out.println(str);
        System.exit(-1);
    }

    public static void main(String[] args) {
        RealOnePlayer md = new RealOnePlayer(ClassLoader.getSystemResource(
                "lift.mpeg").toString());
    }

}


实例351 视频反色效果

import java.awt.*;
import java.io.IOException;

import javax.media.Buffer;
import javax.media.Codec;
import javax.media.ControllerClosedEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.Controls;
import javax.media.Effect;
import javax.media.EndOfMediaEvent;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoProcessorException;
import javax.media.NotConfiguredError;
import javax.media.Processor;
import javax.media.RealizeCompleteEvent;
import javax.media.Time;
import javax.media.UnsupportedPlugInException;
import javax.media.control.TrackControl;
import javax.media.format.RGBFormat;
import javax.swing.*;

public class Media11 extends JFrame implements ControllerListener {
    private JPanel contentPane;

    private BorderLayout bl = new BorderLayout();

    Component vc = null;// 媒体播放画面组件

    Component cc = null;// 媒体播放控制组件

    TrackControl[] tc = null;// 各条媒体踪迹的数据控制处理对象

    Processor p = null;// 媒体处理器,控制整个媒体的播放过程

    public Media11(String mediaURL) {

        Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));// 处理swing组件和awt组件的冲突
        MediaLocator ml = new MediaLocator(mediaURL);
        try {
            p = Manager.createProcessor(ml);
        } catch (NoProcessorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }// 根据媒体定位对象,实例化一个处理器exitProc()方法向屏幕显示信息,并退出程序
        if (p == null) {
            exitProc("不能创建播放器!");

        }
        p.addControllerListener(this);// 添加处理器的控制状态变化监听器
        p.configure();// 初始化处理器的设置
        while (p.getState() != p.Configured)
            ;
        p.setContentDescriptor(null);// 如果处理器不能完成初始设置,则设置媒体上下文描述器
        tc = p.getTrackControls();// 处理器得到媒体数据的所有踪迹控制处理对象
        if (tc.length > 0) {
            Codec[] cd = new Codec[1];
            cd[0] = new NegativeEffect();// 设置媒体编码器为经NegativeEffect对象处理后的编码器
            try {
                tc[0].setCodecChain(cd);
            } catch (UnsupportedPlugInException e) {
                e.printStackTrace();
            } catch (NotConfiguredError e) {
                e.printStackTrace();
            }// 指定一条将在每条媒体踪迹中使用的编码器插件链

        }
        p.realize();// 处理器进入realizing状态
    }

    public void controllerUpdate(ControllerEvent e) {// 如果事件是控制器关闭事件、则正常退出程序
        if (e instanceof ControllerClosedEvent)
            System.exit(0);
        // 如果是媒体播放完毕,则重新设置媒体时间
        if (e instanceof EndOfMediaEvent) {
            p.setMediaTime(new Time(0));
            return;
        }
        // 如是是Realize完成,则处理器获得可视化的播放画面组件,实例化vc对象并添加到主窗口中;同时获得播放控制组件,实例化cc对象,并添加到主窗口中
        if (e instanceof RealizeCompleteEvent) {
            vc = p.getVisualComponent();
            if (vc != null)
                this.getContentPane().add(vc, BorderLayout.CENTER);
            cc = p.getControlPanelComponent();
            if (cc != null)
                this.getContentPane().add(cc, BorderLayout.SOUTH);
            // 调整主窗口属性,并使窗口适合媒体画面大小,而不可改变
            this.pack();
            this.setResizable(false);
            this.setVisible(true);

        }
    }

    public void exitProc(String str) {
        System.out.println(str);
        System.exit(-1);
    }

    public static void main(String[] args) {
        new Media11(ClassLoader.getSystemResource("lift.mpeg").toString());
    }

}

class NegativeEffect implements Effect {
    private static String EffectName = "NegativeEffect";

    protected RGBFormat inputFormat;// 输入的RGB色彩格式

    protected RGBFormat outputFormat;// 输出的RGB色彩格式

    protected Format[] supportedInputFormats;// 所有支持的输入格式

    protected Format[] supportedOutputFormats;// 所有支持的输出格式

    // 构造方法,实例化所有支持的输入输出色彩为RGB色彩格式
    public NegativeEffect() {
        supportedInputFormats = new Format[] { new RGBFormat() };
        supportedOutputFormats = new Format[] { new RGBFormat() };
    }

    // 实现Effect接口继承自Codec的方法,返回所有支持的输入格式
    public Format[] getSupportedInputFormats() {
        System.out.println("getSupportedInputFormats");
        return supportedInputFormats;
    }

    // 实现Effect接口继承自Codec的方法,返回所有支持的输出格式
    public Format[] getSupportedOutputFormats(Format parm) {
        System.out.println("getSupportedOutputFormats[in = " + parm + "]");
        // 如果传入的Format对象parm不是RGBFormat实例,则返回默认的RGBFormat格式对象
        if (parm == null)
            return supportedOutputFormats;
        if (!(parm instanceof RGBFormat))
            return new Format[0];
        // 如果是,根据该格式返回一个对象引用
        RGBFormat rf = (RGBFormat) parm;
        RGBFormat rfb = (RGBFormat) parm.clone();
        return new Format[] { rfb };
    }

    // 实现Effect接口继承自Codec的方法,返回传入的数据格式
    public Format setInputFormat(Format parm) {
        System.out.println("setInputFormatInput[input=" + parm + "]");
        inputFormat = (RGBFormat) parm;
        return (RGBFormat) inputFormat;
    }

    // 实现Effect接口继承自Codec的方法,返回传入的数据格式
    public Format setOutputFormat(Format parm) {
        System.out.println("setOutputFormat[output=" + parm + "]");
        outputFormat = (RGBFormat) parm;
        return (RGBFormat) outputFormat;
    }

    // 不一定要实现的两个方法,仅仅满足get、set的对称性
    public Format getInputFormat() {
        System.out.println("getInputFormat");
        return inputFormat;
    }

    public Format getOutputFormat() {
        System.out.println("getOutputFormat");
        return outputFormat;
    }

    // 实现Effect接口自Codec的方法,处理输入的媒体数据parm,得到经处理的输出的媒体数据parm,该方法完成本类的效用,处理媒体数据,达到使色彩反色输出的处理效果是本类的核心方法
    public int process(Buffer parm1, Buffer parm2) {
        Object o = parm1.getData();// 获得输入的数据对象的引用
        int inLength = parm1.getLength();// 输入的数据的长度
        int inOffset = parm1.getOffset();// 偏移量
        // 如果输入输出的媒体数据非合法的short[]int[]形式,返回出错信息
        if (!(o instanceof short[]) && !(o instanceof int[]))
            return this.BUFFER_PROCESSED_FAILED;
        Object oo = parm2.getData();
        if (oo != null) {
            if (!(oo instanceof short[]) && !(oo instanceof int[]))
                return this.BUFFER_PROCESSED_FAILED;
        } else {
            // 根据输入的数据长度,设置输出的数据长度
            if (o instanceof short[])
                parm2.setData(new short[inLength]);
            else
                parm2.setData(new int[inLength]);
            oo = parm2.getData();
        }
        // 根据输入的数据偏移量,设置输出的数据偏移量
        int outOffset = parm2.getOffset();
        if (o instanceof short[]) {
            short[] inData = (short[]) o;
            short[] outData = (short[]) oo;
            // 处理输入的媒体数据,将色彩取反,并将数据放入输出的媒体数据对象中
            for (int i = 0; i < inLength; i++)
                outData[outOffset++] = (short) -inData[inOffset++];
        } else {
            int[] inData = (int[]) o;
            int[] outData = (int[]) oo;
            for (int i = 0; i < inLength; i++)
                outData[outOffset++] = -inData[inOffset++];
        }
        // 设置输出媒体数据的格式
        parm2.setFormat(outputFormat);
        // 设置输出媒体数据的长度和偏移
        parm2.setLength(inLength);
        parm2.setOffset(0);
        // 返回数据处理成功完成信息
        return this.BUFFER_PROCESSED_OK;
    }

    // 返回类名
    public String getName() {
        System.out.println("getName");
        return EffectName;
    }

    // 以下的方法不一定要求实现,这些方法是Effect接口的父类的上层类
    public void open() {
        System.out.println("open");
    }

    public void close() {
        System.out.println("close");
    }

    public void reset() {
        System.out.println("reset");
    }

    public Object[] getControls() {
        System.out.println("getControls");
        return new Controls[0];
    }

    public Object getControl(String parm1) {
        System.out.println("getControl[controlType=" + parm1 + "]");
        Class clas = null;
        try {
            Object[] cs = this.getControls();
            for (int i = 0; i < cs.length; i++) {
                if (clas.isInstance(cs[i])) {
                    return cs[i];
                }
            }
            clas = Class.forName(parm1);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

}


实例352 实现一个录音机

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Vector;

import javax.media.*;
import javax.media.datasink.*;
import javax.media.format.AudioFormat;
import javax.media.protocol.*;
import javax.media.control.StreamWriterControl;
import javax.swing.*;

//录音机
public class Recorder extends JFrame implements ActionListener,
        DataSinkListener {
    private JPanel contentPane;

    private BorderLayout borderLayout = new BorderLayout();

    StateHelper sh;

    Processor processor;

    DataSink fileWriter = null;

    private JButton btStart = new JButton(" Start ");

    private JButton btStop = new JButton(" Stop ");

    private JLabel jLabel = new JLabel("录间机演示", SwingConstants.CENTER);

    private void initial() throws Exception {
        // 添加按扭的事件监听器
        this.btStart.addActionListener(this);
        this.btStop.addActionListener(this);
        contentPane = new JPanel(borderLayout);
        // 添加按扭到指定位置
        contentPane.add(this.btStart, BorderLayout.WEST);
        contentPane.add(this.jLabel, BorderLayout.CENTER);
        contentPane.add(this.btStop, BorderLayout.EAST);
        this.add(contentPane);
        this.setSize(350, 120);
        this.setVisible(true);
        // 申明一个捕获设备信息类,用于得到本机上的声音捕获相关设备信息
        CaptureDeviceInfo cdi = null;
        AudioFormat af = new AudioFormat(AudioFormat.LINEAR, 8000, 16, 1);// 创建一个指定参数的声音媒体格式
        // 获得设备信息
        Vector deviceList = CaptureDeviceManager.getDeviceList(af);
        if (deviceList.size() > 0) {
            cdi = (CaptureDeviceInfo) deviceList.firstElement();// 使用第一个设备
        } else {
            exitProc("Could not find audiodevice");// 设备都不可用,退出程序
        }
        // 实例化一个处理器
        processor = Manager.createProcessor(cdi.getLocator());
        // 实例化一个实现ControllerListener接口的类,处理控制状态变化事件
        sh = new StateHelper(processor);
        // 设置超时10000ms 退出
        if (!sh.configure(10000)) {
            exitProc("Could not configure processon");
        }
        // 用于在磁盘上指定存储获取的声音数据文件
        FileTypeDescriptor ftd = new FileTypeDescriptor(
                FileTypeDescriptor.BASIC_AUDIO);
        processor.setContentDescriptor(ftd);
        if (sh.realize(10000)) {
            exitProc("Could not realize processor");
        }

    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        ((Component) e.getSource()).setEnabled(false);// 按扭单击后变为不可访问状态
        // 如查被单击的是"Start"按扭,则开始录音,并将声音数据写到指定的文件中
        if (cmd.equals("Start")) {
            DataSource source = processor.getDataOutput();
            MediaLocator dest = new MediaLocator("file:/c:/out.au");
            try {
                fileWriter = Manager.createDataSink(source, dest);
                fileWriter.addDataSinkListener(this);
                fileWriter.open();
            } catch (NoDataSinkException err) {
                exitProc("Could not create data sink");
            } catch (IOException ee) {
                ee.printStackTrace();
            }
            // 设置声音数据的长度限制为10000000B
            StreamWriterControl swc = (StreamWriterControl) processor
                    .getControl("javax.media.control.StreamWriterControl");
            if (swc != null) {
                swc.setStreamSizeLimit(10000000);
            }
            try {
                fileWriter.start();
            } catch (IOException err) {
                System.out.println(err.toString());
            }
            processor.start();
            return;
        }
        // 如果单击的是"Stop"按扭,则关闭处理器
        processor.stop();
        processor.close();

    }

    public void dataSinkUpdate(DataSinkEvent e) {
        if (e instanceof EndOfStreamEvent) {
            fileWriter.close();
            System.exit(0);
        }

    }

    public void exitProc(String str) {
        System.out.println(str);
        System.exit(-1);
    }

    public static void main(String args[]) throws Exception {
        new Recorder().initial();
    }

}

class StateHelper implements ControllerListener {
    Player player = null;

    boolean configured = false;

    boolean realized = false;

    boolean prefetched = false;

    boolean failed = false;

    boolean closed = false;

    // 构造方法的传入参数是Player对象
    public StateHelper(Player player) {
        this.player = player;
        this.player.addControllerListener(this);

    }

    // 完成configure操作
    public boolean configure(int timeOutMillis) {
        long startTime = System.currentTimeMillis();
        synchronized (this) {
            if (player instanceof Processor) {
                ((Processor) player).configure();
            } else {
                return false;
            }
            while (!configured && !failed) {
                try {
                    wait(timeOutMillis);
                } catch (Exception e) {

                }
                if (System.currentTimeMillis() - startTime > timeOutMillis)
                    break;
            }

        }
        return this.configured;

    }

    // 完成realize操作
    public boolean realize(int timeOutMillis) {
        long startTime = System.currentTimeMillis();
        synchronized (this) {
            player.realize();
            while (!realized && !failed) {
                try {
                    wait(timeOutMillis);
                } catch (Exception e) {

                }
                if (System.currentTimeMillis() - startTime > timeOutMillis)
                    break;
            }

        }
        return this.realized;

    }

    // 完成prefetch操作
    public boolean prefetch(int timeOutMillis) {
        long startTime = System.currentTimeMillis();
        synchronized (this) {
            player.prefetch();
            while (!prefetched && !failed) {
                try {
                    wait(timeOutMillis);
                } catch (Exception e) {

                }
                if (System.currentTimeMillis() - startTime > timeOutMillis)
                    break;
            }

        }
        return this.prefetched;

    }

    public void close() {
        synchronized (this) {
            player.close();// 关闭播放器
            while (!closed) {// 如果closed为false,则等待100ms完成程序结束处理
                try {
                    wait(100);
                } catch (Exception e) {

                }
            }

        }
        player.removeControllerListener(this);// 撤销播放器的控制监听器
    }

    // 处理ControllerEvent事件
    public void controllerUpdate(ControllerEvent e) {
        if (e instanceof RealizeCompleteEvent) {
            this.realized = true;
        } else if (e instanceof ConfigureCompleteEvent) {
            this.configured = true;
        } else if (e instanceof PrefetchCompleteEvent) {
            this.prefetched = true;
        } else if (e instanceof ControllerErrorEvent) {
            this.failed = true;
        } else if (e instanceof ControllerClosedEvent) {
            this.closed = true;
        } else {
            return;
        }
    }

}

实例353 建立一个调色板

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class CPalette extends JFrame implements ChangeListener {
    private JPanel contendtPane;
    private BorderLayout borderLayout1 = new BorderLayout();
    private JPanel jPanel1 = new JPanel();
    private JPanel jPanel2 = new JPanel();
    private GridLayout gridLayout1 = new GridLayout();
    private JSlider redSlider = new JSlider();// 调节红色
    private JSlider greenSlider = new JSlider();// 调节绿色
    private JSlider blueSlider = new JSlider();// 调节蓝色
    private JSlider alphaSlider = new JSlider();// 调节Alpha值
    private TitledBorder titledBorder1;
    private TitledBorder titledBorder2;
    private TitledBorder titledBorder3;
    private TitledBorder titledBorder4;
    private JLabel jLabel = new JLabel();
    ColorCanvas canvas = new ColorCanvas();// 创建ColorCanvas的实例
    private BorderLayout borderLayout2 = new BorderLayout();
    public void initial() throws Exception {
        contendtPane = (JPanel) this.getContentPane();
        // 各个JSlider对象的标题边界
        titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(
                Color.white, new Color(142, 142, 142)), "Red");
        titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(
                Color.white, new Color(142, 142, 142)), "Green");
        titledBorder3 = new TitledBorder(BorderFactory.createEtchedBorder(
                Color.white, new Color(142, 142, 142)), "Blue");
        titledBorder4 = new TitledBorder(BorderFactory.createEtchedBorder(
                Color.white, new Color(142, 142, 142)), "Alpha");
        contendtPane.setLayout(borderLayout1);
        this.setSize(new Dimension(401, 317));
        this.setTitle("JColorDemo");
        // jPanel2的布局结构设置
        jPanel2.setLayout(gridLayout1);
        gridLayout1.setColumns(2);
        gridLayout1.setHgap(5);
        gridLayout1.setRows(2);
        gridLayout1.setVgap(5);
        // 设置各个JSlider对象的基本属性
        redSlider.setMaximum(255);// 最大色彩值
        redSlider.setPaintLabels(true);// 绘制标签
        redSlider.setPaintTicks(true);// 绘制移动块
        redSlider.setBorder(titledBorder1);// 设置边界
        greenSlider.setMaximum(255);
        greenSlider.setPaintLabels(true);
        greenSlider.setPaintTicks(true);
        greenSlider.setBorder(titledBorder2);
        blueSlider.setMaximum(255);
        blueSlider.setPaintLabels(true);
        blueSlider.setPaintTicks(true);
        blueSlider.setBorder(titledBorder3);
        alphaSlider.setMaximum(255);
        alphaSlider.setPaintLabels(true);
        alphaSlider.setPaintTicks(true);
        alphaSlider.setBorder(titledBorder4);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel.setText("调色板程序演示");
        jPanel1.setLayout(borderLayout2);
        contendtPane.add(jPanel1, BorderLayout.CENTER);
        contendtPane.add(jPanel2, BorderLayout.SOUTH);
        jPanel2.add(redSlider, null);
        jPanel2.add(greenSlider, null);
        jPanel2.add(blueSlider, null);
        jPanel2.add(alphaSlider, null);
        contendtPane.add(jLabel, BorderLayout.NORTH);
        // 添加各个JSlider对象的事件监听器
        this.redSlider.addChangeListener(this);
        this.greenSlider.addChangeListener(this);
        this.blueSlider.addChangeListener(this);
        this.alphaSlider.addChangeListener(this);
        // jPanel1上添加canvas对象,用来显示当前的颜色
        this.jPanel1.add(this.canvas);
        this.setVisible(true);
    }
    public void stateChanged(ChangeEvent e) {
        JSlider slider = (JSlider) e.getSource();
        // 根据JSlider对象的改变后的值,改变canvas对象的各色彩值,并重新设置canvas的背景色
        if (slider == this.redSlider) {
            this.canvas.redValue = slider.getValue();
            this.canvas.setBackgroudnColor();
        } else if (slider == this.greenSlider) {
            this.canvas.greenValue = slider.getValue();
            this.canvas.setBackgroudnColor();
        } else if (slider == this.blueSlider) {
            this.canvas.blueValue = slider.getValue();
            this.canvas.setBackgroudnColor();
        } else if (slider == this.alphaSlider) {
            this.canvas.alphaValue = slider.getValue();
            this.canvas.setBackgroudnColor();
        }
        // 更新canvas对象的背景色,显示颜色值改变后的颜色
        this.canvas.repaint();
    }
    public static void main(String args[]) throws Exception {
        new CPalette().initial();
    }
}
class ColorCanvas extends Canvas {
    Color color;// 各颜色值形成的颜色
    int redValue, greenValue, blueValue;// 各颜色值
    int alphaValue = 255;
    public ColorCanvas() {
        this.color = new Color(0, 0, 0);// 初始颜色
        this.setBackgroudnColor();// 设置初始的背景色
    }
    // 该方法根据各颜色值,来设置canvas对象的背景色
    public void setBackgroudnColor() {
        this.color = new Color(this.redValue, this.greenValue, this.blueValue,
                this.alphaValue);
        this.setBackground(this.color);
    }
} 

你可能感兴趣的:(java)