суббота, 8 сентября 2012 г.

Enums and annotations

Personally I have never used these Java features. But they might not be surprising to you.

The first one

Enum defines a class, so I can use it just like any normal class: create constructor, add methods, fields and so on. For example:


    enum BeadType {

        ROUND_BEAD(10, 10), 
        CYLINDRIC_BEAD(10, 15), 
        OTHER_BEAD(20, 20);

        private final int width;
        private final int height;

        BeadType(int w, int h) {
            this.width = w;
            this.height = h;
        }

        public int getW() {
            return width;
        }

        public int getH() {
            return height;
        }
    }

I really like it.

The second one

Annotations. I suppose, that almost everyone has at least once used @Override annotation. But did you know that you can create your own type of annotation and even make it to be documented in your Javadoc-documentation (just add @Documeted before your own annotation definition). I was surprised!

    @Documented
    @interface MyAnnotation {

        String myName();

        int myAge();

        String email();
    }

    @MyAnnotation(
            myName = "Nastya",
            myAge = 20,
            email = "zminyty@gmail.com")

воскресенье, 4 марта 2012 г.

Closable java tabs

There is no predefined JTabbedPane in Java with closable tabs, so I decided to make it myself.
No doubts, there are a lot of variations of doing this with standard close icons. I wanted to make it in such a way, that only when you double click on tab - it closes.

Code:


import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;


/**
 *
 * @author Aloren
 */
public class CloseTabbedPane extends JTabbedPane {


    public CloseTabbedPane() {
        super();
        tabbedPane.addMouseListener(new CloseMouseListener(handler));
    }


    private static class CloseMouseListener extends MouseAdapter {


        int oldIndex;


        public CloseMouseListener() {
        }


        @Override
        public void mouseClicked(MouseEvent e) {
            CloseTabbedPane pane = (CloseTabbedPane)e.getSource();
            int i = pane.indexAtLocation(e.getX(), e.getY());
            if (e.getClickCount() == 2) {
                if (i != -1) {
                    pane.remove(i);
                    if (pane.getTabCount() == 0) {
                        ((JFrame) SwingUtilities.getRoot(pane)).dispose();
                        System.exit(0);
                    }
                }
            } else {
                pane.getModel().setSelectedIndex(i);
            }
        }
    }
}