Java Java - JFreeChart示例

import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class jfcExample extends JFrame
{
	private static final long serialVersionUID = 1L;
	
	private DefaultPieDataset dataset;
	private JFreeChart jfc;

	public jfcExample()
	{
		dataset = new DefaultPieDataset();
	}
	
	public void setValue(String title, Double numDouble)
	{
		dataset.setValue(title, numDouble);
	}
	
	public void setChar(String title)
	{
		jfc = ChartFactory.createPieChart(title, dataset, true, true, false);
		
		PiePlot pp = (PiePlot) jfc.getPlot();
		pp.setSectionOutlinesVisible(false);
		pp.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
		pp.setNoDataMessage("Nessun Dato Inserito");
		pp.setCircular(false);
		pp.setLabelGap(0.02);
	}
	
	private JPanel createPanel()
	{
		return new ChartPanel(jfc);
	}
	
	public void Show()
	{
		setContentPane(createPanel());
		setVisible(true);
	}
	
	public static void main(String[] args)
	{
		jfcExample j = new jfcExample();
		j.setTitle("Example Chart...");
		j.setSize(640, 430);
		
		j.setValue("UNO", new Double(20.0));
		j.setValue("DUE", new Double(10.0));
		j.setValue("TRE", new Double(20.0));
		j.setValue("QUATTRO", new Double(30.0));
		j.setValue("CINQUE", new Double(20.0));
		
		j.setChar("Example Chart...");
		
		j.Show();
	}
}

Java Java - JMF简单过滤器

import java.awt.Dimension;

import javax.media.Buffer;
import javax.media.Effect;
import javax.media.Format;
import javax.media.ResourceUnavailableException;
import javax.media.format.RGBFormat;

public class SimpleFilter implements Effect
{
	protected Format inputFormat = null;
	protected Format outputFormat = null;
	
	protected Format[] inputFormats = null;
	protected Format[] outputFormats = null;
	
	public AngelMotionCodec()
	{
		inputFormats = new Format[]{ new RGBFormat(null, Format.NOT_SPECIFIED, Format.byteArray, Format.NOT_SPECIFIED, 24, 3, 2, 1, 3, Format.NOT_SPECIFIED, Format.TRUE, Format.NOT_SPECIFIED) };
		outputFormats = new Format[]{ new RGBFormat(null, Format.NOT_SPECIFIED, Format.byteArray, Format.NOT_SPECIFIED, 24, 3, 2, 1, 3, Format.NOT_SPECIFIED, Format.TRUE, Format.NOT_SPECIFIED) };
	}
	
	/****** Codec ******/
	public Format[] getSupportedInputFormats()
	{
		return inputFormats;
	}

	public Format[] getSupportedOutputFormats(Format input)
	{
		if(input != null)
		{
			if(matches(input, inputFormats) != null)
				return new Format[]{ outputFormats[0].intersects(input) };
			else
				return new Format[0];
		}
		
		return outputFormats;
	}

	public int process(Buffer input, Buffer output)
	{
		// Swap tra input & output
		Object tmp = input.getData();
		
		input.setData(output.getData());
		output.setData(tmp);
		
		return BUFFER_PROCESSED_OK;
	}

	public Format setInputFormat(Format input)
	{
		inputFormat = input;
		
		return input;
	}

	public Format setOutputFormat(Format output)
	{
		if(output != null || matches(output, outputFormats) != null)
		{
			RGBFormat inRGB = (RGBFormat) output;
			
			Dimension size = inRGB.getSize();
			int maxDataLength = inRGB.getMaxDataLength();
			int lineStride = inRGB.getLineStride();
			int flipped = inRGB.getFlipped();
			
			if(size == null)
				return null;
			
			if(maxDataLength < size.width*size.height*3)
				maxDataLength = size.width*size.height*3;
			
			if(lineStride < size.width*3)
				lineStride = size.width*3;
			
			if(flipped != Format.FALSE)
				flipped = Format.FALSE;
			
			outputFormat = outputFormats[0].intersects(new RGBFormat(size, maxDataLength, inRGB.getDataType(), inRGB.getFrameRate(), inRGB.getBitsPerPixel(), inRGB.getRedMask(), inRGB.getGreenMask(), inRGB.getBlueMask(), inRGB.getPixelStride(), lineStride, flipped, inRGB.getEndian()));
			
			return outputFormat;
		}
		
		return null;
	}
	/****** Codec ******/

	/****** PlugIn ******/
	public void close()
	{

	}

	public String getName()
	{
		return "Simple-Filter";
	}

	public void open() throws ResourceUnavailableException
	{

	}

	public void reset()
	{

	}
	/****** PlugIn ******/

	/****** Controls ******/
	public Object getControl(String controlType)
	{
		return null;
	}

	public Object[] getControls()
	{
		return null;
	}
	/****** Controls ******/
	
	/****** Utility ******/
	private Format matches(Format in, Format[] out)
	{
		if(in != null && out != null)
		{
			for(int i=0, cnt=out.length; i<cnt; i++)
			{
				if(in.matches(out[i]))
					return out[i];
			}
		}
		
		return null;
	}
	/****** Utility ******/
}

Java Java - ImageFilter简单

public BufferedImage Embrossing(BufferedImage bi)
	{
		BufferedImage buff = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
		
		Kernel kernel = new Kernel(3, 3, new float[] {
														-2f, 0f, 0f, 
														 0f, 1f, 0f, 
														 0f, 0f, 2f
													 });
		
		ConvolveOp op = new ConvolveOp(kernel);
		op.filter(bi, buff);
		
		return buff;
	}


	public BufferedImage Blurring(BufferedImage bi)
	{
		BufferedImage buff = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
		
		Kernel kernel = new Kernel(3, 3, new float[] {
														1f/9f, 1f/9f, 1f/9f, 
														1f/9f, 1f/9f, 1f/9f, 
														1f/9f, 1f/9f, 1f/9f
													 });
		
		ConvolveOp op = new ConvolveOp(kernel);
		op.filter(bi, buff);
		
		return buff;
	}


	public BufferedImage Sharpening(BufferedImage bi)
	{
		BufferedImage buff = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
		
		Kernel kernel = new Kernel(3, 3, new float[] {
														-1f, -1f, -1f, 
														-1f,  9f, -1f, 
														-1f, -1f, -1f
													 });
		
		ConvolveOp op = new ConvolveOp(kernel);
		op.filter(bi, buff);
		
		return buff;
	}

Java Java - CUT&PASTE

package system.clipboard;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;	 

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class ClipBoard extends JFrame implements ClipboardOwner, ActionListener
{
	private static final long serialVersionUID = 1L;
	
	JTextArea srcText, dstText;
	JButton copyButton, pasteButton;
	Clipboard clipboard = getToolkit().getSystemClipboard();

	public ClipBoard()
	{
		super("Clipboard Test");
		
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		
		setLayout(gridbag);
		
		srcText = new JTextArea(8, 32);
		c.gridwidth = 2;
		c.anchor = GridBagConstraints.CENTER;
		gridbag.setConstraints(srcText, c);
		add(srcText);

		copyButton = new JButton("Copy Above");
		copyButton.setActionCommand("copy");
		copyButton.addActionListener(this);
		c.gridy = 1;
		c.gridwidth = 1;
		gridbag.setConstraints(copyButton, c);
		add(copyButton);
		
		pasteButton = new JButton("Paste Below");
		pasteButton.setActionCommand("paste");
		pasteButton.addActionListener(this);
		pasteButton.setEnabled(false);
		c.gridx = 1;
		gridbag.setConstraints(pasteButton, c);
		add(pasteButton);
		
		dstText = new JTextArea(8, 32);
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 2;
		gridbag.setConstraints(dstText, c);
		add(dstText);
		
		pack();
	}
	
	public void actionPerformed(ActionEvent evt)
	{
		String cmd = evt.getActionCommand();
		
		if(cmd.equals("copy")) 
		{
			// Implement Copy operation
			String srcData = srcText.getText();
			
			if(srcData != null)
			{
				StringSelection contents = new StringSelection(srcData);
				clipboard.setContents(contents, this);
				pasteButton.setEnabled(true);
			}
		}
		else if(cmd.equals("paste"))
		{
			// Implement Paste operation
			Transferable content = clipboard.getContents(this);
			if(content != null) 
			{
				try
				{
					String dstData = (String) content.getTransferData(DataFlavor.stringFlavor);
					dstText.append(dstData);
				}
				catch(Exception e)
				{
					System.out.println("Couldn't get contents in format: " + DataFlavor.stringFlavor.getHumanPresentableName());
				}
			}
		}
	}

	public void lostOwnership(Clipboard clipboard, Transferable contents)
	{
		System.out.println("Clipboard contents replaced");
	}
	
	public static void main(String[] args) 
	{
		ClipBoard test = new ClipBoard();
		test.setVisible(true);
	}
}

Java Java - Applet DrawLine

<html>

	<head>
		<title>Sono una Applet...</title>
	</head>
	
	<body>
		<applet code="Example01.class" width="300" height="300">Non sono supportata...</applet>
	</body>
	
</html>


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JApplet;

public class Example01 extends JApplet implements MouseMotionListener
{
	public void init()
	{
		this.addMouseMotionListener(this);
	}
	
	public void start()
	{
		this.setBackground(Color.YELLOW);
		this.repaint(); // Ridisegna lo schermo
	}
	
	public void paint(Graphics g)
	{
		super.paint(g);
	}

	public void mouseDragged(MouseEvent e)
	{
		
	}

	public void mouseMoved(MouseEvent e)
	{
		Graphics g = this.getGraphics();
		
		g.drawLine(e.getX(), e.getY(), e.getX(), e.getY());
	}
}

Java Java - Mini Lettore Wav

package Multimedia;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class AudioSystem
{
	public static void main(String[] args)
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		
		try
		{
			UIManager.setLookAndFeel(new MetalLookAndFeel());
		}
		catch(UnsupportedLookAndFeelException e)
		{
			e.printStackTrace();
		}
		
		new AudioGUI();
	}
}


package Multimedia;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AudioGUI extends JFrame implements WindowListener
{
	public AudioGUI()
	{
		this.setTitle("AudioSystem");
		this.setSize(240, 100);
		this.setResizable(false);
		
		this.addWindowListener(this);
		
		Container gc = this.getContentPane();
		gc.add(new AudioGUIPan());
		
		this.setVisible(true);
	}

	public void windowOpened(WindowEvent e)
	{
		
	}

	public void windowClosing(WindowEvent e)
	{
		System.exit(0);
	}

	public void windowClosed(WindowEvent e)
	{
		
	}

	public void windowIconified(WindowEvent e)
	{
		
	}

	public void windowDeiconified(WindowEvent e)
	{
		
	}

	public void windowActivated(WindowEvent e)
	{
		
	}

	public void windowDeactivated(WindowEvent e)
	{
		
	}
}

class AudioGUIPan extends JPanel implements ActionListener
{
	private JButton play;
	private JButton stop;
	private JButton loop;
	private JButton open;
	private JButton close;
	
	private JFileChooser jfc;
	
	private String file;
	
	private AudioDevice ad;
	
	public AudioGUIPan()
	{
		play = new JButton("Play");
		play.addActionListener(this);
		stop = new JButton("Stop");
		stop.addActionListener(this);
		open = new JButton("Open");
		open.addActionListener(this);
		close = new JButton("Close");
		close.addActionListener(this);
		
		this.add(stop);
		this.add(play);
		this.add(open);
		this.add(close);
	}

	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == close)
		{
			System.exit(0);
		}
		else if(e.getSource() == open)
		{
			jfc = new JFileChooser();
			jfc.setFileFilter(new AudioFilter());
			
			if(jfc.showOpenDialog(this) != JFileChooser.CANCEL_OPTION)
			{
				file = jfc.getSelectedFile().getAbsolutePath();
				ad = new AudioDevice(new File(file));
			}
		}
		else if(e.getSource() == play)
		{
			if(ad != null)
				ad.play();
		}
		else if(e.getSource() == stop)
		{
			if(ad != null)
				ad.stop();
		}
	}
}


package Multimedia;
import java.io.File;

import javax.swing.filechooser.FileFilter;

public class AudioFilter extends FileFilter
{
	public boolean accept(File f)
	{
		return f.getName().toLowerCase().endsWith(".wav") || f.isDirectory();
	}

	public String getDescription()
	{
		return "Audio File *.wav";
	}
}


package Multimedia;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;

public class AudioDevice implements AudioClip
{
	private AudioClip ac;
	public AudioDevice(File f)
	{		
		try
		{
			ac = Applet.newAudioClip(f.toURL());
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
	}
	
	public void play()
	{
		ac.play();
	}

	public void stop()
	{
		ac.stop();
	}

	public void loop()
	{
		
	}
}

Java 通过通用列表进行迭代(Java 5版本)

List<String> listOfStrings = new LinkedList<String>( );

listOfStrings.add("Why");
listOfStrings.add("Iterate");
listOfStrings.add("When");
listOfStrings.add("You");
listOfStrings.add("Can");
listOfStrings.add("Avoid");
listOfStrings.add("It!");

for (String s: listOfStrings) {
    System.out.println(s);
}

Java 查找和替换

protected String findAndReplace(String orginal, String toBeRemoved, String replacingStr) {
        StringBuffer finalStr = new StringBuffer("");
        int charCounter = 0;
        int start = 0;
        while (charCounter < orginal.length()) {
            start = orginal.indexOf(toBeRemoved, charCounter);
            if (start >= 0) {
                finalStr.append(orginal.substring(charCounter, start));
                charCounter = start + toBeRemoved.length();
                finalStr.append(replacingStr);
            } else {
                finalStr.append(orginal.substring(charCounter, orginal.length()));
                return finalStr.toString();
            }
        }
        return finalStr.toString();
    }

Java 通过比较它的值对地图键进行排序

import java.util.*;

//
// Groovy version of "Sort keys by values" is:
//    keys.sort{ lang[it] }
// That's one line replacement!!!
//

class MapSort {
	public static void main(String[] args){
		Map lang = new HashMap();
		lang.put(0, "Java");
		lang.put(1, "Groovy");
		lang.put(2, "Ruby");
		lang.put(3, "Python");
		lang.put(4, "C#");
		lang.put(5, "C++");
		lang.put(6, "Perl");
		
		List keys = new ArrayList(lang.keySet());
		
		//Sort keys by values.
		final Map langForComp = lang;
		Collections.sort(keys, 
			new Comparator(){
				public int compare(Object left, Object right){
					Integer leftKey = (Integer)left;
					Integer rightKey = (Integer)right;
					
					String leftValue = (String)langForComp.get(leftKey);
					String rightValue = (String)langForComp.get(rightKey);
					return leftValue.compareTo(rightValue);
				}
			});
		
		//List the key value
		for(Iterator i=keys.iterator(); i.hasNext();){
			Object k = i.next();
			System.out.println(k + " " + lang.get(k));
		}
	}
}

Java 用于在Eclipse Europa + m2eclipse中运行的webapp的Maven2 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>deng.mywebapp</groupId>
	<artifactId>mywebapp</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>mywebapp Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<profiles>
		<profile>
			<id>servlet</id>
			<activation>
				<activeByDefault>false</activeByDefault>
			</activation>
			<dependencies>
				<dependency>
					<groupId>javax.servlet</groupId>
					<artifactId>servlet-api</artifactId>
					<version>2.5</version>
					<scope>provided</scope>
				</dependency>
				<dependency>
					<groupId>javax.servlet.jsp</groupId>
					<artifactId>jsp-api</artifactId>
					<version>2.1</version>
					<scope>provided</scope>
				</dependency>
			</dependencies>
		</profile>
	</profiles>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>mywebapp</finalName>
		<plugins>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>