J卡列表?

发布于 2024-12-09 10:36:39 字数 248 浏览 3 评论 0原文

这与:如何在运行时制作动态图像有关?

获得页面图像后,我想将它们呈现在列表中,以便用户可以选择要播放的页面。我知道 JList 确实支持图像,但这会显示整个图像,失去卡片组的感觉。也许我只会显示图像的边缘及其名称,并以某种方式突出显示它。

有什么想法吗?

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

After 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼趣 2024-12-16 10:36:40

我能够把它拉出来。您可以在此处从此代码中获取图像:http://leepoint。 net/notes-java/examples/graphics/cardDemo/cards20.zip

Card.java

package deck.displayer;

import javax.swing.ImageIcon;

/**
*
* @author Javier A. Ortiz <[email protected]>
*/
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 <[email protected]>
 */
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 <[email protected]>
 */
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
}

以下是输出:

示例

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 <[email protected]>
*/
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 <[email protected]>
 */
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 <[email protected]>
 */
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:

example

じее 2024-12-16 10:36:39

指针:您可以使用Layerd Pane

您可能必须打破 JList 的思维定势,然后根据您的 UI 需求考虑不同的组件。您不能在 JList 中使用 LayeredPane(是的,您可以,但不能没有 10K 行的复杂性和错误)。

备用指针 - 如果您必须使用 JList,请考虑 这篇文章

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文