在java.awt.Graphics上绘制java.awt.Cursor

时间:2013-05-03 12:27:45

标签: java swing cursor awt graphics2d

是否可以以位图图片的形式(例如Cursor)或BufferedImage上可绘制的任何内容获取标准AWT Graphics2D?例如,文本光标new Cursor(Cursor.TEXT_CURSOR)

我相信这些游标会根据原生平台进行更改,我希望将它们合并到一些Swing图标中。

1 个答案:

答案 0 :(得分:3)

即使您使用自己的图标,也可以显示稍后将在给定上下文中使用的与平台相关的光标。将鼠标悬停在按钮和相邻面板上以查看效果。使用图标的组件上的工具提示总是很好的。

image

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;

/**
 * @see http://stackoverflow.com/a/16363072/230513
 */
public class Test {

    private static class CursorPanel extends JPanel {

        private static final Icon ICON = UIManager.getIcon("html.pendingImage");
        private Cursor cursor;

        public CursorPanel(final Cursor cursor) {
            this.cursor = cursor;
            String name = cursor.getName();
            JButton button = new JButton(name, ICON);
            button.setCursor(cursor);
            button.setToolTipText(name);
            this.add(button);
            final JPanel panel = new JPanel() {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(200, 125);
                }
            };
            panel.setCursor(cursor);
            panel.setBorder(new TitledBorder(name));
            this.add(panel);
        }
    }

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridLayout(0, 1));
        f.add(new CursorPanel(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)));
        f.add(new CursorPanel(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}