Z-value on imageicon/jlabel

Hi wonder how to put a z-value on a imageicon or jlabel? (which to be on top, and second..etc)
Thanks in advance!

Swing related questions should be posted in the Swing forum.
Use a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout or a [url http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html]LayeredPane.

Similar Messages

  • JLabel Icon Update Question

    Hi. I have created a jLabel that get's it's Icon updated via a value derived from a MYSQL query. The Icon1 value is a URL. My question is, if I do the MYSQL query and the URL doesn't change from the existing value, does the jLabel still go out and pull the image over? Or does it recognize that the URL is still the same and doesn't make an attempt at pulling the image over? Basically, I am asking this because I'm trying to determine the load on my webserver. Thank you for your help!
    image1.setIcon(icon1);

    Hi Daryl. Here is what I'm doing:
    protected static ImageIcon createImageIcon(String URL,
                                                   String description) {
            //java.net.URL imgURL = LabelDemo.class.getResource(URL);
            java.net.URL imgURL = null;
        try {
          imgURL = new java.net.URL(URL);
        } catch (Exception e) {
          //Logger.getLogger(LabelDemo.class.getName()).log(Level.SEVERE, null, ex);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + URL);
                return null;
    ImageIcon icon1 = createImageIcon("https://www.website.com/images/" + dateVal + "/thumbs/" + image2Val + "",
                       image1.setIcon(icon1);

  • Displaying JList holding JLabel with icons of different height screwed up

    I started to create a unix 'make' wrapper, which filters for the binaries being created and display their names and potentially some icon for those in a JList.
    But sometimes the display of the icons is screwed up. It's cut to the size of a pure text (JLabel) line in the JList.
    Below you can find test program.
    You need to put two different sized picture files binary1.jpg and binary2.jpg in the run directory of the java build (i use eclipse)
    and create some test input file like this:
    > cat input
    binary1
    binary2
    binary3
    binary4
    binary5
    binary6
    binary7
    binary8
    binary9
    Set TEST_DIR environment variable to the build run directory.
    Finally start the java class like this:
    > bash -c 'while read line; do echo $line; sleep 1; done' < input| (cd $TEST_DIR; java -classpath $TEST_DIR myTest.MyTest)
    Then you should see the issue.
    ( Don't mind about the JAVA code in general - i know, that there are quite some other issues to fix :-) )
    - many thanks!
    best regards,
    Frank
    ================================================
    package myTest;
    import java.io.*;
    import java.util.HashMap;
    import java.util.Map;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Dimension;
    import javax.imageio.ImageIO;
    import javax.swing.DefaultListModel;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.ListCellRenderer;
    public class MyTest {
        static class MyCellRenderer extends JLabel implements
                ListCellRenderer<Object> {
            private static final long serialVersionUID = 577071018465376381L;
            public MyCellRenderer() {
                setOpaque(true);
            public Component getListCellRendererComponent(JList<?> list,
                    Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                if (value.getClass().equals(JLabel.class)) {
                    JLabel label = JLabel.class.cast(value);
                    setText(label.getText());
                    setIcon(label.getIcon());
                    setBackground(label.getBackground());
                    setForeground(label.getForeground());
                } else {
                    setText(value.toString());
                    setBackground(Color.WHITE);
                    setForeground(Color.BLACK);
                return this;
        static final Map<String, String> fileToPicture = new HashMap<String, String>() {
            private static final long serialVersionUID = 1L;
                put("binary1", "binary1.jpg");
                put("binary2", "binary2.jpg");
        static boolean endProcess;
        static boolean guiStarted;
        static DefaultListModel<Object> listModel;
        static JList<Object> list;
        static public void startGui() {
            JFrame frame = new JFrame("Building...");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            listModel = new DefaultListModel<Object>();
            list = new JList<Object>(listModel);
            list.setCellRenderer(new MyCellRenderer());
            list.setLayoutOrientation(JList.VERTICAL);
            list.setFixedCellHeight(-1);
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setPreferredSize(new Dimension(300, 500));
            frame.getContentPane().add(scrollPane, BorderLayout.NORTH);
            JButton ok = new JButton("CLOSE");
            ok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    endProcess = true;
            frame.getContentPane().add(ok, BorderLayout.SOUTH);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            guiStarted = true;
        static private void addElem(String string, Color color) {
            String fileName = fileToPicture.get(string);
            ImageIcon icon = null;
            if (null != fileName) {
                File file = new File(new File(".").getAbsolutePath() + "/"
                        + fileName);
                try {
                    icon = new ImageIcon(ImageIO.read(file));
                } catch (IOException e) {
                    System.err
                            .println("Exception: IOException for trying to read file '"
                                    + file + "'");
                    e.printStackTrace();
            JLabel label = new JLabel(string);
            Color darker = color.darker();
            label.setForeground(darker);
            label.setBackground(Color.WHITE);
            label.setIcon(icon);
            listModel.addElement(label);
            list.ensureIndexIsVisible(list.getModel().getSize() - 1);
        public static void main(String[] args) {
            endProcess = false;
            guiStarted = false;
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    startGui();
            while (!guiStarted) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            try {
                while (!endProcess) {
                    line = br.readLine();
                    if (line == null) {
                        break;
                    addElem(line, Color.BLACK);
                    System.out.println(line);
            } catch (IOException e) {
                e.printStackTrace();
            if (!endProcess) {
                addElem("...DONE", Color.RED);
                while (!endProcess) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            System.exit(0);

    I found out, that the issue is caused by trying to use auto-scrolling via line #100:
    list.ensureIndexIsVisible(list.getModel().getSize() - 1);
    this helped to solve it:
    java - ensureIndexIsVisible(int) is not working - Stack Overflow
    The result is:
    if (autoScroll.isSelected()) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             list.ensureIndexIsVisible(list.getModel().getSize() - 1);
    rgds,
    Frank

  • JList with ImageIcon

    Hello,
    Can I have JList with an ImageIcon beside it?e.g
    "imageicon" "sometext"
    code snippet would be helpful.
    Thanks

    Hello,
    little improvement-update, custom ListCellRenderer now checks whether object is a String only or a JLabel with an ImageImage. You can use it for both versions of JLists.
    import javax.swing.*;
    import java.awt.*;
    public class ImageTextList extends JFrame
         private static String[]text = new String[10];
         private static JLabel[]labels = new JLabel[text.length];
         private static ImageIcon[] icons = new ImageIcon[labels.length];
         static
              for(int i=0; i<text.length; i++)
                   text[i]   = "Images " + (i+1);
                   icons[i]  = new ImageIcon(     "../testproject/img/" + (i+1) + ".jpg");
                   labels[i] = new JLabel(text, icons[i], JLabel.CENTER);
         public static void main(String[] args)
              new ImageTextList();
         public ImageTextList()
              super("Image+Text in a JList");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //test with labels and text
              JList list = new JList(labels);
              list.setCellRenderer(new MyCellRenderer());
              getContentPane().add(new JScrollPane(list));
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         class MyCellRenderer extends JLabel implements ListCellRenderer
              private JLabel label = null;
              // This is the only method defined by ListCellRenderer.
              // We just reconfigure the JLabel each time we're called.
              public Component getListCellRendererComponent(
                   JList list,
                   Object value,
              // value to display
              int index, // cell index
              boolean isSelected, // is the cell selected
              boolean cellHasFocus) // the list and the cell have the focus
                   String s = value.toString();
                   ImageIcon icon = null;
                   //checks whether the source is a label or another object(String only)
                   if(value instanceof JLabel)
                   {System.out.println("label");
                        label = (JLabel)value;
                        icon = (ImageIcon)label.getIcon();
                        s = label.getText();
                   setText(s);
                   setIcon(icon);
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   } else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   setEnabled(list.isEnabled());
                   setFont(list.getFont());
                   setOpaque(true);
                   return this;
    regards
    Tim

  • Touble getting cell values from jTable

    Hi everybody, I need some hepl to understand this problem.
    I have jtable and I�m trying to get the values from the cells (first in the jOption panel then to jLabel and to jTextFields).
    All cell values are shown perfectly in the JOptionPanel.
    But I can�t get any values to the jLabel from the first column(0) no matter what row I press from the firts column.
    It gives me this error
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer
         at taulukko3.FTaulukko3.jTable1_mouseClicked(FTaulukko3.java:163)Here is my code where I think the problem is:
    public void jTable1_mouseClicked(MouseEvent e) {
       JOptionPane.showMessageDialog(this,jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn()));
          try{
          int valittusarake = jTable1.getSelectedColumn();
           String tulos= "";
           if (valittusarake == 0) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                      jTable1.getSelectedColumn());
            jLabel1.setText(tulos);
           if (valittusarake == 1) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField1.setText(tulos);
           if (valittusarake == 2) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField2.setText(tulos);
    }

    Hi everybody
    I got it workin by making this change to my code:
          if (valittusarake == 0) {
             Object tulos1 = jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn());
             jLabel1.setText(tulos1.toString());
          }

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 1) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • JComboBox : colors in the selected value field

    I have a JComboBox with a custom ListCellRenderer. However the JComboBox seems to change the colors of the Component that my ListCellRenderer creates when the Component is in the Selected value field. Some code is below...
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class ComboBoxTest {
      public static final void main(String[] args) {
        JComboBox cbox;
        Vector elements;
        elements = new Vector();
        elements.add("One");
        elements.add("Two");
        elements.add("Three");
        cbox = new JComboBox(elements);
        cbox.setRenderer(new MyRenderer());
        cbox.setEditable(false);
        JFrame frame = new JFrame();
        JPanel content = (JPanel) frame.getContentPane();
        content.add(cbox);
        frame.pack();
        frame.setVisible(true);
    class MyRenderer implements ListCellRenderer {
      public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
        String strValue;
        JLabel label;
        strValue = (String) value;
        label = new JLabel("<" + strValue + ">");
        label.setOpaque(true);
        if( isSelected ) {
          label.setForeground(Color.black);
          label.setBackground(Color.green);
        } else {
          label.setForeground(Color.white);
          label.setBackground(Color.black);
        return label;
    }This code simply creates a JComboBox with 3 String values, "One", "Two", and "Three". The renderer creates a JLabel with the String value enclosed in triangle brackets. The renderer also sets the colors of the JLabel to white on black if unselected and black on green if selected.
    When I run this program, the list portion of the JComboBox looks correct, but the entry in the edit field is wrong. It has the enclosing triangle brackets around the selected String, but the colors are still the default black on gray.
    What do I need to do to get the colors in the edit field to display correctly?
    - James

    A JComboBox is similar to a JSpinner in the sense that it has an associated editor that has an associated textfield....check out the link shown below
    http://forum.java.sun.com/thread.jsp?forum=57&thread=385077
    ;o)
    V.V.

  • Giving a Class an ImageIcon

    hello all,
    i am a relative beginner to java and am having a small bit of difficulty in a small venture, and was wondering if someone could help.
    I am in the middle of creating a top-down tile-based turn-based engine. I am currently at very early stages.
    - i have a class called "tile". This only contains code for two ints (TerrainType and MovementCost).
    - I make a grid of references, and then apply a whatever.tile to each reference, using an array, which defines the map.
    - The trouble is at the nestedloop, where i cannot apply an "ImageIcon" to class.tile.
    How should i change my code? By the way, this is my 2nd version of this - The first version, used jLabels instead of class.tile, and it worked fine. However i couldnt figure out how to apply attributes to it.
    *****CODE******
    ImageIcon block = new ImageIcon("block.gif");
    ImageIcon grass = new ImageIcon("grass.gif");
    tile t0 = new tile();
    tile t1 = new tile();
    tile t2 = new tile();
    tile t3 = new tile();
    ArrayList tt = new ArrayList();
    tt.add("0");
    tt.add("0");
    tt.add("0");
    tt.add("1");
    tt.add("x");
    int max_rows = 2;
    int max_cols = 2;
    int x = 0;
    tile[][] grid = new tile[max_rows][max_cols];
    grid[0][0] = t0;
    grid[0][1] = t1;
    grid[1][0] = t2;
    grid[1][1] = t3;
    for (int r = 0; r < max_rows; r++) {
    for (int c = 0; c < max_cols; c++) {
    if (tt.get(0).equals("0")){
    grid[r][c].setIcon(grass); <<<<error
    tt.remove(0);}
    else if (tt.get(0).equals("1")){
    grid[r][c].setIcon(block); <<<<error
    tt.remove(0);}
    **********class code*****
    package mapalpha;
    public class tile {
    int TerrainType;
    int MovementCost;
    public tile() {
    }

    To add an 'attribute' to a JLabel: since JLabel extends from JComponent you can use the 'putClientProperty' and the 'getClientProperty' methods to store/retrieve attribute-type information in the component. See the method detail section for each method in the JComponent api.
    On your current design: you can put anything you want in your custom Tile class - ImageIcon, JLabel, JPanel, an image...
    class Tile
        int terrainType, movementCost;
        BufferedImage image;
        ImageIcon icon;
        JLabel label;
        public Tile(args for instantiation if you like...)
        protected void setIcon(ImageIcon icon)
            this.icon = icon;
            // other activity if you like
    }If you want an image/graphics component you could have Tile extend JPanel or JLabel. Then you could override the 'paintComponent' method in JPanel and draw your image/graphics. If extending JLabel simply call 'setIcon' which will be a JLabel method - not the same as in the pseudo code above (which is a 'set' method for the Tile class).

  • Complete beginners help.using ImageIcon and cant assign images

    how do assign the ImageIcon for the front and back to this class.i have two gif files in the same directory. to test the card class i want to press the flip button to display the front and then the back. i am making simple card game but am very new to this and am stumbling at the basics.any help much appreciated. here is my attempt at the code.
    ( havent put in the paint() )
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class JCard extends JComponent
    private int value;
    private ImageIcon FrontImg;
    private ImageIcon BackImg;
    private int size;
    private boolean faceup;
         public JCard()
    this.value= value;
    public int getValue()
    return value;
    //returns the width of the card
    public int getWidth()
    return getSize().width;
    //returns the height of the card
    public int getHeight()
    return getSize().height;
    //returns true if the card is face up
    public boolean faceup()
    return faceup;
    //flips the card
    public void flip()
    if(faceup)
    faceup = false;
    else
    faceup = true;
    repaint();
    public void setBackImg(ImageIcon img)
    BackImg = img;
    public void setFrontImg(ImageIcon img)
    FrontImg = img;
    public void paint(Graphics g)
    //test JCard
    import javax.swing.*;
    import java.awt.event.*;
    public class TestJCard extends JFrame implements ActionListener
         private JCard card = new JCard();
         private JButton b1 = new JButton("flip");
    public TestJCard()
    super();
    JPanel p = (JPanel)getContentPane();
    p.add("Center",card);
    p.add("South",b1);
    b1.addActionListener(this);
    public void actionPerformed(ActionEvent ae)
    card.flip();
    //** To close window**//
    class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent we)
    we.getWindow().hide();
    System.exit(0);
         public static void main(String args[])
    TestJCard fm = new TestJCard();
    fm.setSize(300,300);
    fm.setVisible(true);

    I'm not sure if I understand exactly what you're asking, but if you're wondering how to create/initialize and ImageIcon from an image file on a local disk, I believe it is as simple as:
    ImageIcon i = new ImageIcon("path/filename.ext");
    note: the path can be relative (i.e. "images/pict1.gif")
    or explicit ("c:/project1/images/pict1.gif").
    Hope this is what you're looking for.

  • Problems with animaged gif's

    Hi, I'm trying to draw a ComboBox with animated gifs in the selection list.
    And the problem is that the gifs are painted but always with the same image. Here it is part of the source code of the ListCellRenderer class.
    In the paint(Graphics g) function I have:
    "g.drawImage(((ImageIcon)icon).getImage(),rect.x,rect.y,this);"
    and if I use the following we've the same result
    "icon.paintIcon(this,g,rect.x,rect.y);"
    It is also rewritten the function: "imageUpdate" and it makes the gif to be repainted every 100 ms (that's ok) but always paints the same image so it doesn't animate.
    Any ideas?

    The solution:
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean isSelected, boolean cellHasFocus) {
        JLabel tmpLabel = new JLabel();
        if (value instanceof ImageIcon) {
          ImageIcon tmpIcon = (ImageIcon)value;
          tmpIcon.setImageObserver(list);
          tmpLabel.setPreferredSize(new Dimension(tmpIcon.getIconWidth(),tmpIcon.getIconHeight()));
          tmpLabel.setIcon(tmpIcon);
        else
          tmpLabel.setText(value.toString());
        return tmpLabel;
    }The problem was to set "list" as the ImageObserver of the icon
    Bye...
    Olaso

  • Adding pictures into an Array?

    The following is a BlackJack Program my group and I made. So far, it seems to work and would likely net us a 100% when we hand it in. However, we wish to go that extra mile and add pictures, cards in particular, something that should obviously be in any card game! I've been fiddling around with ImageIcon and Image but I don't have a clue how to implement these or how to get them working correctly. Also, it would be best if the pictures could be loaded into an array, which would allow the program to function basically the same way with little editing.
    //Import various Java utilites critical to program function
    import java.awt.* ;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    import java.lang.String;
    public class BlackJackExtreme extends JFrame {  
      Random r = new Random();  //Assigning "r" to randomize
      int valueA;  //Numerical Value of player Cards
      int valueB;
      int valueC;
      int valueD;
      int valueE;
      int valueAC;  //Numerical Value of computer Cards
      int valueBC;
      int valueCC;
      int valueDC;
      int valueEC;
      int playerVal;  //Numerical total value of player cards
      int playerVal2;
      int playerValT;
      int compVal;  //Numerical total value of computer cards
      int compVal2;
      int compValT;
      int counter;  //A counter
      String playVal; //String value for Numerical total value of player cards
      String cVal;   //String value for Numerical total value of computer cards
      private JLabel YourCard;   //Initializing a title label
      private JLabel CCard;  //Initializing a title label
      private JLabel Total;   //Initializing a title label
      private JLabel CTotal;  //Initializing a title label
      private JLabel Win;   //Initializing a Win label
      private JLabel Lose;  //Initializing a Lose label
      private JLabel Bust;  //Initializing a Bust label
      private JButton Deal;   //Initializing a button
      private JButton Hit;   //Initializing a button
      private JButton Stand;   //Initializing a button
      private JButton Exit;   //Initializing a button
      private JTextArea TCompVal;     //Initializing textbox for computer values
      private JTextArea TotalVal;
      private JLabel CardOne;  //Initializing a label for player card 1
      private JLabel CardTwo;  //Initializing a label for player card 2
      private JLabel CardThree;  //Initializing a label for player card 3
      private JLabel CardFour;   //Initializing a label for player card 4
      private JLabel CardFive;   //Initializing a label for player card 5
      private JLabel CCardOne;   //Initializing a label for computer card 1
      private JLabel CCardTwo;   //Initializing a label for computer card 1
      private JLabel CCardThree;   //Initializing a label for computer card 1
      private JLabel CCardFour;   //Initializing a label for computer card 1
      private JLabel CCardFive;   //Initializing a label for computer card 1
      private JPanel contentPane;
      public BlackJackExtreme() {
        super();
        initializeComponent();     
        this.setVisible(true);
      private void initializeComponent() {   
        YourCard = new JLabel("These are your cards");
        CCard = new JLabel("These are the computers cards");
        Total = new JLabel("Your total is: ");
        CTotal = new JLabel("Computer total is: ");
        TCompVal = new JTextArea();  //Box for computer values
        TotalVal = new JTextArea();  //Box for player values
        Win = new JLabel("You win!");  //Label for a Win
        Lose = new JLabel("You lose!");  //Label for a Loss
        Bust = new JLabel("You both Bust!");  //Label for a Bust
        Deal = new JButton();  //Button
        Hit = new JButton();  //Button
        Stand = new JButton();  //Button
        Exit = new JButton();  //Button
        CardOne = new JLabel("");  //Label for Player Card 1
        CardTwo  = new JLabel("");  //Label for Player Card 2
        CardThree = new JLabel("");  //Label for Player Card 3
        CardFour = new JLabel("");  //Label for Player Card 4
        CardFive = new JLabel("");  //Label for Player Card 5
        CCardOne = new JLabel("");   //Label for Computer Card 1
        CCardTwo  = new JLabel("");  //Label for Computer Card 2
        CCardThree = new JLabel("");  //Label for Computer Card 3
        CCardFour = new JLabel("");  //Label for Computer Card 4
        CCardFive = new JLabel("");  //Label for Computer Card 5
        contentPane = (JPanel)this.getContentPane();
        //Assigns function and ability to the various buttons
        Deal.setText("Deal");
        Deal.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Deal_actionPerformed(e);
         Stand.setText("Stand");
        Stand.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Stand_actionPerformed(e);
            Exit.setText("Exit");
        Exit.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Exit_actionPerformed(e);
         Hit.setText("Hit");
        Hit.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Hit_actionPerformed(e);
        //Determines the arrangement of the various buttons, labels, and other GUI objects
        contentPane.setLayout(null);
        addComponent(contentPane, YourCard, 15,1,150,50);
        addComponent(contentPane, CCard, 325,1,200,50);
        addComponent(contentPane, Deal, 15,415,100,35);
        addComponent(contentPane, Hit, 125,415,100,35);
        addComponent(contentPane, Stand, 235 ,415,100,35);
        addComponent(contentPane, Exit, 435 ,415,100,35);
        addComponent(contentPane, CardOne, 25,35,50,50);
        addComponent(contentPane, CardTwo, 110,35,50,50);
        addComponent(contentPane, CardThree, 25,120,50,50);
        addComponent(contentPane, CardFour, 110,120,50,50);
        addComponent(contentPane, CardFive, 65,200,50,50);
        addComponent(contentPane, CCardOne, 350,35,50,50);
        addComponent(contentPane, CCardTwo, 450,35,50,50);
        addComponent(contentPane, CCardThree, 350,120,50,50);
        addComponent(contentPane, CCardFour, 450,120,50,50);
        addComponent(contentPane, CCardFive, 400,200,50,50);
        addComponent(contentPane, Win, 300,300,70,50);
        addComponent(contentPane, Lose, 300,300,70,50);
        addComponent(contentPane, Bust, 300,300,100,50);
        addComponent(contentPane, Total, 100,350,150,50);
        addComponent(contentPane, TotalVal, 200,365,25,25);
        addComponent(contentPane, CTotal, 300,365,150,25);
        addComponent(contentPane, TCompVal, 425,365,25,25);
        //Sets the "outcome" labels invisible on program execution
        Win.setVisible(false);
        Lose.setVisible(false);
        Bust.setVisible(false);
        //Determines size of program window
        this.setTitle("BlackJack");
        this.setLocation(new Point(220,185));
        this.setSize(new Dimension(555,500));
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      private void addComponent(Container container, Component c, int x, int y, int width, int height){
        c.setBounds(x,y,width,height);
        container.add(c);
      //The DEAL button
      public void Deal_actionPerformed(ActionEvent e) {
        //Correctly resets the display after first round of use
        Hit.setVisible(true);
        Stand.setVisible(true);
        Win.setVisible(false);
        Lose.setVisible(false);
        Bust.setVisible(false);
        CardThree.setVisible(false);
        CardFour.setVisible(false);
        CardFive.setVisible(false);
        TotalVal.setText("");
        TCompVal.setText("");
        //Card Array - Values assigned to cards
        String[] cardnames = new String[15];
        cardnames[0] = "Error";
        cardnames[1] = "Error";
        cardnames[2] = "Two";
        cardnames[3] = "Three";
        cardnames[4] = "Four";
        cardnames[5] = "Five";
        cardnames[6] = "Six";
        cardnames[7] = "Seven";
        cardnames[8] = "Eight";
        cardnames[9] = "Nine";
        cardnames[10] = "Ten";
        cardnames[11] = "Jack";
        cardnames[12] = "Queen";
        cardnames[13] = "King";
        cardnames[14] = "Ace";
        //Randomize Card Values
        valueA = r.nextInt(13)+2;
        valueB = r.nextInt(13)+2;
        valueAC = r.nextInt(13)+2;
        valueBC = r.nextInt(13)+2;
        //Displays Card
        CardOne.setText(cardnames[valueA]);
        CardTwo.setText(cardnames[valueB]);
        CCardOne.setText(cardnames[valueAC]);
        CCardTwo.setText(cardnames[valueBC]);
        //Value Correction for Player Cards
        if (valueA == 11 || valueA == 12 || valueA == 13) {
          valueA = 10;  }
        if (valueA ==14){
          valueA = 11;    }
        if (valueB == 11 || valueB == 12 || valueB == 13) {
          valueB = 10;    }
        if (valueB ==14){
          valueB = 11;    }
        //Value Correction for Computer Cards
        if (valueAC == 11 || valueAC == 12 || valueAC == 13) {
          valueAC = 10;  }
        if (valueAC ==14){
          valueAC = 11;    }
        if (valueBC == 11 || valueBC == 12 || valueBC == 13) {
          valueBC = 10;    }
        if (valueBC ==14){
          valueBC = 11;    }
        //Computer Hand Value Calculations
        compVal = valueAC + valueBC;
        //Assigns addition cards to computer
        if (compVal <= 15) {
          valueCC = r.nextInt(13)+2;
          CCardThree.setText(cardnames[valueCC]);
          if (valueCC == 11 || valueCC == 12 || valueCC == 13) {
           valueCC = 10;    }
          if (valueCC ==14){
            valueCC = 11;    }
          compVal += valueCC;    }
        //Changes the Integer value of player and computer hands into a String value
        cVal = Integer.toString(compVal);  
        playerVal = valueA + valueB;
        playVal =  Integer.toString(playerVal);
        TotalVal.setText(playVal);
        Deal.setVisible(false);
        CCardOne.setVisible(false);
      //The HIT button
      public void Hit_actionPerformed(ActionEvent e) {
        //A counter that changes the specific function of the HIT button when it is pressed at different times
        counter++;
          if (counter ==3){
          Hit.setVisible(false);
        //Card Array - Values assigned to cards
        String[] cardnames = new String[15];
        cardnames[0] = "Error";
        cardnames[1] = "Error";
        cardnames[2] = "Two";
        cardnames[3] = "Three";
        cardnames[4] = "Four";
        cardnames[5] = "Five";
        cardnames[6] = "Six";
        cardnames[7] = "Seven";
        cardnames[8] = "Eight";
        cardnames[9] = "Nine";
        cardnames[10] = "Ten";
        cardnames[11] = "Jack";
        cardnames[12] = "Queen";
        cardnames[13] = "King";
        cardnames[14] = "Ace";
        //Randomize Card Values
        valueC = r.nextInt(13)+2;
        valueD= r.nextInt(13)+2;
        valueE = r.nextInt(13)+2;
        //Determines which card is being hit, as well as randomizing a value to that location
        if (counter == 1) {
          CardThree.setText(cardnames[valueC]);
          playerVal2 = 0 + (valueC);      
          CardThree.setVisible(true);    }
        if (counter == 2) {
          CardFour.setText(cardnames[valueD]);  
          playerVal2 += (valueD) ; 
          CardFour.setVisible(true);    }
        if (counter == 3) {
          CardFive.setText(cardnames[valueE]);
          playerVal2 += (valueE);
          CardFive.setVisible(true);    }
        //Value corrections for player cards
        if (valueC == 11 || valueC == 12 || valueC == 13) {
          valueC = 10;    }
        if (valueC ==14){
          valueC = 11;    }
        if (valueD == 11 || valueD == 12 || valueD == 13) {
          valueD = 10;    }
        if (valueD ==14){
          valueD = 11;    }
        if (valueE == 11 || valueE == 12 || valueE == 13) {
          valueE = 10;    }
        if (valueE ==14){
          valueE = 11;
        //Changes the Integer value of player and computer hands into a String value
        playerValT = playerVal + playerVal2;
        playVal =  Integer.toString(playerValT);
        TotalVal.setText(playVal);
        //The STAND button
        private void Stand_actionPerformed(ActionEvent e) {
          //Correctly assigns player value if HIT button is never pressed
          if (counter == 0){
            playerValT = playerVal; }    
          //Reveals the unknown computer card
          CCardOne.setVisible(true);
          //Determines the winner and loser
          if (playerValT <= 21 && compVal < playerValT) {
            Win.setVisible(true); }
          else if (playerValT <= 21 && compVal > 21) {
            Win.setVisible(true); }
          else if (playerValT >21 && compVal > 21) {
            Bust.setVisible(true); }
          else if (compVal <= 21 && playerValT < compVal){
            Lose.setVisible(true);}
          else if (compVal <= 21 && playerValT > 21) {
            Lose.setVisible(true); }
          else if (compVal == playerValT){
            Lose.setVisible(true); }
          //Configures program and display for next use
          Deal.setVisible(true);
          Stand.setVisible(false);
          Hit.setVisible(false);
          counter = 0;
          TCompVal.setText(cVal);
        //The EXIT button
          private void Exit_actionPerformed(ActionEvent e) {
            System.exit ( 0 );
      public static void main(String[]args) {   
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);   
        new BlackJackExtreme();
      Instead of having a JLabel with "Ace", "Eight", etc appear, how would one make pictures appear? How does one do this with an array?
    Edited by: Funkdmonkey on Jan 1, 2008 7:45 PM

    I guess an array or perhaps better a hashmap where the image is the value and the card (a great place for an enum!) is the key would work nicely. Oh, and you can find a great public domain set of card images here:
    http://www.eludication.org/playingcards.html
    Finally, your code appears to be suffering from the God-class anti-pattern. You would do well to refactor that beast.
    Edited by: Encephalopathic on Jan 1, 2008 8:09 PM

  • TreeCellRendere updating icons

    I have a TreeCellRederer which changes the icons of JTREE when openen/closing items (linked to start/stop applications)
    When an item (application) is open and i switch to another item, the icon does not change (correct because app is still running). When i select an item and close the application, the icon is changed correctly (from closed to open and vise versa).
    When an item (app3) is open and i switch to another application (app2) and then close the app2, my cursus jumps to item 0 (top level) and the icon of the app2 is closed. Then i close app3 (without selecting it first). Now it is goes wrong, the icon is not changed. This is because the line is not rendered.
    I can force closing of the item by jumping to the last item in the list and then to the first item in the list "removeFromActiveApplicationList(String application)" method, but this is a bit of overkill.
    The problem is that the item-row is not rendered when application is closed without the item be-ing active. Any idea how to solve this?
    I will include all coding but icon-iconimages.
    MenuApplication:
    package myMenu;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyVetoException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.StringTokenizer;
    import java.util.logging.Handler;
    import java.util.logging.Logger;
    import javax.swing.ImageIcon;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import testje.testApp;
    import testje.testInternalFrame;
    public class MenuTest extends JFrame implements TreeSelectionListener{
        // System Properties
        public static Logger myLogger = Logger.getLogger(MenuTest.class.getName());
        public Handler myHandler = null;
        private static String appName;
        // Variables
        public ArrayList activeApplicationList;
        private Object[] [] data;
        private ArrayList sflData;
        public String selectedApplication;
        // Swing objects and varialbles
        public JDesktopPane myDeskTop;
        private JPanel jContentPane = null;
        private JSplitPane jSplitPane = null;
        private JTree jTree = null;
        private javax.swing.JMenuBar jJMenuBar = null;
        private javax.swing.JMenu fileMenu = null;
        private javax.swing.JMenuItem exitMenuItem = null;
        private boolean packFrame = false;
        private PropertyChangeEvent currentEvent;
        // Applications
        private testApp myPanelTestje;
        private testInternalFrame myFrameTestje;
         * This is the default constructor
        public MenuTest() {
            super();
            initialize();
            setAppName("Test Menu");
         * Launches this application
        public static void main(String[] args) {
             MenuTest myMenu = new MenuTest();
             myMenu.setVisible(true);
         * This method initializes this
         * @return void
        private void initialize() {
            setContentPane(getJContentPane());
            setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
            setJMenuBar(getJJMenuBar());
            setSize(800, 600);
            setTitle("MyMenu");
            setVisible(true);
            //Validate frames that have preset sizes
            //Pack frames that have useful preferred size info, e.g. from their layout
            if (packFrame) {
              this.pack();
            else {
              this.validate();
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = this.getSize();
            if (frameSize.height > screenSize.height) {
              frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
              frameSize.width = screenSize.width;
            setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
         * This method initializes jJMenuBar   
         * @return javax.swing.JMenuBar
        private javax.swing.JMenuBar getJJMenuBar() {
            if (jJMenuBar == null) {
                jJMenuBar = new javax.swing.JMenuBar();
                jJMenuBar.add(getFileMenu());
            return jJMenuBar;
         * This method initializes jMenu   
         * @return javax.swing.JMenu   
        private javax.swing.JMenu getFileMenu() {
            if (fileMenu == null) {
                fileMenu = new javax.swing.JMenu();
                fileMenu.setText("File");
                fileMenu.add(getExitMenuItem());
            return fileMenu;
         * This method initializes jMenuItem   
         * @return javax.swing.JMenuItem   
        private javax.swing.JMenuItem getExitMenuItem() {
            if (exitMenuItem == null) {
                exitMenuItem = new javax.swing.JMenuItem();
                exitMenuItem.setText("Exit");
                exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {   
                        System.exit(0);
            return exitMenuItem;
         * This method initializes jContentPane
         * @return javax.swing.JPanel  
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(getJSplitPane(), java.awt.BorderLayout.CENTER);
            return jContentPane;
         * This method initializes jSplitPane  
         * @return javax.swing.JSplitPane  
        private JSplitPane getJSplitPane() {
            if (jSplitPane == null) {
                jSplitPane = new JSplitPane();
                jSplitPane.setLeftComponent(getJTree());
                myDeskTop = new JDesktopPane();
                jSplitPane.setRightComponent(myDeskTop);
                jSplitPane.setDividerLocation(150);
            return jSplitPane;
        private JTree getJTree() {
            if (jTree == null) {
                // Create Root
                DefaultMutableTreeNode root = new DefaultMutableTreeNode("Conti7");
                setActiveApplicationList(new ArrayList());
                // Create ApplicationsList
                // Get Applicationlist
                getApplicationList();
                // Process MenuArray to create Menu
                String previousFolder = "";
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
                for (int i = 0; i < sflData.size(); i++){
                    myLogger.fine(
                            "Dataline "+i +" =" + data[0] + " | "
    + data[i][1] + " | "
    + data[i][2] + " | "
    + data[i][3] + " | "
    + data[i][4] + " | "
    + data[i][5]);
    if (!(((String)data[i][2]).equals(previousFolder))) {
    if (!(previousFolder.equals(""))){
    root.add(newNode);
    previousFolder = (String)data[i][2];
    newNode = new DefaultMutableTreeNode(previousFolder);
    newNode.add(new DefaultMutableTreeNode(data[i][3]));
    if (!previousFolder.equals("")){
    root.add(newNode);
    // Add Full menu to tree
    jTree = new JTree(root);
    jTree.setCellRenderer(new TreeExRenderer());
    jTree.addTreeSelectionListener(this);
    return jTree;
    public void valueChanged(TreeSelectionEvent event) {
    String selectedApplication = jTree.getLastSelectedPathComponent().toString();
    myLogger.info(
    "Current Item Selection = " + selectedApplication);
    setSelectedApplication(selectedApplication);
    activateApplication(selectedApplication);
    private void activateApplication(String selectedApplication) {
    if (getSelectedApplication().equals("PanelTestje")){
    if (myPanelTestje==null){
    myPanelTestje = new testje.testApp();
    addInternalFrame(myPanelTestje);
    activateInternalFrame(myPanelTestje);
    if (getSelectedApplication().equals("FrameTestje")){
    if (myFrameTestje==null){
    myFrameTestje = new testje.testInternalFrame();
    addInternalFrame(myFrameTestje);
    activateInternalFrame(myFrameTestje);
    public void addInternalFrame(JInternalFrame myFrame) {
    myDeskTop.add(myFrame);
    myFrame.pack();
    myFrame.setClosable(true);
    try {
    myFrame.setMaximum(true);
    } catch (PropertyVetoException e){}
    myFrame.addPropertyChangeListener(new PropertyChangeHandler());
    activeApplicationList.add(getSelectedApplication());
    Collections.sort(activeApplicationList);
    public void activateInternalFrame(JInternalFrame myFrame) {
    myFrame.setVisible(true);
    myFrame.toFront();
    class PropertyChangeHandler implements PropertyChangeListener {
    public void propertyChange(PropertyChangeEvent e) {
    if (((String)e.getPropertyName()).equals("closed")){
    setCurrentEvent(e);
    deActivateApplication(e);
    private void deActivateApplication(PropertyChangeEvent currentEvent){
    if ((getCurrentEvent().getSource() instanceof testje.testApp)){
    myPanelTestje = null;
    removeFromActiveApplicationList("PanelTestje");
    if ((getCurrentEvent().getSource() instanceof testje.testInternalFrame)){
    myFrameTestje = null;
    removeFromActiveApplicationList("FrameTestje");
    * Deze methode wordt gebruikt om de applicatienaam op
    * te vragen.
    * <p>
    * @return appName : appName Objectvalue.
    public static String getAppName() {
    return appName;
    * Deze methode wordt gebruikt om de applicatie af te sluiten
    * nadat eerst connectieObject wordt afgesloten.
    * <p>
    public static void exitApplication() {
    myLogger.info("End application.");
    System.exit(0);
    private static void setAppName(String appName)
    MenuTest.appName = appName;
    public class TreeExRenderer extends DefaultTreeCellRenderer {
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
    row, hasFocus);
    String nodeName = value.toString();
    ImageIcon main_leaf = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_open = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_close = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon leafIcon = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafOpen = createImageIcon("/images/jTreeFolderOpen.gif");
    ImageIcon leafClosed = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafSelected = createImageIcon("/images/jTreeItemSelected.gif");
    ImageIcon leafActivated = createImageIcon("/images/jTreeItemSelected.gif");
    if (row==0){
    setIcon(main_leaf);
    } else {
    if(sel){
    setIcon(leafSelected);
    } else {
    if (!expanded) {
    if (isApplicationInActiveList(nodeName)){
    setIcon(leafActivated);
    } else {
    setIcon(leafClosed);
    }else{
    setIcon(leafOpen);
    return this;
    public ImageIcon createImageIcon(String path) {
    URL imgURL = MenuTest.class.getResource(path);
    URL imgURL1 = MenuTest.class.getResource(path);
    if ((imgURL != null)) {
    return new ImageIcon(imgURL);
    } else if ((imgURL == null)) {
    return new ImageIcon(imgURL1);
    } else {
    System.out.println("Hello ");
    System.err.println("Couldn't find file: " + path);
    return null;
    private ArrayList getActiveApplicationList()
    return activeApplicationList;
    private void setActiveApplicationList(ArrayList activeApplicationList)
    this.activeApplicationList = activeApplicationList;
    private boolean isApplicationInActiveList(String nodeName)
    if (activeApplicationList.indexOf(nodeName)>-1) {
    return true;
    } else {
    return false;
    public void removeFromActiveApplicationList(String application)
    activeApplicationList.remove(activeApplicationList.indexOf(application));
    // jTree.setSelectionRow((jTree.getRowCount())-1);
    jTree.setSelectionRow(0);
    public String getSelectedApplication()
    return selectedApplication;
    private void setSelectedApplication(String selectedApplication)
    this.selectedApplication = selectedApplication;
    public PropertyChangeEvent getCurrentEvent()
    return currentEvent;
    private void setCurrentEvent(PropertyChangeEvent currentEvent)
    this.currentEvent = currentEvent;
    private void getApplicationList() {
    sflData = new ArrayList();
    // Get Applicationlist
    sflData.add("PGO;50;General;App1;pack.myApp1;Application 1");
    sflData.add("PGO;55;Operational;App2;pack.myApp2;Application 2");
    sflData.add("PGO;60;Operational;App3;pack.myApp3;Application 3");
    sflData.add("PGO;65;Expeditie;PanelTestje;testje.Paneltestje;Expeditie Paneltestje");
    sflData.add("PGO;70;Desktop;App4;pack.myApp4;Application 4");
    sflData.add("PGO;75;Manifest;FrameTestje;testje.FrameTestje;Maritiem FrameTestje");
    sflData.add("PGO;80;Desktop;App5;pack.myApp5;Application 5");
    // Convert applicationlist to MenuArray
    data = new Object[sflData.size()][6];
    for (int i = 0; i < sflData.size(); i++){
    int count = 0;
    String str;
    str = (String)sflData.get(i);
    StringTokenizer token = new StringTokenizer(str,";");
    while (token.hasMoreTokens()){
    data [i] [count] = token.nextToken();
    count++;
    *testapp1*package testje;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testApp
    extends JInternalFrame {
         testPanel p;
    Container c;
    boolean packFrame = false;
         public testApp() {
              super("Swing-Toepassing PanelTestje");
              c = getContentPane();
    c.setLayout(new BorderLayout());
              p = new testPanel();
              c.add(p);
    //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
    this.pack();
    else {
    this.validate();
    // addWindowListener(new WindowAdapter() {
    // public void windowClosed(WindowEvent e) {
    // System.exit(0);
         public static void main(String[] args) {
              // final JFrame f = new testApp();
    // new testApp();
    *testInternalFrame*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testInternalFrame extends JInternalFrame {
         public void testInternalFrame(){
              setBackground(Color.white);
              Container contentPane = getContentPane();
              setLocation(20,20);
              setTitle("Internal Frame");
              setClosable(true);
              setResizable(true);
              setMaximizable(true);
              setIconifiable(true);
              setVisible(true);
              contentPane.setLayout(new FlowLayout());
              contentPane.add(new JTextArea(5,15), "Center");
              pack();
    *testPanel*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testPanel extends JPanel {
         public void testPanel(){
              setBackground(Color.blue);
         public void paintComponent (Graphics g){
              super.paintComponent(g);
              g.drawString("Groeten van Patrick", 0, 60);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    When you say "the JLabel changes" I'm guessing you mean that the JLabel variable named "imageLabel" was the thing that changed? That won't change the GUI's reference to the original JLabel object.
    Which is what you have to change. You have a reference to that object in the form of the "imageLabel" variable; to change the object you call one of its methods, like maybe setIcon() or something... whatever your ImageManager class is doing to create the label in the first place.

  • Change colors in the png - keep transparency

    I load a png-file as ImageIcon into a JLabel as setIcon(). A color of the png (generally color white) is defined for transparency, that in the JLabel is represented correctly as transparency.
    I want to convert now another dark color in ImageIcon like new Color (0,0,0) into a bright-grey-color like new Color (244,244,244), after the transformation transparency effect should kept by color white.
    How can that be done, please?

    BufferedImage is the easiest interface to the pixels yes. You can always load your images as BufferedImage instances and pass those to your ImageIcon objects; if you ever want the image back you simply cast the return value of ImageIcon.getImage() to BufferedImage.

  • Flashing undecorated JDialog on resize+setLocation

    Hi everyone
    I have a undecorated JDialog with custome resize code. Here is a part of my code
              frame.setUndecorated(true);
              frame.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                             sp = e.getPoint();
                             compStartHeight = frame.getSize().height;
                             compStartWidth = frame.getSize().width;
                             frameLoc = frame.getLocation();
                        public void mouseEntered(MouseEvent e)
                        public void mouseExited(MouseEvent e)
                             if (sp == null)
                                  frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        public void mouseClicked(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             sp = null;
              frame.addMouseMotionListener(new MouseMotionListener()
                        public void mouseMoved(MouseEvent e)
                             Point p = e.getPoint();
                             if (p.y > e.getComponent().getSize().height - 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
                             else if (p.y < 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
                             else
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                        public void mouseDragged(MouseEvent e)
                             Point p = e.getPoint();
                             int compWidth = frame.getSize().width;
                             int compHeight = frame.getSize().height;
                             if (frame.getCursor().getType() == Cursor.S_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+p.y-sp.y;
                                  if (nextHeight > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                             else if (frame.getCursor().getType() == Cursor.N_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+sp.y-p.y;
                                  if (nextHeight > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.E_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.W_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(p.x-sp.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else
                                  int x = frame.getX()+p.x-sp.x;     
                                  int y = frame.getY()+p.y-sp.y;     
                                  setLocation(x,y);
                   });Here is the code that can be compile if you want to try ou
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.event.*;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.net.URL;
    public class TrdHistForm
        private static final int MAX_LINE = Share.MAX_HIST_LINE;
        private static final int ROW_HEIGHT = 20;
        private JDialog frame = new JDialog();
         private JPanel mainPane = new JPanel(new BorderLayout());
         private JPanel titleBar = new JPanel();
         private JLabel title = new JLabel("", JLabel.LEFT);
        private JTable table;
        private TableView view;
        private Vector t;
         private boolean minimized = false; // starts up as normal size window, not minimized
         private Point loc = new Point(0,0);
         private Dimension size = new Dimension(0,0);
         private Point sp;
         private Point frameLoc = new Point(0,0);
         //private Dimension frameSize = new Dimension(0,0);
         private int     compStartHeight;
         private int compStartWidth;
        private static SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy h:mm:ss a");
        private static SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        private static DateFormat format = new SimpleDateFormat("HH:mm:ss");
        private static int PRICE_C = 0;
        private static int VOL_C = 1;
        private static int TIME_C = 2;
        private static int PRICE_W = 70;
        private static int VOL_W = 55;
        private static int TIME_W = 60;
        private static int[] colWidth =
            PRICE_W, VOL_W, TIME_W
        private static String[] colOrgName =
            "price","vol","time"
        private String PRICE_N = "Price";
        private String VOL_N = "Volume";
        private String TIME_N = "Time";
        private String[] colName =
            PRICE_N, VOL_N, TIME_N
         private Color rowColor = new Color(0x00, 0x80, 0x00); //VERY DARK GREEN
        public TrdHistForm()
              minimized = false;
              loc = new Point(0,0);
              size = new Dimension(0,0);
              Dimension butDim = new Dimension(15,15);
              //mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
              //mainPane.setLayout(new BorderLayout());
              //mainPane.setOpaque(false);
              //JPanel upPane = new JPanel();
              setupTitleBar();
              URL url = TrdHistForm.class.getResource("tvbg.JPG");
            ImageIcon icon = new ImageIcon(url);
              mainPane.add(Share.wrapInBackgroundImage(titleBar, icon), BorderLayout.NORTH);
              JPanel butPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              JButton but = new JButton("_");
              but.setActionCommand("Minimized");
              but.setToolTipText("Minimized this window");
              but.setMargin(new Insets(0,0,0,0));
              but.setMaximumSize(butDim);
            but.setMinimumSize(butDim);
            but.setPreferredSize(butDim);
              but.addActionListener(this);
              but.setFocusPainted(false);
              butPane.add(but);
              but = new JButton("\u25FB");
              but.setActionCommand("Restore");
              but.setToolTipText("Restore this window to previous location and size");
              but.setMaximumSize(butDim);
            but.setMinimumSize(butDim);
            but.setPreferredSize(butDim);
              but.setMargin(new Insets(0,0,0,0));
              but.addActionListener(this);
              but.setFocusPainted(false);
              butPane.add(but);
              mainPane.add(butPane);
              mainPane.add(Box.createRigidArea(new Dimension(0,1)));
            t = new Vector();
            view = new TableView();
            int colNum = colName.length;
            table = new JTable(view.model);
            // Call custom rendering
            TableColumn column = null;
            for(int i = 0; i < colNum; i++)
                column = table.getColumnModel().getColumn(i);
                column.setCellRenderer(new CustomRenderer());
            // Set up columns' widths
            for (int i = 0; i < colNum; i++)
                column = table.getColumnModel().getColumn(i);
                column.setPreferredWidth(colWidth);
    int i = 0;
    for (int j = 0; j < colWidth.length; j++)
    i = i + colWidth[j];
              //table.setShowGrid(false);
    //table.setOpaque(false);
              //table.setPreferredScrollableViewportSize(new Dimension(i, 500));
              table.setRowHeight(ROW_HEIGHT);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //table.setGridColor(new Color(239, 239, 239));
    JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              //scrollPane.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
              //scrollPane.setOpaque(false);
              //scrollPane.getViewport().setOpaque(false);
              //scrollPane.getVerticalScrollBar().setOpaque(false);
              //scrollPane.getHorizontalScrollBar().setOpaque(false);
              mainPane.add(scrollPane, BorderLayout.CENTER);
              mainPane.setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x66, 0xCC), 3));
              //URL url = AtBestForm.class.getResource("tvbg.JPG");
    //ImageIcon icon = new ImageIcon(url);
              //frame.setContentPane(Share.wrapInBackgroundImage(mainPane, icon));
              frame.setContentPane(mainPane);
    frame.setVisible(false);
    //frame.pack();
              frame.setSize(new Dimension(i, 500));
              //frame.setDoubleBuffered(true);
    //frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    frame.setLocation(0,0);
              frame.setUndecorated(true);
              frame.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                             sp = e.getPoint();
                             compStartHeight = frame.getSize().height;
                             compStartWidth = frame.getSize().width;
                             frameLoc = frame.getLocation();
                        public void mouseEntered(MouseEvent e)
                        public void mouseExited(MouseEvent e)
                             if (sp == null)
                                  frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        public void mouseClicked(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             sp = null;
              frame.addMouseMotionListener(new MouseMotionListener()
                        public void mouseMoved(MouseEvent e)
                             Point p = e.getPoint();
                             if (p.y > e.getComponent().getSize().height - 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
                             else if (p.y < 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
                             else
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                        public void mouseDragged(MouseEvent e)
                             Point p = e.getPoint();
                             int compWidth = frame.getSize().width;
                             int compHeight = frame.getSize().height;
                             if (frame.getCursor().getType() == Cursor.S_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+p.y-sp.y;
                                  if (nextHeight > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                             else if (frame.getCursor().getType() == Cursor.N_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+sp.y-p.y;
                                  if (nextHeight > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.E_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.W_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(p.x-sp.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > Share.MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else
                                  int x = frame.getX()+p.x-sp.x;     
                                  int y = frame.getY()+p.y-sp.y;     
                                  setLocation(x,y);
         private void setupTitleBar()
              titleBar.setLayout(new BorderLayout());
              //titleBar.setToolTipText("Double click here to minimize the window");
              titleBar.setOpaque(false);
              titleBar.setBackground(Color.BLUE);
              titleBar.setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x66, 0xCC), 2));
              title.setForeground(Color.WHITE);
              title.setOpaque(false);
              titleBar.add(title, BorderLayout.WEST);
              FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
              flow.setVgap(0);
              flow.setHgap(0);
              JPanel conPane = new JPanel(flow);
              conPane.setOpaque(false);
              // Setup minimize label
              JLabel lab = new JLabel(" _ ");
              lab.setForeground(Color.WHITE);
              lab.setOpaque(false);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             if (minimized == false)
                                  size = frame.getSize();
                                  //titleBar.setToolTipText("Double click here to restore the window");
                                  frame.setSize(((int)size.getWidth()), Share.MINIMIZED_HEIGHT);
                                  minimized = true;
              conPane.add(lab);
              // Setup restore label
              lab = new JLabel(" " + "\u25FB" + " ", JLabel.RIGHT);
              lab.setOpaque(false);
              lab.setForeground(Color.WHITE);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             if (minimized == true)
                                  frame.setSize(size);
                                  //titleBar.setToolTipText("Double click here to minimize the window");
                                  minimized = false;
              conPane.add(lab);
              // Setup close label
              lab = new JLabel(" x ", JLabel.RIGHT);
              lab.setForeground(Color.WHITE);
              lab.setOpaque(false);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             //frame.setVisible(false);
                             System.exit(0);
              conPane.add(lab);
              titleBar.add(conPane, BorderLayout.EAST);          
              titleBar.addMouseMotionListener(new MouseMotionListener()
                        public void mouseDragged(MouseEvent e)
                             //int x = ((int)frame.getLocation().getX());
                             //int y = ((int)frame.getLocation().getY());
                             //frame.setLocation(e.getX() + (x-e.getX()), e.getY() + (y-e.getY()));
                             Point p = frame.getLocationOnScreen();
                             frame.setLocation(p.x + e.getX() - loc.x,p.y + e.getY() - loc.y);
                        public void mouseMoved(MouseEvent e)
              titleBar.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                             loc.x = e.getPoint().x;
                             loc.y = e.getPoint().y;
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
    public void setFrameTitle(String s)
    title.setText(" " + s);
    public void setVisible(boolean b)
    frame.setVisible(b);
    private class TableView
    MyTableModel model;
    private TableView()
    try
    model = new MyTableModel();
    catch (Exception exc)
    Share.d("TableView E: " + exc.toString());
    class MyTableModel extends AbstractTableModel
    public int getColumnCount()
    return colName.length;
    public int getRowCount()
    if (t == null)
    return 0;
    else
    return t.size();
    public String getColumnName(int col)
    return colName[col];
    public Object getValueAt(int row, int col)
    String[] data = t.get(row).toString().split(",");
    return data[col];
    public boolean isCellEditable(int row, int col)
    return false;
    public void setValueAt(Object value, int row, int col)
    String[] data = t.get(row).toString().split(",");
    data[col] = value.toString();
    String s = "";
    for (int i = 0; i < data.length; i++)
    s = s + data;
    if (i != data.length - 1)
    s = s + ",";
    t.set(row, s);
    fireTableCellUpdated(row, col);
    public void setData(Vector newData)
    t = newData;
    fireTableDataChanged();
    private class CustomRenderer extends JLabel implements TableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
    try
    // 08/06/2007 18:54:44,62000,4,,
    setOpaque(true);
                        setForeground(Color.WHITE);
    if (vColIndex == PRICE_C)
    setText(" " + value.toString());
    setHorizontalAlignment(JLabel.LEFT);
    if (rowIndex == 0)
    //setForeground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                  //setForeground(Color.green);
                                  setBackground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                  rowColor = new Color(0x00, 0x80, 0x00);
    else
    Double d = getPrice(rowIndex - 1) - getPrice(rowIndex);
    if (d < 0.0)
    //setForeground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                       //setForeground(Color.green);
                                       setBackground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                       rowColor = new Color(0x00, 0x80, 0x00);
    else if (d > 0.0)
    //setForeground(new Color(0xcc, 0xcc, 0x00));
                                       setBackground(Share.sellCol); //VERY DARK GREEN
                                       rowColor = Share.sellCol;
    else if (d == 0.0)
                                       setForeground(Color.BLACK);
                                       setBackground(null);
                                       rowColor = Color.WHITE;
    //setForeground(Color.WHITE);
    else if (vColIndex == TIME_C)
    Date d;
    if (value.toString().split(" ").length == 3)
    d = sdf.parse(value.toString());
    else
    d = sdf1.parse(value.toString());
    setText(format.format(d));
    setHorizontalAlignment(JLabel.RIGHT);
                             setBackground(rowColor);
                             if (rowColor == Color.WHITE)
                                  setForeground(Color.BLACK);     
                             else
                                  setForeground(Color.WHITE);
    else if (vColIndex == VOL_C)
    setText(value.toString() + " ");
    setHorizontalAlignment(JLabel.RIGHT);
                             setBackground(rowColor);
                             if (rowColor == Color.WHITE)
                                  setForeground(Color.BLACK);     
                             else
                                  setForeground(Color.WHITE);
    else
    // For future buyer and seller info
    catch (Exception exc)
    Share.d("CustomRenderer E: " + exc.toString());
    return this;
    public void addRow(String s)
    if (t.size() == MAX_LINE)
    t.remove(MAX_LINE - 1);
    t.add(0, s);
    view.model.setData(t);
    public double getPrice(int i)
    return(Double.parseDouble((t.get(i).toString().split(","))[0]));
    public Point getLocation()
    return frame.getLocation();
    public void setLocation(int x, int y)
    frame.setLocation(x, y);
    public void setOnTop(boolean b)
    frame.setAlwaysOnTop(b);
         public void removeAll()
              t.clear();
    view.model.setData(t);
    public void actionPerformed(ActionEvent e)
    String item = e.getActionCommand();
    if (item.equals("Minimized"))
                   if (minimized == false)
                        loc = frame.getLocation();
                        size = frame.getSize();
                        if (Share.MINIMIZED_WIDTH + size.getWidth() > Share.SCREEN_WIDTH)
                             Share.MINIMIZED_ROW++;
                             Share.MINIMIZED_WIDTH = 0;
                             //frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS);
                             frame.setSize(((int)size.getWidth()), Share.MINIMIZED_HEIGHT);
                             frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS-(Share.MINIMIZED_ROW*Share.MINIMIZED_HEIGHT));
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH + ((int)size.getWidth());
                        else
                             //frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS);
                             frame.setSize(((int)size.getWidth()), Share.MINIMIZED_HEIGHT);
                             frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS-(Share.MINIMIZED_ROW*Share.MINIMIZED_HEIGHT));
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH + ((int)size.getWidth());
                        Share.MINIMIZED_NUM++;
                        minimized = true;
    else if (item.equals("Restore"))
                   if (minimized == true)
                        frame.setLocation(loc);
                        frame.setSize(size);
                        frame.setVisible(true);
                        if (Share.MINIMIZED_WIDTH - size.getWidth() < 0)
                             Share.MINIMIZED_WIDTH = Share.SCREEN_WIDTH;
                             Share.MINIMIZED_ROW--;
                        else
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH - ((int)size.getWidth());
                        Share.MINIMIZED_NUM--;
                        minimized = false;
         public static void main(String[] args)
    System.getProperties().put("sun.awt.noerasebackground", "true");
              TrdHistForm form = new TrdHistForm();
              form.setFrameTitle("TEST");
              form.addRow("2,69000,2007/07/07 05:05:05");
              form.setVisible(true);
    The problem is that when a resize that needs a setLocation() to go with it, the frame flash/flicker a lot. I already tried to set "sun.awt.noerasebackground" to "true" but it didn't help me. Is there another way to solve the flickering problem?
    I notice on normal frames, there is an outline drawn as the mouse moves around, then the windows resize/setLocation at mouse release events. How can I do this (if the flash/flicker problem can't be solved)?
    Thank you very much for your time!!
    Cheers!

    Thanks for the reply! But I don't have a problem with moving the undecorated JDialog. It's the resize operations that I try to do. If the resize operations need to resize and setLocation (i.e NW, SW, NE, W, N resize) then my JDialog will flash... I doubt that you need to read it... If you are familiar with this kind of things then once you compile and run it, you will probably know the fix right away...
    Here is the compilable code
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.event.*;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.net.URL;
    public class MoveWindow
        private static final int MAX_LINE = 100;
        private static final int ROW_HEIGHT = 20;
        private JDialog frame = new JDialog();
         private JPanel mainPane = new JPanel(new BorderLayout());
         private JPanel titleBar = new JPanel();
         private JLabel title = new JLabel("AA", JLabel.LEFT);
        private JTable table;
        private TableView view;
        private Vector t;
         private boolean minimized = false; // starts up as normal size window, not minimized
         private Point loc = new Point(0,0);
         private Dimension size = new Dimension(0,0);
         private Point sp;
         private Point frameLoc = new Point(0,0);
         //private Dimension frameSize = new Dimension(0,0);
         private int     compStartHeight;
         private int compStartWidth;
        private static SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy h:mm:ss a");
        private static SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        private static DateFormat format = new SimpleDateFormat("HH:mm:ss");
        private static int PRICE_C = 0;
        private static int VOL_C = 1;
        private static int TIME_C = 2;
        private static int PRICE_W = 70;
        private static int VOL_W = 55;
        private static int TIME_W = 60;
        private static int[] colWidth =
            PRICE_W, VOL_W, TIME_W
        private static String[] colOrgName =
            "price","vol","time"
        private String PRICE_N = "Price";
        private String VOL_N = "Volume";
        private String TIME_N = "Time";
        private String[] colName =
            PRICE_N, VOL_N, TIME_N
         private Color rowColor = new Color(0x00, 0x80, 0x00); //VERY DARK GREEN
         private static final int MINIMIZED_HEIGHT = 50;
        public MoveWindow()
              minimized = false;
              loc = new Point(0,0);
              size = new Dimension(0,0);
              Dimension butDim = new Dimension(15,15);
              //mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
              //mainPane.setLayout(new BorderLayout());
              //mainPane.setOpaque(false);
              //JPanel upPane = new JPanel();
              setupTitleBar();
              //URL url = TrdHistForm.class.getResource("tvbg.JPG");
            //ImageIcon icon = new ImageIcon(url);
              //mainPane.add(Share.wrapInBackgroundImage(titleBar, icon), BorderLayout.NORTH);
              mainPane.add(titleBar,BorderLayout.NORTH);
              JPanel butPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              JButton but = new JButton("_");
              but.setActionCommand("Minimized");
              but.setToolTipText("Minimized this window");
              but.setMargin(new Insets(0,0,0,0));
              but.setMaximumSize(butDim);
            but.setMinimumSize(butDim);
            but.setPreferredSize(butDim);
              but.addActionListener(this);
              but.setFocusPainted(false);
              butPane.add(but);
              but = new JButton("\u25FB");
              but.setActionCommand("Restore");
              but.setToolTipText("Restore this window to previous location and size");
              but.setMaximumSize(butDim);
            but.setMinimumSize(butDim);
            but.setPreferredSize(butDim);
              but.setMargin(new Insets(0,0,0,0));
              but.addActionListener(this);
              but.setFocusPainted(false);
              butPane.add(but);
              mainPane.add(butPane);
              mainPane.add(Box.createRigidArea(new Dimension(0,1)));
            t = new Vector();
            view = new TableView();
            int colNum = colName.length;
            table = new JTable(view.model);
            // Call custom rendering
            TableColumn column = null;
            for(int i = 0; i < colNum; i++)
                column = table.getColumnModel().getColumn(i);
                column.setCellRenderer(new CustomRenderer());
            // Set up columns' widths
            for (int i = 0; i < colNum; i++)
                column = table.getColumnModel().getColumn(i);
                column.setPreferredWidth(colWidth);
    int i = 0;
    for (int j = 0; j < colWidth.length; j++)
    i = i + colWidth[j];
              //table.setShowGrid(false);
    //table.setOpaque(false);
              //table.setPreferredScrollableViewportSize(new Dimension(i, 500));
              table.setRowHeight(ROW_HEIGHT);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //table.setGridColor(new Color(239, 239, 239));
    JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              //scrollPane.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
              //scrollPane.setOpaque(false);
              //scrollPane.getViewport().setOpaque(false);
              //scrollPane.getVerticalScrollBar().setOpaque(false);
              //scrollPane.getHorizontalScrollBar().setOpaque(false);
              mainPane.add(scrollPane, BorderLayout.CENTER);
              mainPane.setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x66, 0xCC), 3));
              //URL url = AtBestForm.class.getResource("tvbg.JPG");
    //ImageIcon icon = new ImageIcon(url);
              //frame.setContentPane(Share.wrapInBackgroundImage(mainPane, icon));
              frame.setContentPane(mainPane);
    frame.setVisible(false);
    //frame.pack();
              frame.setSize(new Dimension(i, 500));
              //frame.setDoubleBuffered(true);
    //frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    frame.setLocation(0,0);
              frame.setUndecorated(true);
              frame.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                             sp = e.getPoint();
                             compStartHeight = frame.getSize().height;
                             compStartWidth = frame.getSize().width;
                             frameLoc = frame.getLocation();
                        public void mouseEntered(MouseEvent e)
                        public void mouseExited(MouseEvent e)
                             if (sp == null)
                                  frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        public void mouseClicked(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             sp = null;
              frame.addMouseMotionListener(new MouseMotionListener()
                        public void mouseMoved(MouseEvent e)
                             Point p = e.getPoint();
                             if (p.y > e.getComponent().getSize().height - 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
                             else if (p.y < 5)
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
                                  else
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
                             else
                                  if (p.x < 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
                                  else if (p.x > e.getComponent().getSize().width - 5)
                                       frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                        public void mouseDragged(MouseEvent e)
                             Point p = e.getPoint();
                             int compWidth = frame.getSize().width;
                             int compHeight = frame.getSize().height;
                             if (frame.getCursor().getType() == Cursor.S_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+p.y-sp.y;
                                  if (nextHeight > MINIMIZED_HEIGHT)
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                             else if (frame.getCursor().getType() == Cursor.N_RESIZE_CURSOR)
                                  int nextHeight = compStartHeight+sp.y-p.y;
                                  if (nextHeight > MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));
                                       frame.setSize(compWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.E_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.W_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);
                                       frame.setSize(nextWidth,compHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(p.x-sp.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.SW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(p.y-sp.y);
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y);                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NW_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+(sp.x-p.x);
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x-(sp.x-p.x), frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else if (frame.getCursor().getType() == Cursor.NE_RESIZE_CURSOR)
                                  int nextWidth = compStartWidth+p.x-sp.x;
                                  int nextHeight = compStartHeight+(sp.y-p.y);
                                  if (nextWidth > MINIMIZED_HEIGHT)
                                       frame.setLocation(frameLoc.x, frameLoc.y-(sp.y-p.y));                              
                                       frame.setSize(nextWidth,nextHeight);
                                       frame.validate();
                                       //frame.repaint();
                             else
                                  int x = frame.getX()+p.x-sp.x;     
                                  int y = frame.getY()+p.y-sp.y;     
                                  setLocation(x,y);
         private void setupTitleBar()
              titleBar.setLayout(new BorderLayout());
              //titleBar.setToolTipText("Double click here to minimize the window");
              titleBar.setOpaque(true);
              titleBar.setBackground(Color.BLUE);
              titleBar.setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x66, 0xCC), 2));
              title.setForeground(Color.WHITE);
              title.setOpaque(false);
              titleBar.add(title, BorderLayout.WEST);
              FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
              flow.setVgap(0);
              flow.setHgap(0);
              JPanel conPane = new JPanel(flow);
              conPane.setOpaque(false);
              // Setup minimize label
              JLabel lab = new JLabel(" _ ");
              lab.setForeground(Color.WHITE);
              lab.setOpaque(false);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             if (minimized == false)
                                  size = frame.getSize();
                                  //titleBar.setToolTipText("Double click here to restore the window");
                                  frame.setSize(((int)size.getWidth()), MINIMIZED_HEIGHT);
                                  minimized = true;
              conPane.add(lab);
              // Setup restore label
              lab = new JLabel(" " + "\u25FB" + " ", JLabel.RIGHT);
              lab.setOpaque(false);
              lab.setForeground(Color.WHITE);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             if (minimized == true)
                                  frame.setSize(size);
                                  //titleBar.setToolTipText("Double click here to minimize the window");
                                  minimized = false;
              conPane.add(lab);
              // Setup close label
              lab = new JLabel(" x ", JLabel.RIGHT);
              lab.setForeground(Color.WHITE);
              lab.setOpaque(false);
              lab.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
                             //frame.setVisible(false);
                             System.exit(0);
              conPane.add(lab);
              titleBar.add(conPane, BorderLayout.EAST);          
              titleBar.addMouseMotionListener(new MouseMotionListener()
                        public void mouseDragged(MouseEvent e)
                             //int x = ((int)frame.getLocation().getX());
                             //int y = ((int)frame.getLocation().getY());
                             //frame.setLocation(e.getX() + (x-e.getX()), e.getY() + (y-e.getY()));
                             Point p = frame.getLocationOnScreen();
                             frame.setLocation(p.x + e.getX() - loc.x,p.y + e.getY() - loc.y);
                        public void mouseMoved(MouseEvent e)
              titleBar.addMouseListener(new MouseListener()
                        public void mousePressed(MouseEvent e)
                             loc.x = e.getPoint().x;
                             loc.y = e.getPoint().y;
                        public void mouseReleased(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseEntered(MouseEvent e)
                             //frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        public void mouseExited(MouseEvent e)
                             //frame.setCursor(Cursor.getDefaultCursor());
                        public void mouseClicked(MouseEvent e)
    public void setFrameTitle(String s)
    title.setText(" " + s);
    public void setVisible(boolean b)
    frame.setVisible(b);
    private class TableView
    MyTableModel model;
    private TableView()
    try
    model = new MyTableModel();
    catch (Exception exc)
    //Share.d("TableView E: " + exc.toString());
    class MyTableModel extends AbstractTableModel
    public int getColumnCount()
    return colName.length;
    public int getRowCount()
    if (t == null)
    return 0;
    else
    return t.size();
    public String getColumnName(int col)
    return colName[col];
    public Object getValueAt(int row, int col)
    String[] data = t.get(row).toString().split(",");
    return data[col];
    public boolean isCellEditable(int row, int col)
    return false;
    public void setValueAt(Object value, int row, int col)
    String[] data = t.get(row).toString().split(",");
    data[col] = value.toString();
    String s = "";
    for (int i = 0; i < data.length; i++)
    s = s + data;
    if (i != data.length - 1)
    s = s + ",";
    t.set(row, s);
    fireTableCellUpdated(row, col);
    public void setData(Vector newData)
    t = newData;
    fireTableDataChanged();
    private class CustomRenderer extends JLabel implements TableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
    try
    // 08/06/2007 18:54:44,62000,4,,
    setOpaque(true);
                        setForeground(Color.WHITE);
    if (vColIndex == PRICE_C)
    setText(" " + value.toString());
    setHorizontalAlignment(JLabel.LEFT);
    if (rowIndex == 0)
    //setForeground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                  //setForeground(Color.green);
                                  setBackground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                  rowColor = new Color(0x00, 0x80, 0x00);
    else
    Double d = getPrice(rowIndex - 1) - getPrice(rowIndex);
    if (d < 0.0)
    //setForeground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                       //setForeground(Color.green);
                                       setBackground(new Color(0x00, 0x80, 0x00)); //VERY DARK GREEN
                                       rowColor = new Color(0x00, 0x80, 0x00);
    else if (d > 0.0)
    //setForeground(new Color(0xcc, 0xcc, 0x00));
                                       setBackground(Color.red); //VERY DARK GREEN
                                       rowColor = Color.red;
    else if (d == 0.0)
                                       setForeground(Color.BLACK);
                                       setBackground(null);
                                       rowColor = Color.WHITE;
    //setForeground(Color.WHITE);
    else if (vColIndex == TIME_C)
    Date d;
    if (value.toString().split(" ").length == 3)
    d = sdf.parse(value.toString());
    else
    d = sdf1.parse(value.toString());
    setText(format.format(d));
    setHorizontalAlignment(JLabel.RIGHT);
                             setBackground(rowColor);
                             if (rowColor == Color.WHITE)
                                  setForeground(Color.BLACK);     
                             else
                                  setForeground(Color.WHITE);
    else if (vColIndex == VOL_C)
    setText(value.toString() + " ");
    setHorizontalAlignment(JLabel.RIGHT);
                             setBackground(rowColor);
                             if (rowColor == Color.WHITE)
                                  setForeground(Color.BLACK);     
                             else
                                  setForeground(Color.WHITE);
    else
    // For future buyer and seller info
    catch (Exception exc)
    //Share.d("CustomRenderer E: " + exc.toString());
    return this;
    public void addRow(String s)
    if (t.size() == MAX_LINE)
    t.remove(MAX_LINE - 1);
    t.add(0, s);
    view.model.setData(t);
    public double getPrice(int i)
    return(Double.parseDouble((t.get(i).toString().split(","))[0]));
    public Point getLocation()
    return frame.getLocation();
    public void setLocation(int x, int y)
    frame.setLocation(x, y);
    public void setOnTop(boolean b)
    frame.setAlwaysOnTop(b);
         public void removeAll()
              t.clear();
    view.model.setData(t);
    public void actionPerformed(ActionEvent e)
    String item = e.getActionCommand();
    if (item.equals("Minimized"))
                   if (minimized == false)
                        loc = frame.getLocation();
                        size = frame.getSize();
                        if (Share.MINIMIZED_WIDTH + size.getWidth() > Share.SCREEN_WIDTH)
                             Share.MINIMIZED_ROW++;
                             Share.MINIMIZED_WIDTH = 0;
                             //frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS);
                             frame.setSize(((int)size.getWidth()), Share.MINIMIZED_HEIGHT);
                             frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS-(Share.MINIMIZED_ROW*Share.MINIMIZED_HEIGHT));
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH + ((int)size.getWidth());
                        else
                             //frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS);
                             frame.setSize(((int)size.getWidth()), Share.MINIMIZED_HEIGHT);
                             frame.setLocation(Share.MINIMIZED_WIDTH, Share.MINIMIZED_START_POS-(Share.MINIMIZED_ROW*Share.MINIMIZED_HEIGHT));
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH + ((int)size.getWidth());
                        Share.MINIMIZED_NUM++;
                        minimized = true;
    else if (item.equals("Restore"))
                   if (minimized == true)
                        frame.setLocation(loc);
                        frame.setSize(size);
                        frame.setVisible(true);
                        if (Share.MINIMIZED_WIDTH - size.getWidth() < 0)
                             Share.MINIMIZED_WIDTH = Share.SCREEN_WIDTH;
                             Share.MINIMIZED_ROW--;
                        else
                             Share.MINIMIZED_WIDTH = Share.MINIMIZED_WIDTH - ((int)size.getWidth());
                        Share.MINIMIZED_NUM--;
                        minimized = false;
         public static void main(String[] args)
              System.getProperties().put("sun.awt.noerasebackground", "true");
              MoveWindow form = new MoveWindow();
              form.setFrameTitle("TEST");
              form.addRow("2,69000,2007/07/07 05:05:05");
              form.setVisible(true);
    Thanks again for your time and help!

  • Embedding fonts into applets

    hi im making a applet game and it has a custom font
    how can i embed the font so the user does not have to install it manually
    i read on page u can do this by adding it to the jar and pointing to it some how but they dint explain how
    is this possible or is there another way ? point to the font if i upload it or soming
    thx :)

    been playin with this for past few hours not getting any were just dont no java well enough to really understand whats going on
    all going over my head
    font is at http://www.auba18.dsl.pipex.com/fruitsim/AthleticTown.ttf
    my applet class files r at
    http://www.auba18.dsl.pipex.com/fruitsim/
    so same place as my font
    i just need the applet to some how load this font and display it were the other ones are grabbing "LCD"
    iv got a few pieces of code no idea which one to use or how to get them to compile properlty
    would some one be able to add the code in for me would really appreciate it thanks :)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    import java.io.*;
    import java.io.InputStream;
    import java.net.URL;
    public class drawTopbox {
         private Applet parrentapp;
         JLabel imageLabel;
         ImageIcon ImageIcon;
         JLabel bronze = new JLabel("000.00");
         JLabel silver = new JLabel("000.00");
         JLabel gold = new JLabel("000.00");
         //InputStream in = getClass().getResourceAsStream("AthleticTown.ttf");
         //public static Font createFont(int in);
         //Font     font = Font.createFont(Font.TRUETYPE_FONT, in);
         //InputStream fis = new FileInputStream("font.ttf");
         //Font f = Font.createFont(Font.TRUETYPE_FONT, fis);
         public drawTopbox(Applet parrent, int maxSlots) {
              parrentapp = parrent;          
         try {
         URL url = new URL("AthleticTown.ttf");
         InputStream is = url.openStream();
         Font font = Font.createFont(Font.TRUETYPE_FONT, is);
          } catch (Exception e) {
          e.printStackTrace();
              // bronze
              bronze.setBounds(((187*maxSlots)/2)-99, 14 ,100, 50); 
              bronze.setFont(new Font(font, Font.PLAIN, 25));
              bronze.setForeground(Color.red);
              parrentapp.add(bronze);
              // silver
              silver.setBounds(((187*maxSlots)/2)-54, 45 ,100, 50); 
              silver.setFont(new Font("LCD", Font.PLAIN, 25));
              silver.setForeground(Color.red);
              parrentapp.add(silver);
              // gold
              gold.setBounds(((187*maxSlots)/2)-20, 9 ,200, 50); 
              gold.setFont(new Font("LCD", Font.PLAIN, 35));
              gold.setForeground(Color.red);
              parrentapp.add(gold);
              // background
              ImageIcon = new ImageIcon(parrentapp.getImage(parrentapp.getCodeBase(), "Images/topbox.gif"));
              imageLabel = new JLabel(ImageIcon);
              imageLabel.setBounds(((187*maxSlots)/2)-135, 0, 271, 100);
              parrentapp.add(imageLabel);
              parrentapp.setLayout(null);
         *     displayBronze                              *
         public void displayBronze(double value) {
              bronze.setText(String.valueOf(value) + "0");     
         *     displaySilver                              *
         public void displaySilver(double value) {
              silver.setText(String.valueOf(value) + "0");     
         *     displayGold                                   *
         public void displayGold(double value) {
              gold.setText(String.valueOf(value) + "0");     
         *     clearValue                                   *
         public void clearValue(int value) {
              switch (value) {
             case 0:
                        gold.setText("");     
                        break;
               case 1:
                        silver.setText("");     
                        break;
               case 2:
                        bronze.setText("");     
                        break;
    }silver and gold work fine (old way grabbing from pc)
    trying to convert bronze to work by grabbing font from my server

Maybe you are looking for

  • Adobe Indesign and Ms Word

    Hi, My job primarily involves the usage of Ms Word file with lots of tect and graphics used on it. Now, I found Adobe Indesign to be a powerful tool. However, most of the word documents which i generally use have pages ranging +100. As I am a new use

  • Adobe Reader don't always open instruction pdf files

    I have a 27 inch iMac running the latest osx software 10.8.2. and Adobe Reader 10.1.4. Often when I download instruction manuals, such as the one for iDraw, which I purchased from the App Store;  it says the file is corrupt and can't open it. I have

  • HT4623 Why they install apps under their Apple IDs in the shop???

    Why they install apps under their Apple IDs in the shop??? After I realised that, I cannot make any updates for the apps installed there. Shall I reinstall them or otherwise the problem can be solved?

  • System pref- what do the display numbers mean &other questions

    1. are they the choices that the mini (purchased 9/07) can "send to the display" or are they the monitor's only display choices built into the monitor (like 1024x 768) 2. whats the advantage if any of a widescreen LCD display 3. will any "cheap- ie $

  • VOFM Pricing Requirement - Condition type at header

    Hi Experts, We have a new condition type, we want to use it in all our new invoices and has been made mandatory in the pricing procedure. Both the sales order and invoice have the same pricing procedure. I am using a requirement routine. The code has