开发者

JList of cards?

This is related to: How to make a dynamic image at run time?

Aft开发者_运维知识库er I have the page images I would like to present them in a list so the user can select the page to play. I know JList do support images but that would display the whole image losing the card deck feeling. Probably I would only show the edge of the image with its name and highlight it somehow.

Any idea?


Pointer: You may use Layerd Pane

You may have to break your mind-set with JList and then think of a different component, based on your UI needs. You can not use a LayeredPane inside a JList (yes you can, but not with out 10K lines of complexity and bugs).

Alternate Pointer - if you so have to use JList, consider this SO post


I was able to pull it out. You can get the images from this code here: http://leepoint.net/notes-java/examples/graphics/cardDemo/cards20.zip

Card.java

package deck.displayer;

import javax.swing.ImageIcon;

/**
*
* @author Javier A. Ortiz <javier.ortiz.78@gmail.com>
*/
public class Card {

private String text;
private ImageIcon icon;

public Card(String text, ImageIcon icon) {
    this.text = text;
    this.icon = icon;
}

/**
 * @return the text
 */
public String getText() {
    return text;
}

/**
 * @return the icon
 */
public ImageIcon getIcon() {
    return icon;
}
}

CardCellRenderer.java

package deck.displayer;

import java.awt.Component;
import java.awt.Font;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

/**
 *
 * @author Javier A. Ortiz <javier.ortiz.78@gmail.com>
 */
public class CardCellRenderer extends JLabel implements ListCellRenderer {

    private Font uhOhFont;

    @Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }
    Card card = (Card) value;
    setIcon(card.getIcon());
    if (getIcon() != null) {
        if (index != list.getModel().getSize() - 1) {
            setIcon(new ImageIcon(createImage(new FilteredImageSource(((ImageIcon) getIcon()).getImage().getSource(),
                    new CropImageFilter(0, 0, getIcon().getIconWidth(), 20)))));
        }
        setFont(list.getFont());
    } else {
        setUhOhText(card.getText() + " (no image available)",
                list.getFont());
    }
    return this;
}
//Set the font and text when no image was found.

protected void setUhOhText(String uhOhText, Font normalFont) {
    if (uhOhFont == null) { //lazily create this font
        uhOhFont = normalFont.deriveFont(Font.ITALIC);
    }
    setFont(uhOhFont);
    setText(uhOhText);
}
}

Test.java

package deck.displayer;

import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;

/**
 *
 * @author Javier A. Ortiz <javier.ortiz.78@gmail.com>
 */
public class Test extends javax.swing.JFrame {
ArrayList<Card> cards = new ArrayList<Card>();

/**
 * Creates new form Test
 */
public Test() {
    try {
        initComponents();
        String suits = "shdc";
        String faces = "a23456789tjqk";
        for (int suit = 0; suit < suits.length(); suit++) {
            for (int face = 0; face < faces.length(); face++) {
                //... Get the image from the images subdirectory.
                String imagePath = "cards/" + faces.charAt(face)
                        + suits.charAt(suit) + ".gif";
                URL imageURL = this.getClass().getResource(imagePath);
                ImageIcon img = new ImageIcon(imageURL);

                //... Create a card and add it to the deck.
                System.out.println("Adding: "+String.valueOf(faces.charAt(face))
                        + String.valueOf(suits.charAt(suit)));
                cards.add(new Card(String.valueOf(faces.charAt(face))
                        + String.valueOf(suits.charAt(suit)), img));
            }
        }
        pageList.setCellRenderer(new CardCellRenderer());
        pageList.setModel(new javax.swing.AbstractListModel() {

            @Override
            public int getSize() {
                return cards.size();
            }

            @Override
            public Object getElementAt(int i) {
                return cards.get(i);
            }
        });
    } catch (Exception e) {
        System.exit(1);
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    pageList = new javax.swing.JList();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    pageList.setModel(new javax.swing.AbstractListModel() {
        String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
        public int getSize() { return strings.length; }
        public Object getElementAt(int i) { return strings[i]; }
    });
    jScrollPane1.setViewportView(pageList);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new Test().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList pageList;
// End of variables declaration
}

Here's the output:

JList of cards?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜