some transformation methods for the Graphics2D class
rotate() |
scale() |
translate() |
translate(AffineTransform) |
Awt Drawing ‹↑›
The old awt drawing methods are extremely limited. Here is an
example
draw a some shapes using the old awt graphics class (limited)
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class ShapeDraw extends Component {
public void paint(Graphics g) {
g.drawLine(10,10,40,40);
g.drawRect(20, 20, 100, 100);
g.fillRect(120, 120, 200, 200);
}
public ShapeDraw() {}
public Dimension getPreferredSize() { return new Dimension(400, 600); }
public static void main(String[] args) {
JFrame f = new JFrame("Drawing Stuff");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new ShapeDraw());
f.pack(); f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Images ‹↑›
Image Information ‹↑›
read an image from a url and get its height and width
URL url = new URL("http://i.stack.imgur.com/Nqf3H.jpg");
final BufferedImage originalImage = ImageIO.read(url);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
create a new image icon
ImageIcon i = new ImageIcon(imgURL, "some image");
get an image size without reading the whole image
ImageInputStream in = ImageIO.createImageInputStream(resourceFile);
try {
final Iterator readers = ImageIO.getImageReaders(in);
if (readers.hasNext()) {
ImageReader reader = (ImageReader) readers.next();
try {
reader.setInput(in);
return new Dimension(reader.getWidth(0), reader.getHeight(0));
}
finally { reader.dispose(); }
}
}
finally {if (in != null) in.close(); }
a small app which allows to load a set of images from a folder
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ImageApp extends Component implements KeyListener {
BufferedImage img;
File[] imageList;
public void paint(Graphics g) {
//g.drawImage(img, 0, 0, null);
g.drawImage(img, 0, 0, 400, 600, null);
g.setFont(new Font("Georgia", Font.ITALIC, 20));
g.drawString("Hello graphics", 20, 30);
}
public ImageApp() {
try { img = ImageIO.read(new File("villa.jpg"));}
catch (IOException e) { System.out.println("Image File not found"); }
this.addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
char key = e.getKeyChar();
System.out.println("key typed:" + key);
switch (key)
{
case 'h':
this.setVisible(false);
break;
case 'l':
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = c.showOpenDialog(this);
java.io.File folder = c.getSelectedFile();
System.out.println("folder selected:" + folder );
this.imageList = folder.listFiles();
System.out.println("Files:" + java.util.Arrays.toString(this.imageList));
break;
default:
break;
}
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
//return new Dimension(img.getWidth(null), img.getHeight(null));
return new Dimension(400, 600);
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageApp li = new ImageApp();
f.add(li);
li.requestFocusInWindow();
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Loading Images ‹↑›
load an image
try { img = ImageIO.read(new File("villa.jpg"));}
catch (IOException e) { System.out.println("Image File not found"); }
load an image:
java.net.URL imgURL = ImageDemo.class.getResource("path/to/image");
if (imgURL != null)
{ return new ImageIcon(imgURL, "a description"); }
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
Displaying Images ‹↑›
load an image and display it scaled to 400 by 600
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class DisplayImage extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, 400, 600, null);
}
public DisplayImage() {
try { img = ImageIO.read(new File("villa.jpg"));}
catch (IOException e) { System.out.println("Image File not found"); }
}
public Dimension getPreferredSize() { return new Dimension(400, 600); }
public static void main(String[] args) {
JFrame f = new JFrame("Load and Display Image Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new DisplayImage());
f.pack(); f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
displaying an image in a tooltip for a JLabel using swing html (A. Thompson)
import javax.swing.*;
import java.awt.GridLayout;
class ThumbTip {
private static final String HTML = "<html><body>";
ThumbTip(String[] album) {
JPanel p = new JPanel(new GridLayout(1,0,2,2));
for (String url : album) {
String s = HTML + "<img src='" + url.toString() + "'";
String size = " width=200 height=150";
JLabel l = new JLabel(s + size + ">");
l.setToolTipText(s + ">");
p.add(l);
}
JOptionPane.showMessageDialog(null, p);
}
public static void main(String[] args) {
final String[] urls = {
"http://pscode.org/media/stromlo1.jpg",
"http://pscode.org/media/stromlo2.jpg"
};
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ThumbTip(urls);
}
});
}
}
,,,
Scaling Images ‹↑›
scale an image:
Image image = imageIcon.getImage ();
int width = (int) (factor * image.getWidth (null));
int height = (int) (factor * image.getHeight (null));
Image newImage = image.getScaledInstance (width, height, Image.SCALE_SMOOTH);
ImageIcon newImageIcon = new ImageIcon (newImage);
draw an image scaling to frame size
g.drawImage(BuffImg,0,0,getWidth(),getHeight(),this):
resize (scale) an image
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
This example is incomplete, because you still need to actually write
the new image to file- but that is not difficult
scale all image files in a folder
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.io.File;
/**
* ImageScaler
*
* This class loads all images in a given directory and scales them to the
* given sizes, saving the results as JPEG files in a new "scaled/" subdirectory
* of the original directory.
*/
public class ImageScaler {
// Default w/h values; overriden by command-line -width/-height parameters
static int IMAGE_W = 150;
static int IMAGE_H = 250;
public static void main(String args[]) {
// Default directory is current directory, overridden by -dir parameter
String imagesDir = ".";
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-dir") && ((i + 1) < args.length)) {
imagesDir = args[++i];
} else if (args[i].equals("-width") && ((i + 1) < args.length)) {
IMAGE_W = Integer.parseInt(args[++i]);
} else if (args[i].equals("-height") && ((i + 1) < args.length)) {
IMAGE_H = Integer.parseInt(args[++i]);
}
}
// new subdirectory for scaled images
String scaledImagesDir = imagesDir + File.separator + "scaled";
// directory that holds original images
File cwd = new File(imagesDir);
// directory for scaled images
File subdir = new File(scaledImagesDir);
subdir.mkdir();
File files[] = cwd.listFiles();
// temporary image for every scaled instance
BufferedImage scaledImg = new BufferedImage(IMAGE_W, IMAGE_H,
BufferedImage.TYPE_INT_RGB);
Graphics2D gScaledImg = scaledImg.createGraphics();
// Note the use of BILNEAR filtering to enable smooth scaling
gScaledImg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
for (int i = 0; i < files.length; ++i) {
try {
// For every file in the directory, assume it's an image and
// load it
BufferedImage img = ImageIO.read(files[i]);
// If we get here, we must have read the image file successfully.
// Create a new File in the scaled subdirectory
File scaledImgFile = new File(scaledImagesDir + File.separator +
files[i].getName());
// Scale the original image into the temporary image
gScaledImg.drawImage(img, 0, 0, IMAGE_W, IMAGE_H, null);
// Save the scaled version out to the file
ImageIO.write(scaledImg, "jpeg", scaledImgFile);
} catch (Exception e) {
System.out.println("Problem with " + files[i]);
}
}
}
}
http://weblogs.java.net/blog/chet/archive/2004/07/imageio_just_an.html
good stuff about image scaling
Translucency ‹↑›
code for making translucent images, and extending a JLabel
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class TransparentIcon {
public static void main(String[] args) throws Exception {
String imgURL =
"http://www.gravatar.com/avatar/" +
"a1ab0af4997654345d7a949877f8037e";
final BufferedImage image = ImageIO.read(new URL(imgURL));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ImageIcon icon = new ImageIcon(image);
JPanel p = new JPanel(new GridLayout(2,3));
for (int ii=0; ii<6; ii++) {
TransparentLabel tl = new TransparentLabel();
tl.setOpacity((ii+1)/6f);
tl.setIcon(icon);
p.add(tl);
}
JOptionPane.showMessageDialog(null, p);
}
});
}
}
class TransparentLabel extends JLabel {
float opacity = 1f;
public void setOpacity(float opacity) {
this.opacity = opacity;
}
private Icon getTranslucentIcon(Icon icon) {
if (icon!=null) {
BufferedImage bi = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
AlphaComposite ac = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,
opacity);
g.setComposite(ac);
icon.paintIcon(this,g,0,0);
g.dispose();
return new ImageIcon(bi);
} else {
return null;
}
}
public void setIcon(Icon icon) {
super.setIcon( getTranslucentIcon(icon) );
}
}
Clipping Images ‹↑›
Clipping in this context refers to drawing an image within
a particular shape, such as an oval or within the shape of text.
draw an image in the shape of some text using a clip, save image as png file
// get the width and the height from the original image
URL url = new URL("http://i.stack.imgur.com/Nqf3H.jpg");
final BufferedImage originalImage = ImageIO.read(url);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
final BufferedImage textImage = new BufferedImage(
width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
Font font = new Font("Arial", Font.BOLD, 250);
GlyphVector gv = font.createGlyphVector(frc, "Cat");
Rectangle2D box = gv.getVisualBounds();
int xOff = 25+(int)-box.getX();
int yOff = 80+(int)-box.getY();
Shape shape = gv.getOutline(xOff,yOff);
g.setColor(Color.WHITE);
g.setClip(shape);
g.drawImage(originalImage,0,0,null);
g.dispose();
ImageIO.write(textImage,"png",new File("cat-text.png"));
Image Icons ‹↑›
create a jlabel with icon from a scaled buffered image
BufferedImage img = ...;
JLable l = new JLabel(new ImageIcon(img.getScaledInstance(
img.getWidth(null)/2, img.getHeight(null)/2, Image.SCALE_SMOOTH)));
convert an ImageIcon to a BufferedImage
ImageIcon imageIcon =
new ImageIcon("http://pscode.org/media/stromlo2.jpg");
JLabel imageLabel = new JLabel(
"A Horse", imageIcon, SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, imageLabel);
Icon icon = imageLabel.getIcon();
BufferedImage bi = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0,0);
Screen Shots ‹↑›
A screen-shot is an image taken of what happens to be on the
computer screen at a given time.
capture a screen shot.
try
{
Robot robot = new Robot ();
// Capture a particular area on the screen
int x = 100; int y = 100; int width = 200; int height = 200;
Rectangle area = new Rectangle (x, y, width, height);
BufferedImage bufferedImage = robot.createScreenCapture (area);
// Capture the whole screen
area = new Rectangle (Toolkit.getDefaultToolkit ().getScreenSize ());
bufferedImage = robot.createScreenCapture (area);
}
catch (AWTException e) { }
get a buffered image of a jframe and write it to a png file
Component c = f.getContentPane();
BufferedImage i = getScreenShot(c);
try {
ImageIO.write(img, "png", new File("screenshot.png"));
} catch (Exception e) {
e.printStackTrace();
}
public static BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage(
component.getWidth(),
component.getHeight(), BufferedImage.TYPE_INT_RGB
);
// call the Component's paint method, using
// the Graphics object of the image.
component.paint(image.getGraphics());
return image;
}
Saving Images ‹↑›
save a jpeg image with a specified quality (and file compression)
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
...
float quality = 0.85f;
File outfile = new File( "MyImage.jpg" );
BufferedImage image = ...;
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageOutputStream ioStream = ImageIO.createImageOutputStream( outfile );
imgWriter.setOutput( ioStream );
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam( Locale.getDefault() );
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
imgWriter.write(null, new IIOImage(image, null, null), jpegParams );
ioStream.flush();
ioStream.close();
imgWriter.dispose();
,,,,
* similar code to save a compressed jpeg image
private Image getJpegCompressedImage(BufferedImage image) throws IOException {
float qualityFloat = (float)quality.getValue()/100f;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName( "jpg" ).next();
ImageOutputStream ioStream = ImageIO.createImageOutputStream( outStream );
imgWriter.setOutput( ioStream );
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam( Locale.getDefault() );
jpegParams.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
jpegParams.setCompressionQuality( qualityFloat );
imgWriter.write( null, new IIOImage( image, null, null ), jpegParams );
ioStream.flush();
ioStream.close();
imgWriter.dispose();
jpgSize = outStream.toByteArray().length;
BufferedImage compressedImage = ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
return compressedImage;
}
Converting Image Formats ‹↑›
convert to a png compressed image without saving
BufferedImage image = ...;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outStream);
pngSize = outStream.toByteArray().length;
BufferedImage compressedImage =
ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
Animation ‹↑›
animation advice to reduce flicker
In a JPanel, override paintComponent(Graphics) rather than
paint(Graphics) Instead of calling Thread.sleep(n) implement a Swing
Timer for repeating tasks or a SwingWorker for long running tasks.
See "Concurrency in Swing" for more details.
an animation to create 'marching ants' rectangle
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimatedStroke {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BasicStroke dashedStroke;
final int width = 100;
final int height = 30;
final BufferedImage image = new BufferedImage(
width,height,BufferedImage.TYPE_INT_ARGB);
final JLabel label = new JLabel(new ImageIcon(image));
int pad = 5;
final Shape rectangle = new Rectangle2D.Double(
(double)pad,(double)pad,
(double)(width-2*pad),
(double)(height-2*pad));
ActionListener listener = new ActionListener() {
float dashPhase = 0f;
float dash[] = {5.0f,5.0f};
@Override
public void actionPerformed(ActionEvent ae) {
dashPhase += 9.0f;
BasicStroke dashedStroke = new BasicStroke(
1.5f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_MITER,
1.5f, //miter limit
dash, dashPhase
);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
g.setColor(Color.BLACK);
g.setStroke(dashedStroke);
g.draw(rectangle);
g.dispose();
label.repaint();
/*
if (dashPhase<100f) {
try { ImageIO.write(image, "PNG",
new File("img" + dashPhase + ".png"));
} catch(IOException ioe) {}
}*/
}
};
Timer timer = new Timer(40, listener);
timer.start();
JOptionPane.showMessageDialog(null, label);
}
});
}
}
The following animation doesnt flicker much on my pc.
a waveform animation
import java.awt.*;
import javax.swing.*;
public class FlickerPanel extends JPanel implements Runnable {
private float[] pixelMap = new float[0];
// Cached graphics objects to reduce flicker
private Image screenBuffer;
private Graphics bufferGraphics;
public FlickerPanel () {
Thread t = new Thread(this);
t.start();
}
private float addNoise () {
return (float)((Math.random()*2)-1);
}
private synchronized void advance () {
if (pixelMap == null || pixelMap.length == 0) return;
float[] newPixelMap = new float[pixelMap.length];
for (int i=1; i<pixelMap.length; i++) {
newPixelMap[i-1] = pixelMap[i];
}
newPixelMap[newPixelMap.length-1] = addNoise();
pixelMap = newPixelMap;
}
public void run() {
while (true) {
advance();
repaint();
try {
Thread.sleep(25);
} catch (InterruptedException e) {}
}
}
private int getY (float height) {
double proportion = (1-height)/2;
return (int)(getHeight()*proportion);
}
public void paint (Graphics g) {
if (screenBuffer == null || screenBuffer.getWidth(this) != getWidth() || screenBuffer.getHeight(this) != getHeight()) {
screenBuffer = createImage(getWidth(), getHeight());
bufferGraphics = screenBuffer.getGraphics();
}
if (pixelMap == null || getWidth() != pixelMap.length) {
pixelMap = new float[getWidth()];
}
bufferGraphics.setColor(Color.BLACK);
bufferGraphics.fillRect(0, 0, getWidth(), getHeight());
bufferGraphics.setColor(Color.GREEN);
int lastX = 0;
int lastY = getHeight()/2;
for (int x=0; x<pixelMap.length; x++) {
int y = getY(pixelMap[x]);
bufferGraphics.drawLine(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
g.drawImage(screenBuffer, 0, 0, this);
}
public void update (Graphics g) {
paint(g);
}
public static void main (String [] args) {
JFrame frame = new JFrame("Flicker test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new FlickerPanel());
frame.setSize(500,300);
frame.setVisible(true);
}
}
Charts ‹↑›
one option is to use JFreeChart
a simple example with jfreechart
HistogramDataset dataset = new HistogramDataset();
dataset.addSeries("series label",arrayOfValues,noOfBins);
//Create a chart object
JFreeChart chart = ChartFactory.
createHistogram( "plotTitle", "xaxis label", "yaxis label",
dataset, PlotOrientation.VERTICAL, false, false, false);
//If swing application use ChartPanel to render chart
ChartPanel chartPanel = new ChartPanel(chart)
chartPanel.setPreferredSize(new java.awt.Dimension JavaDoc(500, 270));
chartPanel.setMouseZoomable(true, false);
If need to write chart to a file/stream use ChartUtilities.saveChartAsPNG(...)
ChartUtilities.saveChartAsPNG(new File("histogram.PNG"), chart, width, height);
Javamail ‹↑›
Sending and receiving email can be done with the Javamail package
Installing Javamail ‹↑›
Sending Email ‹↑›
send email using a tls connection
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
,,,,
* send an email via smtp and an ssl connection
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Java can parse html in using a number of packages
html tools
JSoup - easy to use |
HtmlEditorKit - a bit more tricky |
parse html
JSoup (jsoup.org)
convert html to text
public static String html2text(String html) {
return Jsoup.parse(html).text();
} }
Html Java Source Code Syntax Highlighting ‹↑›
convert 'Test.java' to syntax highlighted HTML
webcpp Test.java Test.java.html -s
convert 'Test.java' to LaTeX and other formats
highlight -i Test.java -o Test.java.html -L
source-highlight ....
Development Tools For Java ‹↑›
On Microsoft Windows ‹↑›
I am assuming that the windows computer is borrowed and that you dont
really want to spend all your time developing in that environment.
My preferences:
install Vim, and GVim from www.vim.org - this is an somewhat annoying but
useful text editor.
install 'putty' and 'pscp' or 'pftp' so that you can upload your java files to
some server. If you like, just put the .exe files for these programs in
the directory where you are developing, otherwise add the location of the .exe
files to the microsoft 'path' environment variable.
Set up some useful mappings in the _vimrc file. See the section 'Vim and Java'
for a long list of useful mappings.
Put your _vimrc file somewhere like c:\program files\Vim
Vim And Java ‹↑›
Its possible, though possibly not advisable to use the vim
text editor as a java editor. By using mappings and commands we
can simplify the process of compiling and running java programs.
When using Microsoft windows the format of some of these commands are
slightly different owing to the use of the \ backslash in Windows file names
and the different command line syntax used by the Windows console
(for example & and && used to separated multiple commands on one line)
For a great deal of detailed information and recipes about how to use Vim
see bumble.sf.net/books/vim/vim-book.txt
save the current file to a sourceforge server
:!scp % user,project@web.sf.net:folder/subfolder/ (## unix)
:!pscp % user,project@web.sf.net:folder/subfolder/ (## windows)
For the ms windows command, this requires that the pscp program has
been installed, available from the 'putty' website.
make a command 'Sav' (placed in vimrc) to save the current file to sourceforge
com Sav !scp % user,project@web.sf.net:folder/subfolder/
com Sav !pscp % user,project@web.sf.net:folder/subfolder/ (## windows)
The user can upload the current file to the sourceforge server by typing ':Sav'
map the key sequence ';jr' to compile and run the current file with java
map ;jr :!javac % && java %:r<cr>
When the user types ';jr' in normal mode (not insert mode) the current file
will be compiled and run. If the compilation with javac fails, then the
mapping aborts
make an abbreviation to insert the main method in the file
ab public static void main(String[] args) {
java abbreviations
ab public static void main(String[] args) { public static void main(String[] args) {
ab public class Test {
public static void main(String[] args) {}
} public class Test {<cr> public static void main(String[] args) {}<cr> }
,,,
make a mapping of ',jt' which inserts a simple skeleton program
map ,jt 0i public class Test {<cr> public static void main(String[] args) {}<cr>}
save a fragment (between '*' and ',,,') to a file
:?\*?+1,/,,,/-1w Test.java
save a fragment to a file even if it exists
:?\*?+1,/,,,/-1w! Test.java
save a fragment to a file and compile
:?^ *---?+1,/,,,/-1w! Test.java | !javac Test.java
compile and run a java program (between '---' and ',,,')
:?^ *---?+1,/,,,/-1w! Test.java | !javac Test.java; java Test
Note that the java program between the markers must be complete with a main method
the same as above but also works on a Microsoft Windows computer
:?^ *---?+1,/,,,/-1w! Test.java | !javac Test.java && java Test
map ',jf' to compile and run a java program in the document on a unix system
:map ,jf :?^ *---?+1,/,,,/-1w! Test.java \| !javac Test.java; java Test<cr>
and on Microsoft windows compile and run a java program
:map ,jf :?^ *---?+1,/,,,/-1w! Test.java \| !javac Test.java && java Test<cr>
Actually the Windows mapping will also work on Unix systems, since && has the
same meaning in Unix (only execute the second command if the first was successful)
For example, if the document contains the following text containing
a simple java program.
the simplest java program
---
public class Test {
public static void main(String[] args) {
System.out.println("hi");
}
}
,,,
Then typing ',jf' in 'normal' or 'command' mode will extract
and compile and then run the java program contained within the
lines containing '---' and ',,,' The only problem is that
the code must use the class 'Test'
save and compile a java multiline fragment, inserting a class
:?^ *---?+1,/,,,/-1w ! (echo -e 'public class Test {\n public static void main(String[] args) {'; sed 's/a/a/'; echo -e ' }\n}') > Test.java; javac Test.java; java Test.java
create a mapping which compiles and runs a java fragment
map ,jfr :?^ *---?+1,/,,,/-1w ! (echo -e 'public class Test {\n public static void main(String[] args) {'; sed 's/a/a/'; echo -e ' }\n}') > Test.java; javac Test.java; java Test.java
The above will compile and run a fragment of java code in the
current document which is contained between '---' and ',,,,'
Extracting The Java Class Name With Vim ‹↑›
These recipes below are working towards a function which will extract
the java class name from a program within a text document.
put the text of the current line into a variable
:let t = getline('.') | echo t
set a vim variable to the text of the line just above the next empty one
:let line = search("^$") - 1
:let text = getline(line)
set a vim variable to the text of the next line containing the word elephant
:let line = search("elephant")
:let text = getline(line)
set the variable 't' to the next line containing the word 'public'
:let l = search("public") | let t = getline(l) | echo t
split the words of the current line into an array and display the second word
:let text = getline('.') | let words = split(text) | echo words[1]
Using a one character variable name for the array doesnt seem to work.
use a variable as part of a shell command.
:let n = '..' | exe "!dir " . n
In order to use the value of the variable in the shell command we need to
use the exe command which evaluates the concatenated string as a vim command
split the current line on each '(' character
:let t = getline(".") | let res = split(t, '(') | echo res[0]
go back to the first line above which contains split
:exe "?split?"
find the next java class name definition
exe "/^ *public class /" | let words = split(getline('.')) | echo words[2]
just a fragment to test the mapping below
public class Person {
private String first;
private String last;
public Person(String f, String l)
{ this.first = f; this.last = l; }
public void print()
{ System.out.println(this.first + " " + this.last); }
public static void main(String[] args) {
Person t = new Person("Bill", "King");
t.print();
}
}
a mapping to extract the class name from a java program in a document
:map ;jj ?^ *---?<cr> \| :let l = search("^ *public class ") \| echo split(getline(l))[2] <cr>
The beginning of the java program in the document is marked by a line
which starts with '---'
a mapping to extract the class name from a java program in a document
:map ;jj ?^ *---?<cr> \| :let l = search("^ *public class ") \| echo split(getline(l))[2] \| :?^ *---?+1,/,,,/-1w! Frag.java <cr>
extract the class name from a fragment and write to a file with that name
:map ,jr ?^ *---?<cr> \| :let l = search("^ *public class ") \| let class = split(getline(l))[2] \| exe ":?^ *---?+1,/,,,/-1w! " . class . ".java" <cr>
save, compile and run a fragment using the java class name
:map ,jr ?^ *---?<cr> \| :let l = search("^ *public class ") \| let class = split(getline(l))[2] \| exe ":?^ *---?+1,/,,,/-1w! " . class . ".java" \| exe "!javac " . class . ".java && java " . class <cr>
The mapping above is the culmination of the entire preceding section. It uses
several tricky aspects of Vims scripting language and variables. First is searches
backwards for the start of the java code (---), then it finds the line with
the java class name definition, then it assigned the class name to a variable
by calling 2 functions to create an list of words and getting the 3rd word.
Then it uses the "exe" function which is like an "eval" function in other
languages to construct a shell command using the value of the variable which
contains the Java class name. Finally it compiles and runs the java class
:map ,jf :?^ *---?+1,/,,,/-1w! Test.java \| !javac Test.java && java Test<cr>
Viewing Methods With Vim ‹↑›
a dubious but useful way to show public method declarations
:g/^ *public.*) *{*$/
a command to show most public methods in a java file
:command! Me g/^ *public.*) *{*$/
Indenting Within Vim ‹↑›
a mapping to indent a java fragment within a document using astyle
map ,ji :?^ *---?+1,/^ *,,,/-1! astyle -s2<cr>
a mapping to indent a java fragment and indent the result 2 spaces
map ,ji :?^ *---?+1,/^ *,,,/-1! astyle -s2 <bar> sed 's/^/ /'<cr>
indent the whole java file
:%! astyle -s2
:%! astyle -bs2
map ',jii' to indent the whole java file with a 2 space indent
:map ,jii %! astyle -s2<cr>
2 space indent with open brace on the same line
If you are developing in java using vim on a microsoft computer, you
will almost certainly want to use gvim, since the fonts are much nicer.
In gvim select the font which you like, and then type
:set guifont
If you have select 'courier new' size 20, you will see something like
guifont=Courier_New:h20:cANSI
Now open the _vimrc file (windows) or .vimrc file (unix) and put the
following line in the vimrc file
set guifont=Courier_New:h20:cANSI
This will ensure that everytime that gvim starts it will use the specified
font. To do the same for the colorscheme, place the following in the vimrc file
colorscheme elflord
where you replace 'elflord' with whatever colorscheme you like.
Bash And Java ‹↑›
The power and flexibility of the bash shell may help us
in the somewhat clumsy process of developing java applications.
a bash function to show the methods and constructors of java class
function jcl
{
cat << xxx > JJJ.java
import java.lang.reflect.*;
public class JJJ {
public static void main(String args[]) throws Exception {
Class c = Class.forName("java.lang.$1");
Constructor cc[] = c.getDeclaredConstructors();
Method m[] = c.getMethods();
for (int i = 0; i < cc.length; i++) System.out.println(cc[i]);
for (int i = 0; i < m.length; i++) System.out.println(m[i]);
}
}
xxx
javac JJJ.java; java JJJ
}
Indenting ‹↑›
astyle
view a java file nicely indented with 2 spaces
cat test.java | astyle -s2 | less
The indent program was written for the c language but may be
used with java. astyle may be better.
Java People ‹↑›
Bill Joy
One time head of sun, programmer.
fred swartz:
made some good notes, at leepoint.net
Knowledgable Programmers ‹↑›
Vineet Reynolds @ stackoverflow - knows about stuff in java
Andrew Thompson @ stackoverflow -
a contributor to the stack overflow site. Writes very complete code
examples on a range of java topics
x4u @ stackoverflow - knows about images
Glossary ‹↑›
Tooltip -
A little (usually yellow) that pops up when you move your mouse over
an element in a Java Gui Application. The box is supposed to contain
explanatory or helpful text relation to how to use the element highlighted.
Data hiding:
Garbage collection
Memory Management:
Decoupling
Patterns:
Testing ‹↑›
initialization
public class Test {
public int x;
public double d;
public static void main(String[] args) {
Test t = new Test();
System.out.println("x=" + t.d);
}
}
infinite recursion
public class Test {
public static void while()
{ Test.while(); }
public static void main(String[] args) {
Test.while();
System.out.println("=");
}
}
testing char casts
public class Test {
public static void main(String[] args) {
char c = 'e';
int i = (int)'A';
if ((c >= 'a') && (c <= 'z'))
{
System.out.println("c=" + (int)c);
System.out.println("i=" + i);
}
}
}
parseint
public class Test {
public static void main(String[] args) {
String s = "-123";
int i = Integer.parseInt(s);
System.out.println("i=" + i);
}
}
testing char casts
public class Test {
public static void main(String[] args) {
char c = 'e';
int i = (int)'A';
if ((c >= 'a') && (c <= 'z'))
{
System.out.println("c=" + (int)c);
System.out.println("i=" + i);
}
}
}
testing char casts
public class Test {
public static void main(String[] args) {
char c = 'a' + 4;
System.out.println("c=" + c);
}
}
This section contains notes which havent been placed in
their appropriate chapter or section yet.
load an application resource from a jar (not a user resource)
URL iconUrl = this.getClass().getResource("/icons/copy.jpg");
The code above has the disadvantage of downloading the images from
the internet each time they are used.
display a (buffered) image in a message box
JOptionPane.showMessageDialog(parent, new JLabel(new ImageIcon(theImage)));
a logger which publishes to the console
import java.util.logging.*;
class LoggingLevels {
public static void main(String[] args) {
Logger logger = Logger.getAnonymousLogger();
// LOG this level to the log
logger.setLevel(Level.FINER);
ConsoleHandler handler = new ConsoleHandler();
// PUBLISH this level
handler.setLevel(Level.FINER);
logger.addHandler(handler);
System.out.println("Logging level is: " + logger.getLevel());
for (int ii=0; ii<3; ii++) {
logger.log(Level.FINE, ii + " " + (ii*ii));
logger.log(Level.INFO, ii + " " + (ii*ii));
}
}
}
produces output like
Logging level is: FINER
Jun 11, 2011 9:39:23 PM LoggingLevels main
INFO: 0 0
Jun 11, 2011 9:39:24 PM LoggingLevels main
INFO: 1 1
Jun 11, 2011 9:39:24 PM LoggingLevels main
INFO: 2 4
,,,
to investigate, writing log files with the logging package
import java.util.logging.*;
private Logger logger = Logger.getAnonymousLogger();
logger.log(Level.FINER, "Get column styles");
update look and feel after gui has been displayed
try {
UIManager.setLookAndFeel(plafInfos[index].getClassName() );
SwingUtilities.updateComponentTreeUI(frame);
// not necessary to pack but good
frame.pack();
frame.setMinimumSize(frame.getSize());
} catch(Exception e) {
e.printStackTrace();
}
get a screen shot of a jframe component (using BufferedImage)
http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992
set a window location depending on os
jframe.setLocationByPlatform(true);
Modern Loops ‹↑›
String s = "red yellow blue";
String[] splitString = (s.split("\\s+"));
for (String ss: splitString) { System.out.println(ss); }
http://www.daniweb.com/software-development/java/threads/94567/writing-string-to-a-file
a nice visual effect of highlighted words with shadows
StringBuilder since Java 1.5 not synchronized, more efficient, not to be used in threads
StringBuffer can be used in threads
Have the same methods
Use StringBuilder unless you really are trying to share a buffer between threads
insert integers at the beginning of a StringBuilder, this is very inefficient\
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
,,,
use the built in javascript engine in java 1.6 to evaluate a sum
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}
,,,
use javap to generate bytecode or java assembly
3: dup
4: ldc #3; //String bu
6: invokespecial #4; //Method StringBuilder."<init>":(String;)V
9: astore_1
10: ldc #5; //String b
12: astore_2
13: ldc #6; //String u
,,,
By using javap it may be possible to see how the java compiler generates
bytecode.
Reading And Writing Text Files ‹↑›
FileReader and FileWriter can only use the default system encoding
read a file which is encoded in utf8
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader in = new InputStreamReader(fis, "UTF-8");
write a text file encoded as utf8
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
If the encoding is not specified then the default system encoding is used
read utf8 text data from a file
import java.io.*;
public class test {
public static void main(String[] args){
try {
File file = new File("c:\\temp\\test.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(file), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{ System.out.println(e.getMessage()); }
catch (IOException e)
{ System.out.println(e.getMessage());}
catch (Exception e)
{ System.out.println(e.getMessage());}
}
}
,,,
Regular Expressions ‹↑›
Peter Boughton on Stackoverflow- knowledgable chap about regexes
replace all text between tree and leaf with "new" (this is non "greedy"?)
String ResultString = subjectString.replaceAll("(tree).*?(leaf)", "$1new$2");
The $1 and $2 are back references. The .*? is non greedy matching
double all sequences of "a"s using a compiled regular expression
Pattern p = Pattern.compile("(a+)");
String ret = p.matcher(input).replaceAll("$1 $1");
Compiling the regular expression or pattern is supposed to be more efficient.
match any sequence of characters which are not word chars or # or $
Pattern p = Pattern.compile("^[\\w#$]+$");
use a matcher to print each occurence of the 2nd subgroup found
String input = " ;1=2011-10-23T16:16:53+0530; 2=2011-10-23T16:17:53+0530;3=2011-10-23T16:18:53+0530;4=2011-10-23T16:19:53+0530;";
Pattern p = Pattern.compile("(;\\d+?)?=(.+?);");
Matcher m = p.matcher(input);
while(m.find()){
System.out.println(m.group(2));
}
match a string starting with a digit or a non-word char or a whitespace char
Pattern p = Pattern.compile("^\\d|^\\W|^\\s");
Matcher m = p.matcher("stack overflow"); // no matches with this input
parse a string into a date using a SimpleDateFormat
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
final Date date = parser.parse(dateString);
System.out.println(integer + " -> " + date);
} catch (final ParseException pe) {
System.err.println("bad date: " + dateString + ": " + pe);
}
Writing Text ‹↑›
write utf8 text data to a file
import java.io.*;
public class test {
public static void main(String[] args){
try {
File file = new File("c:\\temp\\test.txt");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF8"));
out.append("Website UTF-8").append("\r\n");
out.append("??????? UTF-8").append("\r\n");
out.flush();
out.close();
}
catch (UnsupportedEncodingException e)
{ System.out.println(e.getMessage()); }
catch (IOException e)
{ System.out.println(e.getMessage());}
catch (Exception e)
{ System.out.println(e.getMessage());}
}
}
,,,
The BufferedWriter class has a .newLine() method, but it uses the default
newline character(s) for the system.
run a system command with environment variable
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();
,,,
run a system command and read the output
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
Process p = Runtime.getRuntime().exec("ps -ef");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
,,,
create a temporary file and delete it when the program exits
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
,,,
File System Types ‹↑›
list file system labels or names
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
public class Test2 {
public static void main(String args[]){
List <File>files = Arrays.asList(File.listRoots());
for (File f : files) {
String s = FileSystemView.getFileSystemView().getSystemDisplayName(f);
System.out.println("*" + s);
}
/* output (French WinXP)
REGA1 (C:)
My Book (F:)
/
}
}
,,,
print the types of storage devices currently mounted as filesystems
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String args[]) {
List <File>files = Arrays.asList(File.listRoots());
for (File f : files) {
String s = FileSystemView.getFileSystemView().getSystemTypeDescription(f);
System.out.println("*" + s);
}
/* sample output (French WinXP)
Disquette 3 1/2 pouces
Disque local
Lecteur CD
Disque local
/
}
}
,,,
the above is from rgagnon.com
using printf style format strings, for those who live in the 80s
String.format("http://%s/manager/list", _host + ":8080"));
Http Basic Authentication ‹↑›
a possible alternative for authenticating with "basic" auth on a url
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
,,,
from a Java program, a FileNotFoundException is thrown when you try to read from an InputStream associated with the basic authenticated URL.
upload a file to a server. The server has to know how to receive it
public static void main(String[] args) throws IOException {
File textFile = new File("D:\\file.zip");
String boundary = Long.toHexString(System.currentTimeMillis());
// Just generate some unique value for the boundary.
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/upslet/upload").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
// Send text file.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"file1\"; filename=\"" + textFile.getName() + "\"");
writer.println("Content-Type: application/octet-stream");
FileInputStream fin = new FileInputStream(textFile);
writer.println();
IOUtils.copy(fin, output);
writer.println();
// End of multipart/form-data.
writer.println("--" + boundary + "--");
output.flush();
closeQuietly(fin, writer, output);
// Above request will never be sent if .getInputStream() or .getResponseCode() or .getResponseMessage() does not get called.
connection.getResponseCode();
}
,,,
apache httpclient provides more advanced authentication
The method below is said to work with java 1.1. see the method above
for a more modern technique (use an authenticator)
access a url which is protected by "basic" authentication, untested...
URL url = new URL(¿location address¿);
URLConnection uc = url.openConnection();
String authorizationString = ¿Basic ¿ + Base64.encode("username:password");
uc.setRequestProperty ("Authorization", authorizationString);
InputStream in = url.openStream();
but the Base64 encoding above is not part of standard java, try
------------
byte[] data = . . .;
String encoded = javax.xml.bind.DataTypeConverter.printBase64Binary(data);
byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(encoded);
,,,
read text from a url
try {
URL url = new URL("http://hostname:80/index.html");
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text;
// readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) { }
,,,
another almost identical way to read text from a webpage
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
,,,
I wonder if this is more efficient than readline///
post data using a url and read the reply from the webserver
try {
String data =
URLEncoder.encode("key1", "UTF-8") + "=" +
URLEncoder.encode("value1", "UTF-8") + "&" +
URLEncoder.encode("key2", "UTF-8") + "=" +
URLEncoder.encode("value2", "UTF-8");
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {}
,,,
Jtextpane ‹↑›
get the default font for a text pane
System.out.println(UIManager.get("TextPane.font"));
get the pixel position of the cursor (caret) in jtextpane
------------
Rectangle caretCoords = textpane.modelToView(caretposition);
y = (int) caretCoords.getY();
,,,
loop through a textpanes different styles
JTextPane jtp = new JTextPane();
HTMLDocument doc = (HTMLDocument) jtp.getDocument();
StyleSheet styles = doc.getStyleSheet();
Enumeration rules = styles.getStyleNames();
while (rules.hasMoreElements()) {
String name = (String) rules.nextElement();
Style rule = styles.getStyle(name);
System.out.println(rule.toString());
}
,,,
Gridbag Layout ‹↑›
using a grid bag, its not so hard, just like a table but with spans
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 2;
c.gridheight = 1;
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2, 2, 2, 2);
getContentPane().add(new JScrollPane(pane), c);
Text Components ‹↑›
http://es.scribd.com/doc/89923641/31/JTextComponent-features
very good summary of JTextComponent features.
.createPosition in a text component is like creating a bookmark. The
bookmark doesnt change even when its offset from the start of the
document changes
JTextComponent is complex and is the ancestor of all java text
components. Documents can have a structure such as chapter paragraph
etc.
textArea.setCaretPosition(textArea.getDocument().getLength());
sets the cursor to the end of the ta
create a shape by subtracting one area from another
Area area = new Area(new Rectangle2D.Double(...));
Area inner = new Area(new Rectangle2D.Double(...));
area.subtract(inner);
,,,
Borders ‹↑›
Java swing provides a great deal of flexibility with how
borders are painted around components.
create a new type of border by implementing the interface
public static class GradientBorder implements Border
{
private Insets margin;
public GradientBorder ( int top, int left, int bottom, int right )
{
super ();
margin = new Insets ( top, left, bottom, right );
}
public void paintBorder(
Component c, Graphics g, int x, int y, int width, int height )
{
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint (new GradientPaint(
x, y, Color.RED, x + width, y, Color.BLUE));
Area border = new Area ( new Rectangle ( x, y, width, height ) );
border.subtract ( new Area ( new Rectangle ( x + margin.left, y + margin.top, width - margin.left - margin.right, height - margin.top - margin.bottom ) ) );
g2d.fill ( border );
}
public Insets getBorderInsets ( Component c )
{ return margin; }
public boolean isBorderOpaque ()
{ return true; }
}
,,,
a rounded corder border
class OldRoundedBorderLine extends AbstractBorder {
private final static int MARGIN = 5;
private static final long serialVersionUID = 1L;
private Color color;
OldRoundedBorderLine(Color clr) { color = clr; }
public void setColor(Color clr) { color = clr; }
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
g.drawRoundRect(x, y, width, height, MARGIN, MARGIN);
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(MARGIN, MARGIN, MARGIN, MARGIN);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = MARGIN;
insets.top = MARGIN;
insets.right = MARGIN;
insets.bottom = MARGIN;
return insets;
}
}
,,,
http://stackoverflow.com/questions/4458982/repaint-swing-button-with-different-gradient/5845007#5845007
set the colour gradient on abutton
create a hexagon button
You will have to extend JButton class not AbstractButton. Try the following things and you will get idea
The first move is to subclass JButton.
Then, in your subclass, start by redefining the paintComponent(Graphics) method. If you want any changes.
Then, override paintBorder(Graphics) to give it a shape of hexagon
,,,
create rounded corners on a border, but you cant control the radius
LineBorder(Color color, int thickness, boolean roundedCorners)
Creates a line border with the specified color, thickness, and corner
shape.
set text antialiasing with something like this
g2.setRenderingHint(RenderingHints.KEY_TEXTANTIALIASING, RenderingHints.VALUE_TEXTANTIALIAS_ON);
(com.sun.awt.AWTUtilities) to make your JFrame really transparent.
import com.sun.awt.AWTUtilities;
/* "this" is the JFrame */
this.setUndecorated(true);
AWTUtilities.setWindowOpaque(this, true);
AWTUtilities.setWindowOpacity(this, 0.5f);
AWTUtilities.setWindowShape(this, new RoundRectangle2D.Float(0f, 0f, (float) getWidth(), (float) getHeight(), 15f, 15f));
,,,
another way to make a transparent top level window, w opaque component, but not on linux
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(new Color(0f, 0f, 0f, 0.1f));
f.setUndecorated(true);
f.add(new JLabel("<html>Testing<br>1, 2, 3</html>"));
f.pack();
,,,
http://oreilly.com/catalog/java2d/chapter/ch04.html
a chapter on painting from an oreilly book
idea: to create an angled stripy effect with two colours, use
a gradient paint in cycle mode with the gradient very small, or tight.
Then you could animate the gradient paint to create moving stripes.
This technique can fill a shape with lots of stripes.
make an italic font in the same family
Font f = g.deriveFont(Font.ITALIC);
make a text box with an image in it
use CompoundBorder and MatteBorder
===========================================
a borderlayout with gaps and a title
JPanel p = new JPanel( new BorderLayout(5,5) );
p.setBorder( new TitledBorder("Main GUI") );
,,,
create a menu with control 0 shortcut key and an action listener
JMenuItem screenshot = new JMenuItem("Screenshot");
screenshot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0,
InputEvent.CTRL_DOWN_MASK));
screenshot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// do something here
}};
JMenu menu = new JMenu("Other");
menu.add(screenshot);
JMenuBar mb = new JMenuBar();
mb.add(menu);
jframe.setJMenuBar(mb);
,,,
get a buffered image of a jframe and write it to a png file
Component c = f.getContentPane();
BufferedImage i = getScreenShot(c);
try {
ImageIO.write(img, "png", new File("screenshot.png"));
} catch (Exception e) { e.printStackTrace(); }
public static BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage(
component.getWidth(), component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
component.paint(image.getGraphics());
return image;
}
,,,
create a jlabel with icon from a scaled buffered image
BufferedImage img = ...;
JLable l = new JLabel(
new ImageIcon(img.getScaledInstance(
img.getWidth(null)/2, img.getHeight(null)/2, Image.SCALE_SMOOTH)));
,,,
get a screen shot of a jframe component (using BufferedImage)
http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992
set a window location depending on os
jframe.setLocationByPlatform(true);
set the native system look and feel.
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
initGui();
}
});
}
,,,
Modern Loops ‹↑›
String s = "red yellow blue";
String[] splitString = (s.split("\\s+"));
for (String ss: splitString) { System.out.println(ss); }
Regular Expressions ‹↑›
use the String built in pattern matching
public class Test {
public static final String S = "This is my small example string for testing";
public static void main(String[] args) {
System.out.println(S.matches("\\w.*"));
String[] splitString = (S.split("\\s+"));
for (String string : splitString) {
System.out.println(string);
}
// Replace all whitespace with tabs
System.out.println(s.replaceAll("\\s+", "\t"));
}
}
use compiled patterns and matching loops
-------
Pattern pattern = Pattern.compile("\\w+");
// or Pattern pattern = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("some test string");
// Check all occurance
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
,,,
replace all occurance of whitespace with tabs
---
Pattern replace = Pattern.compile("\\s+");
Matcher matcher2 = replace.matcher("some example string");
System.out.println(matcher2.replaceAll("\t"));
,,,
Constructors ‹↑›
make 2 object contructors, of which one uses a default value
----
public FileSystemModel()
{ this( System.getProperty( "user.home" ) ); }
public FileSystemModel( String startPath ) {
root = startPath;
}
,,,
read a file into a string buffer
----
BufferedReader br = new BufferedReader(fr);
String buffer;
StringBuffer result = new StringBuffer();
while ((buffer = br.readLine()) != null) {
result.append(buffer);
}
,,,
It would probably be faster to read into a larger buffer (8k ?) rather than
just one line.
jlist with a list model
----
import java.awt.*;
import javax.swing.*;
public class List extends JFrame {
public static void main(String[] args) {
List t = new List();
ListModel bigData = new AbstractListModel() {
public int getSize() { return Short.MAX_VALUE; }
public Object getElementAt(int index) { return "Index " +
index; }
};
JList bigDataList = new JList(bigData);
//use the following method for performance reasons
bigDataList.setPrototypeCellValue("Index 1234567890");
JScrollPane js = new JScrollPane(bigDataList);
t.getContentPane().add(js);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
}
,,,
displays a file list in the center of the screen
------
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class List extends JFrame {
public static void main(String[] args) {
List t = new List();
JList bigDataList = new JList((new File(".")).listFiles());
JScrollPane js = new JScrollPane(bigDataList);
JPanel pl = new JPanel(); pl.add(js);
t.getContentPane().add(pl);
t.setSize(new Dimension(300, 300));
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setLocationRelativeTo(null);
t.setVisible(true);
}
}
,,,
display list of files in the current folder in a list box
------
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class List extends JFrame {
public static void main(String[] args) {
List t = new List();
File dir = new File(".");
File[] files = dir.listFiles();
JList bigDataList = new JList(files);
JScrollPane js = new JScrollPane(bigDataList);
JPanel pl = new JPanel(); pl.add(js);
t.getContentPane().add(pl);
t.setSize(new Dimension(300, 300));
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
}
,,,
do something when a jlist item is double clicked
--------
final JList list = new JList(dataModel);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
};
list.addMouseListener(mouseListener);
,,,
list with model and unicode characters
------
import java.awt.*;
import javax.swing.*;
public class List extends JFrame {
public static void main(String[] args) {
List t = new List();
ListModel bigData = new AbstractListModel() {
public int getSize() { return Short.MAX_VALUE; }
public Object getElementAt(int index)
{ return "unicode " + index + "=" + (char)index; }
};
JList bigDataList = new JList(bigData);
bigDataList.setPrototypeCellValue("Index 1234567890");
JScrollPane js = new JScrollPane(bigDataList);
JPanel pl = new JPanel(); pl.add(js);
t.getContentPane().add(pl);
t.setSize(new Dimension(300, 300));
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
}
,,,
a simple file directory TreeModel for use with a JTree element
---------
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.io.*;
public class FileSystemModel implements TreeModel {
String root;
public FileSystemModel() {
this( System.getProperty( "user.home" ) );
}
public FileSystemModel( String startPath )
{ root = startPath; }
public Object getRoot()
{ return new File( root ); }
public Object getChild( Object parent, int index ) {
File directory = (File)parent;
String[] children = directory.list();
return new File( directory, children[index] );
}
public int getChildCount( Object parent ) {
File fileSysEntity = (File)parent;
if ( fileSysEntity.isDirectory() ) {
String[] children = fileSysEntity.list();
if (children == null) return 0;
return children.length;
}
return 0;
}
public boolean isLeaf( Object node )
{ return ((File)node).isFile(); }
public void valueForPathChanged( TreePath path, Object newValue ) {}
public void removeTreeModelListener(TreeModelListener l) {}
public void addTreeModelListener(TreeModelListener l) {}
public int getIndexOfChild( Object parent, Object child ) {
File directory = (File)parent;
File fileSysEntity = (File)child;
String[] children = directory.list();
int result = -1;
for ( int i = 0; i < children.length; ++i ) {
if ( fileSysEntity.getName().equals( children[i] ) ) {
result = i; break;
}
}
return result;
}
public static void main(String[] args)
{
JFrame f = new JFrame();
JTree t = new JTree(new FileSystemModel());
f.getContentPane().add(t);
f.setVisible(true);
}
}
,,,
A Simple Frame Template With A Button ‹↑›
public class Eg extends PPSFrame implements ActionListener
{
private JButton b;
public Eg()
{
b = new JButton("click");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b) {}
if (e.getActionCommand().equals("click")) {}
repaint();
}
public void paintComponent(Graphics g) {}
public static void main(String[] args) {}
}
The Filloval Method ‹↑›
fill an oval
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
private boolean tracing;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.YELLOW);
g.setColor(Color.WHITE);
g.fillOval(100,0,400,400);
}
public static void main(String[] args)
{
Test t = new Test();
}
}
The origin (0,0) is the top left
fillOval: public abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
System.out.println("hello " + i);
System.out.print("hello " + i);
import java.util.Scanner;
Scanner s = new Scanner(System.in);
int i = s.nextInt(); # get next integer
String w = s.next(); # get the next word
String w = s.nextLine(); # get whole line (but not '\n')
Random ‹↑›
A random number from 0-9
java.util.Random g = new java.util.Random();
int i = g.nextInt(10);
System.out.println("i=" + i);
A random element of an array
java.util.Random g = new java.util.Random();
char[] cc = new char[20];
int i = g.nextInt(cc.length);
Constructor ‹↑›
Constructors ARE methods.
public Name(String f, int i) {}
public Name() {}
final String WORD = new String("tree");
private final String WORD = new String("tree");
Methods ‹↑›
!!! method names cant be reserved words ('do', 'while' etc)
public void print() {}
public boolean print() {}
public String print(int i, double d) {}
private static int[] doo() {}
public static int doo(int i) {}
public static void doo(char c) {}
Recursion ‹↑›
Infinite recursion gives stack overflow error (compiles)
Declare ‹↑›
compile errors !!! variable uninitialised
int x; System.out.print("x=" + x);
int x; x=x+1
but NO error if var is an instance variable
private int x; !! initialised to zero
Integer ‹↑›
int x = 2;
parseInt is FUSSY, below throws number format exception
int i = Integer.parseInt("123 ")' !!! NO
int i = Integer.parseInt(" 123")' !!! NO
int i = Integer.parseInt("123\n")' !!! NO
Below is ok
int i = Integer.parseInt("-123")'
Operator Precedence ‹↑›
In normal order, prints '2'
System.out.println("\n result=" + 10*2%3);
Double ‹↑›
Convert a string to a double
double d = Double.parseDouble("-0.223");
java.lang.Math.pow(3,4)
char letter = 'a';
char c = 'a' + 4; (c='e')
Implicit casts to integer are OK in statements
char c = 'A'; int i = 4 + c;
Implicit casts to integer are NOT OK in methods
Test.doo(25); !!! no if "doo(char c)"
Comparisons with characters ok
char c = 'A'; if (c <= 'B') {}
'a'=97, 'A'=65
lower case letter: if ((c >= 'a') && (c <= 'z'))
Convert case
char c = Character.toLowerCase('A');
char c = Character.toUpperCase('a');
Convert a decimal digit to a character
char c = Character.forDigit(4, 10);
Strings ‹↑›
String r, s, t;
String s = new String("cat");
if (s.equals("tree") {}
if (s.equalsIgnoreCase("trEE")) {}
t = "TTR".toLowerCase();
t = "TTR ".trim();
t = "TTR".indexOf('R');
t = "TTR".indexOf("TT");
Starts with and ends with
if ("big".startsWith("bi"))
if ("big".endsWith("ig"))
Matches
if ("009".matches("\\d")) System.out.println("\n\nyes");
Split a string into words
String[] ss = ("Some new words".split("\\s+")); System.out.println(ss[1]);
Substrings
"big".substring(0,2) == "bi"
Comparing strings
System.out.println("this".compareTo("this")); // prints 0
System.out.println("zed".compareTo("this")); // prints 6
System.out.println("us".compareTo("this")); // prints 1
System.out.println("this".compareTo("us")); // prints -1
System.out.println("this".compareTo("thks")); // prints -2
get the hundreds
i = 1234; i=i/100%10;
for (int i=0; i < 5; i++) {}
for (int i=0; i < array.length; i++) {}
Using The Graphics Object ‹↑›
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
private boolean tracing;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.YELLOW);
g.setColor(Color.WHITE);
g.fillOval(0,0,400,400);
g.setFont(new Font("SansSerif",Font.BOLD,32));
g.drawString("Target Practice", 130, 75);
}
public static void main(String[] args)
{ Test t = new Test(); }
}
Watch Out For ‹↑›
array.length() !!! no array.length
Class.make() !!! is 'make' static???
method 'while()' !!! reserved word
Investigate ‹↑›
This section contains subjects and code snippets in java to
investigate
what does this mean, a raster is a kind of pixel map
WritableRaster wr = screen.getRaster();
investigate Maps
Map<?, ?> properties = ((TAudioFileFormat) fileFormat).properties();
xml parsing code, zip extracting, logging code, by A. Thompson
http://stackoverflow.com/questions/8509302/is-this-ods-reader-functional
investigate using JWindows for pop up dialogs or tool tips
JWindow
initialize a boolean array (all element false)
boolean[] array = new boolean[size];
initialize a boolean array to true
Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.TRUE);
,,,
transfer a file via scp, Jsch has a reputation for being tricky to use
use JSch
an alternative to jsch is sshj
https://github.com/shikhar/sshj
DOCUMENT-NOTES: