Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

java - How to make draggable components with ImageIcon

I'm trying to build a user interface for a chess game. I've used a GridBagLayout filled with JLabels and the chess pieces are ImageIcons of the JLabels.

Now I would like to move the pieces by dragging it on the board. Is there a way to do this with ImageIcons? Or is there a better way to solve the problem?

EDIT: here is a sample code. you can notice that you can move the iconImage, but it doesn't "drag" with the mouse.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;




public class MainDebug extends JFrame implements MouseListener {

    private JPanel BoardPanel;


    private String buffercase_mousepressed;
    private String buffercase_mouseentered;

    private JLabel A8 = new JLabel("A8");
    private JLabel B8 = new JLabel("B8");

    private HashMap componentMap;

    private ImageIcon RookIcon = createImageIcon("50px-Rook.png", "Rook");



    public MainDebug(String name) {
        super(name);
        setResizable(true);

    }

    private ImageIcon createImageIcon(String path, String description) {

        java.net.URL imgURL = getClass().getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
            }
    }

    public void addComponentsToPane(final Container pane) {

        BoardPanel = new JPanel();
        BoardPanel.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        Dimension dim50 = new Dimension(50,50);

        A8.setOpaque(true);
        A8.setBackground(Color.white);
        A8.setPreferredSize(dim50);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        BoardPanel.add(A8,c);
        A8.setName("A8");
        A8.addMouseListener(this);


        B8.setOpaque(true);
        B8.setBackground(Color.lightGray);
        B8.setPreferredSize(dim50);
        B8.setName("B8");
        c.gridx=1;
        BoardPanel.add(B8,c);
        B8.addMouseListener(this);

        A8.setIcon(RookIcon);

        pane.add(BoardPanel, BorderLayout.CENTER);

        createComponentMap();

    }

    private void createComponentMap() {
        componentMap = new HashMap<String,Component>();

        int max_components = BoardPanel.getComponentCount();
        //Component[] components = BoardPanel.getComponentCount();
        //Component[] components = BoardPanel.getContentPane().getComponents();
        for (int i=0; i < max_components; i++) {
                componentMap.put(BoardPanel.getComponent(i).getName(), BoardPanel.getComponent(i));
        }
    }

    public Component getComponentByName(String name) {
        if (componentMap.containsKey(name)) {
                return (Component) componentMap.get(name);
        }
        else return null;
}

    public void mousePressed(MouseEvent e) {

        buffercase_mousepressed = e.getComponent().getName();
    }

    public void mouseReleased(MouseEvent e) {

        moveIcon(buffercase_mousepressed,buffercase_mouseentered);
    }

    public void mouseEntered(MouseEvent e) {

        buffercase_mouseentered = e.getComponent().getName();
    }


    public void mouseExited(MouseEvent e) {

    }

    public void mouseClicked(MouseEvent e) {

    }


    public void moveIcon(String A, String B){

        if ((A != null) && (B != null)){

            JLabel Ja = (JLabel)getComponentByName(A);
            JLabel Jb = (JLabel)getComponentByName(B);

            Icon iconeA = Ja.getIcon();
            Icon iconeB = Jb.getIcon();

            if (iconeA != null && iconeB == null){

                Ja.setIcon(null);
                Jb.setIcon(iconeA);

            }

        }

        buffercase_mousepressed = null;
        buffercase_mouseentered = null;
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        MainDebug frame = new MainDebug("Test interface");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });


    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some years ago I wrote a framework to customize Swing controls.

Maybe you can use it as a start and tweak it for your use case.

Tutorial: http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html

Javadoc:

http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/index.html

Maven:

<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>softsmithy-lib-swing-customizer</artifactId>  
    <version>0.3</version>  
</dependency>  

You might want to implement an alternative CustomizerLayout to replace InfiniteTableLayout with a Chessboard layout, possibly also extending AbstractCustomizerLayout.

You can use a JXIconCustomizer for image/icon support. You also might want to remove "width" and "height" from the set of customizable propteries of the JXIconCustomizer, to prevent the user from changing the size of the images: http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/org/softsmithy/lib/swing/customizer/AbstractCustomizer.html#getCustomizableProperties%28%29

You can find more information about the latest release here: http://puces-blog.blogspot.ch/2012/11/news-from-software-smithy-version-03.html

If you feel this approach doesn't work for you for some reason, you could have a look at the source code (the library is Open Source) to get some starting points:

http://softsmithy.hg.sourceforge.net/hgweb/softsmithy/lib/main-golden/file/6171c01d6fd0/softsmithy-lib-swing-customizer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...