Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

February 10, 2011

Simple sample to create a dynamic flash card layout in Swing

  • Solid white background
  • Two dynamically resizing text fields
  • Buttons have equal width
  • Buttons float to the top, no more weird grid-based spacing issues
  • Text areas are scrollable
  • Starts out small, but window can be adjusted to any reasonable size, even maximized
package migLayoutCenterExpandTest;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import net.miginfocom.swing.MigLayout;

public class Main {
    static JFrame      frame;

    static JPanel      firstPanel;
    static JPanel      secondPanel;

    static JLabel      firstPanelLabel;
    static JButton     firstPanelButton;

    static JTextArea   textArea1;
    static JTextArea   textArea2;
    static JScrollPane textScrollPane1;
    static JScrollPane textScrollPane2;
    static JButton     button1;
    static JButton     button2;
    static JButton     button3;
    static JButton     button4;
    static JButton     button5;
    static JButton     button6;

    /**
     * @param args
     */
    public static void main(String[] args) {
        createObjects();

        setUpFrame();
        setUpFirstPanel();
        setUpSecondPanel();

        frame.getContentPane().add(firstPanel);
        frame.setVisible(true);
    }

    public static void createObjects() {
        frame = new JFrame();

        firstPanel = new JPanel();

        firstPanelLabel = new JLabel("first label");
        firstPanelButton = new JButton("change screens");

        secondPanel = new JPanel();

        textArea1 = new JTextArea("Text area 1");
        textArea2 = new JTextArea("Text area 2");
        textScrollPane1 = new JScrollPane();
        textScrollPane2 = new JScrollPane();
        button1 = new JButton("Button one text");
        button2 = new JButton("Button two text");
        button3 = new JButton("Button three text");
        button4 = new JButton("Button four text");
        button5 = new JButton("Button five text");
        button6 = new JButton("Button six text");
    }

    public static void setUpFrame() {
        frame.setSize(400, 300);

        JPanel contentPane = (JPanel) frame.getContentPane();
        contentPane.setLayout(new MigLayout("align 50% 50%, filly"));
        contentPane.setBackground(Color.WHITE); // Disable this to debug panel sizes

        frame.addWindowListener(new ExitListener());
    }

    public static void setUpFirstPanel() {
        firstPanel.setLayout(new MigLayout("flowy"));
        firstPanel.setBackground(Color.WHITE);

        firstPanel.add(firstPanelLabel, "align 50%");
        firstPanel.add(firstPanelButton, "align 50%");

        firstPanelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Container contentPane = frame.getContentPane();
                contentPane.removeAll(); // Required for new stuff to appear
                contentPane.add(secondPanel); // Required for new stuff to appear; this _is_ the new stuff, after all
                ((JPanel) contentPane).revalidate(); // Required for new stuff to appear
                contentPane.repaint(); // Without this, old stuff isn't removed before new stuff is painted and is still visible underneath
            }
        });
    }

    public static void setUpSecondPanel() {
        secondPanel.setLayout(new MigLayout("fill, flowy"));
        secondPanel.setBackground(Color.WHITE);

        secondPanel.setPreferredSize(new Dimension(1650, 1080));
        secondPanel.setMinimumSize(new Dimension(300, 200));
        secondPanel.setMaximumSize(new Dimension(1920, 1080));

        textScrollPane1 = new JScrollPane(textArea1);
        textScrollPane2 = new JScrollPane(textArea2);

        textScrollPane1.setBackground(Color.WHITE);
        textScrollPane2.setBackground(Color.WHITE);

        textScrollPane1.setBorder(BorderFactory.createTitledBorder("Text area 1"));
        textScrollPane2.setBorder(BorderFactory.createTitledBorder("Text area 2"));

        textScrollPane1.setPreferredSize(new Dimension(400, 300));
        textScrollPane2.setPreferredSize(new Dimension(400, 300));

        // cell col row [span x [span y]]
        secondPanel.add(textScrollPane1, "cell 0 0 1 1, push, grow");
        secondPanel.add(textScrollPane2, "cell 0 1 1 1, push, grow");
        secondPanel.add(button1, "cell 1 0 1 2, aligny top, growx");
        secondPanel.add(button2, "cell 1 0, growx");
        secondPanel.add(button3, "cell 1 0, growx");
        secondPanel.add(button4, "cell 1 0, growx");
        secondPanel.add(button5, "cell 1 0, growx");
        secondPanel.add(button6, "cell 1 0, growx");
    }
}

class ExitListener extends WindowAdapter {
    public void windowClosing(WindowEvent event) {
        System.exit(0);
    }
}

February 4, 2011

Simple sample to replace the contents of a content pane in Swing


package swingTest;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class Main
{
static JFrame frame;

static JPanel firstPanel;
static JPanel secondPanel;

static JLabel firstPanelLabel;
static JButton firstPanelButton;

static JLabel secondPanelLabel;

/**
* @param args
*/
public static void main(String[] args)
{
createObjects();

firstPanel.add(firstPanelLabel);
firstPanel.add(firstPanelButton);

firstPanelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
Container contentPane = frame.getContentPane();
contentPane.remove(firstPanel); // Required for new stuff to appear
contentPane.add(secondPanel); // Required for new stuff to appear; this _is_ the new stuff, after all
((JPanel) contentPane).revalidate(); // Required for new stuff to appear
contentPane.repaint(); // Without this, old stuff isn't removed before new stuff is painted and is still visible underneath
}
});

secondPanel.add(secondPanelLabel);

frame.addWindowListener(new ExitListener());
frame.getContentPane().add(firstPanel);
frame.setVisible(true);
}

public static void createObjects()
{
frame = new JFrame();
frame.setSize(500, 500);

firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout());
firstPanelLabel = new JLabel("first label");
firstPanelButton = new JButton("first button");

secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout());
secondPanelLabel = new JLabel("second label");
}
}

class ExitListener extends WindowAdapter
{
public void windowClosing(WindowEvent event)
{
System.exit(0);
}
}

July 12, 2010

Package becomes unrecognized in Eclipse

Error:
Saving a Java source file in Eclipse causes the errors "[class] cannot be resolved to a type" and "The import org.oasis_open.docs.[whatever] cannot be resolved" for classes in a package that was previously recognized.

Solution:
Open the context menu for the affected package in Package Explorer, select Build Path > Configure Build Path... and go to the "Order and Export" tab. Make sure custom classes are at the top, third-party files are in the middle and the JRE is at the bottom of the list. Select OK and refresh the affected files/packages.

July 6, 2010

The Java heap

The young generation consists of eden plus two survivor spaces. Objects are initially allocated in eden. One survivor space is empty at any time, and serves as a destination of the next, copying collection of any live objects in eden and the other survivor space. Objects are copied between survivor spaces in this way until they are old enough to be tenured, or copied to the tenured generation.

-Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine by Sun

The Java HotSpot VM defines two generations: the young generation (sometimes called the "nursery") and the old generation. The young generation consists of an "Eden space" and two "survivor spaces." The VM initially assigns all objects to the Eden space, and most objects die there. When it performs a minor GC, the VM moves any remaining objects from the Eden space to one of the survivor spaces. The VM moves objects that live long enough in the survivor spaces to the "tenured" space in the old generation. When the tenured generation fills up, there is a full GC that is often much slower because it involves all live objects. The permanent generation holds all the reflective data of the virtual machine itself, such as class and method objects.

-Using JConsole by Sun

See figure at either link above (both use the same figure).

Mark-and-Sweep Garbage Collection, used in Tenured Generation GC
Stop-and-Copy Garbage Collection, used in Young Generation GC
The Copy Algorithm, used in the Stop-and-Copy method of GC

June 28, 2010

Create and print a simple XML document in Java using javax.xml.transform.Transformer


package pkg;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Bar
{
public static void main(String[] args)
{
List properties = new ArrayList();
properties.add(new DummyObject("n1", "t1", "v1"));
properties.add(new DummyObject("n2", "t2", "v2"));
properties.add(new DummyObject("n3", "t3", "v3"));
properties.add(new DummyObject("n4", "t4", "v4"));
properties.add(new DummyObject("n5", "t5", "v5"));
properties.add(new DummyObject("n6", "t6", "v6"));
properties.add(new DummyObject("n7", "t7", "v7"));
properties.add(new DummyObject("n8", "t8", "v8"));
properties.add(new DummyObject("n9", "t9", "v9"));

// Create XML document tree
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document documentTree = null;
Element dummyParent = null;
try
{
db = dbf.newDocumentBuilder();
documentTree = db.newDocument();
dummyParent = documentTree.createElement("DummyParent");
documentTree.appendChild(dummyParent);

for (DummyObject property : properties)
{
// Create XML tags for the property
Element propertyNode = documentTree.createElement("Property");
Element nameNode = documentTree.createElement("Name");
Element typeNode = documentTree.createElement("Type");
Element valueNode = documentTree.createElement("Value");

// Populate the property's XML tags
nameNode.setTextContent(property.getName());
typeNode.setTextContent(property.getType());
valueNode.setTextContent(property.getValue());

// Add the data to the property node
propertyNode.appendChild(nameNode);
propertyNode.appendChild(typeNode);
propertyNode.appendChild(valueNode);

// Add the property node to the XML tree
dummyParent.appendChild(propertyNode);
}

DOMSource source = new DOMSource(documentTree);
StreamResult result = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(source, result);
}
catch (ParserConfigurationException e)
{
System.out.println("D'oh! Creating the document failed.");
System.out.println(e.getMessage());
}
catch (TransformerException e)
{
System.out.println("D'oh! Transformer failed.");
System.out.println(e.getMessage());
}
}
}

class DummyObject
{
String name;
String type;
String value;

public DummyObject()
{
super();
}

public DummyObject(String n, String t, String v)
{
name = n;
type = t;
value = v;
}

public String getName()
{
return name;
}

public String getType()
{
return type;
}

public String getValue()
{
return value;
}
}

June 1, 2010

[Tom] Duff's Device

Duff's Device is mentioned in the JLS section about switch statements. The nitty-gritty is explained at this StackOverflow answer.

Sample code:

package pkg;

public class Foo
{
public static void main(String args[])
{
int numTimesToCallMethod = 20;
int numTimesToRunWhile = (numTimesToCallMethod + 7) / 8;

switch (numTimesToCallMethod%8)
{
case 0:
do {
IllHaveADuffYouHaveOneToo(); // Great C hack, Tom,
case 7: IllHaveADuffYouHaveOneToo(); // but it's not valid here.
case 6: IllHaveADuffYouHaveOneToo();
case 5: IllHaveADuffYouHaveOneToo();
case 4: IllHaveADuffYouHaveOneToo();
case 3: IllHaveADuffYouHaveOneToo();
case 2: IllHaveADuffYouHaveOneToo();
case 1: IllHaveADuffYouHaveOneToo();
} while (--numTimesToRunWhile > 0);
}
}

public static void IllHaveADuffYouHaveOneToo()
{
System.out.println();
}
}


MyEclipse 8.5 shows two errors at the semicolon immediately before "Great C hack...":
Multiple markers at this line
- Syntax error, insert "while ( Expression ) ;" to complete DoStatement
- Syntax error, insert "}" to complete Block

April 21, 2010

Weak references in Java

there are actually four different degrees of reference strength: strong, soft, weak, and phantom

The important part about strong references — the part that makes them "strong" — is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection.

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.

Understanding Weak References by Ethan Nicholas

March 16, 2010

javadoc.exe man page

http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html

Generating Javadoc using MyEclipse

It seems that some versions of MyEclipse don't have the "Generate Javadoc..." option under the main Project menu that "regular" Eclipse does, at least MyEclipse 7.5. The facility for generating Javadoc is still somewhere; one workaround way to access it is by opening the help menu, searching for "javadoc" and opening the second result, "Javadoc Generation." That help file has a link to the Javadoc Generation wizard.

March 2, 2010

Validating XML against schemas in Java

XML validation with namespaces will not work properly unless the DocumentBuilderFactory has namespace awareness turned on manually, via setNamespaceAware.

January 13, 2010

Intro to working with XML using Java

Rob Lybarger wrote a great intro article about this, the link skips to page two of five: Working with XML and Java

January 7, 2010

Array index behavior in Java

int indexFor1D = 3;
int indexFor2D = 1;
int [] array1D = { 5, 6, 7, 8, 9 };
int [][] array2D = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};

System.out.println("From 2D: " + array2D[indexFor2D++][indexFor2D++]);
System.out.println("indexFor2D: " + indexFor2D);

array1D[indexFor1D++] = indexFor1D;
System.out.println("indexFor1D: " + indexFor1D);
System.out.print("New 1D: ");
for(int tmp : array1D)
System.out.print(tmp);


produces output

From 2D: 5
indexFor2D: 3
indexFor1D: 4
New 1D: 56749

Nerd Sniping or: Finally Always Wins, Unless You Crash The Machine Beforehand.

try {
return true;
} finally {
return false;
}


http://stackoverflow.com/questions/1995113/strangest-language-feature/2005435#2005435

January 6, 2010

Rules for bits in Java

All integer literals are, by default, ints in Java. All floating point literals are, by default, doubles. If a value larger than allowed is put into a given primitive type, the leftmost bits are discarded. So,

char c = (char) 65656; // Binary 00000000000000010000000001111000
byte i = (byte) 130; // Binary 00000000000000000000000010000010

A char is 16 bits, so it is set to 0000000001111000, which equals 1111000, which is 120, which in turn is the character 'z'; a byte is eight bits, so it is set to 10000010. Since the first bit is a sign bit, this actually equals -126. (By two's complement, 10000010 = -(01111101 + 1) = -(01111110) = -126.)

Division by zero in Java

Incredibly, the following code will compile without any problems:


int x = 7/0;
System.out.println(x);

int y = 0;
int z = 7/y;
System.out.println(z);


When the inevitable runtime error occurs, it appears as an ArithmeticException; there is no such thing as DivideByZeroException.

January 5, 2010

Increment and decrement for array indices in Java

This code


int anIndex = 1;
int [][] anArray = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
System.out.println("Number: " + anArray[anIndex++][anIndex++] + ".");


prints out "Number: 5." That's anArray[1][2]; anIndex is incremented after each index, so it ends up at 3 by the end of the code fragment.

Concatenation to strings in Java


System.out.println("" + 1 + 2);
System.out.println(1 + "" + 2);
System.out.println(1 + 2 + "");


results in

12
12
3

Java instanceof operator

instanceof checks true runtime values. So, the following code would print:


Object o = new LinkedList();
if(o instanceof LinkedList)
System.out.println("yep");


This is not the same behavior as method lookup (find the fancy name for this). This example would produce an error:


List theList = new Queue();
theList.enqueue(new Object());

Class initialization in Java

"Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down." -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)

Class loading time is the same as initialization time, which is described right at the top of section 12.4 of the Java Language Specification.

What happens if more than one class contains static init blocks? Are static init blocks guaranteed to run? My question at Stack Overflow covers these questions.

What about multiple instances of a class? As expected, the static initialization blocks do NOT run again. Modifying main() from the link above to this:


System.out.println("START");
new Child();
System.out.println("MIDDLE");
new Child();
System.out.println("END");


produces this output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
MIDDLE
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END