下面列出了怎么用javax.swing.ImageIcon的API类实例代码及写法,或者点击链接到github查看源代码。
public MessageWindow(Rectangle rect) {
this.rect = rect;
innerRect = new Rectangle(
rect.x + EDGE_WIDTH,
rect.y + EDGE_WIDTH,
rect.width - EDGE_WIDTH * 2,
rect.height - EDGE_WIDTH * 2);
textRect = new Rectangle(
innerRect.x + 16,
innerRect.y + 16,
320,
120);
// ���b�Z�[�W�G���W�����쐬
messageEngine = new MessageEngine();
// �J�[�\���C���[�W�����[�h
ImageIcon icon = new ImageIcon(getClass().getResource("image/cursor.gif"));
cursorImage = icon.getImage();
timer = new Timer();
}
/**
* Helper method to load an image file from the CLASSPATH
* @param imageName the package and name of the file to load relative to the CLASSPATH
* @return an ImageIcon instance with the specified image file
* @throws IllegalArgumentException if the image resource cannot be loaded.
*/
public ImageIcon loadImage( String imageName )
{
try
{
ClassLoader classloader = getClass().getClassLoader();
java.net.URL url = classloader.getResource( imageName );
if ( url != null )
{
ImageIcon icon = new ImageIcon( url );
return icon;
}
}
catch( Exception e )
{
e.printStackTrace();
}
throw new IllegalArgumentException( "Unable to load image: " + imageName );
}
private void displayWeight(List<Double> currentKernel) {
JFrame frame = new JFrame("Weight Visualiser: ");
frame.setSize(400, 400);
JLabel label = new JLabel();
Dimension d = new Dimension(kernel.getWidth() * RATIO, kernel.getHeight() * RATIO);
label.setSize(d);
label.setPreferredSize(d);
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
BufferedImage image = new BufferedImage(kernel.getWidth(), kernel.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
int[] rgb = convertWeightToRGB(currentKernel);
image.setRGB(0, 0, kernel.getWidth(), kernel.getHeight(), rgb, 0, kernel.getWidth());
label.setIcon(new ImageIcon(image.getScaledInstance(kernel.getWidth() * RATIO, kernel.getHeight() * RATIO, Image.SCALE_SMOOTH)));
}
private void addShowAxesButton(JToolBar buttonBar, Insets margin) {
xyzAxis = new JToggleButton( new ImageIcon(
GUIFrame.class.getResource("/resources/images/Axes-16.png")) );
xyzAxis.setMargin(margin);
xyzAxis.setFocusPainted(false);
xyzAxis.setRequestFocusEnabled(false);
xyzAxis.setToolTipText(formatToolTip("Show Axes",
"Shows the unit vectors for the x, y, and z axes."));
xyzAxis.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent event ) {
DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XYZ-Axis");
if (ent != null) {
KeywordIndex kw = InputAgent.formatBoolean("Show", xyzAxis.isSelected());
InputAgent.storeAndExecute(new KeywordCommand(ent, kw));
}
controlStartResume.requestFocusInWindow();
}
} );
buttonBar.add( xyzAxis );
}
private static Icon findIconForPath(String path) {
FileObject fo = RecentFiles.convertPath2File(path);
final Icon i;
if (fo == null) {
i = null;
} else {
DataObject dObj;
try {
dObj = DataObject.find(fo);
} catch (DataObjectNotFoundException e) {
dObj = null;
}
i = dObj == null
? null
: new ImageIcon(dObj.getNodeDelegate().getIcon(
BeanInfo.ICON_COLOR_16x16));
}
return i;
}
/** Samples a trivial number of pixels from an image and compares them with
*pixels from a component to determine if the image is painted on the
* component at the exact position specified */
private void assertImageMatch(String msg, Image i, JComponent comp, int xpos, int ypos) throws Exception {
ImageIcon ic = new ImageIcon(i);
int width = ic.getIconWidth();
int height = ic.getIconHeight();
for (int x=2; x < 5; x++) {
for (int y=2; y < 5; y++) {
int posX = width / x;
int posY = height / y;
System.err.println(" Check " + posX + "," + posY);
assertPixelFromImage(msg, i, comp, posX, posY, xpos + posX, ypos + posY);
}
}
}
@Override
public Component getListCellRendererComponent(
final JList<?> list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
super.getListCellRendererComponent(
list, ((GamePlayer) value).getName(), index, isSelected, cellHasFocus);
if (uiContext == null || value == GamePlayer.NULL_PLAYERID) {
setIcon(new ImageIcon(Util.newImage(32, 32, true)));
} else {
setIcon(new ImageIcon(uiContext.getFlagImageFactory().getFlag((GamePlayer) value)));
}
return this;
}
/**
* Defines an <code>Action</code> object with a default description string and default icon.
*
* @param dataSourceList the list containing the datasources
*/
private RemoveDataSourceAction(final JList dataSourceList)
{
this.dataSourceList = dataSourceList;
setEnabled(getDialogModel().isConnectionSelected());
final URL resource = ConnectionPanel.class.getResource("/org/pentaho/reporting/ui/datasources/jdbc/resources/Remove.png");
if (resource != null)
{
putValue(Action.SMALL_ICON, new ImageIcon(resource));
}
else
{
putValue(Action.NAME, bundleSupport.getString("ConnectionPanel.Remove.Name"));
}
putValue(Action.SHORT_DESCRIPTION, bundleSupport.getString("ConnectionPanel.Remove.Description"));
}
/**
* Use null for default Images
*
* @param checkedImg Image that should be displayed if checked
* @param uncheckedImg Image that should be displayed if not checked
*/
public CustomCheckBoxEditor(String uncheckedImg, String checkedImg) {
super(new JCheckBox());
setClickCountToStart(0);
editorComponent = (JCheckBox) super.editorComponent;
editorComponent.setHorizontalAlignment(SwingConstants.CENTER);
editorComponent.setText("");
try {
unchecked = new ImageIcon(this.getClass().getResource(uncheckedImg));
checked = new ImageIcon(this.getClass().getResource(checkedImg));
} catch (Exception e) {
unchecked = null;
checked = null;
}
}
ImageTopComponent(Image image, String className, int instanceNumber) {
setName(BrowserUtils.getSimpleType(className) + "#" + instanceNumber);
setToolTipText("Preview of " + className + "#" + instanceNumber);
setLayout(new BorderLayout());
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage displayedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = displayedImage.createGraphics();
drawChecker(g, 0, 0, width, height);
g.drawImage(image, 0, 0, null);
JComponent c = new JScrollPane(new JLabel(new ImageIcon(displayedImage)));
add(c, BorderLayout.CENTER);
JToolBar toolBar = new JToolBar();
toolBar.putClientProperty("JToolBar.isRollover", Boolean.TRUE); //NOI18N
toolBar.setFloatable(false);
toolBar.setName(Bundle.ImageDetailProvider_Toolbar());
//JButton button = new JButton();
//button.setText("");
toolBar.add(new ImageExportAction(image));
add(toolBar, BorderLayout.NORTH);
}
public CreateImpliedMatchAction(VTController controller,
VTImpliedMatchesTableProvider provider) {
super("Accept Implied Match", VTPlugin.OWNER);
this.controller = controller;
this.provider = provider;
ImageIcon icon = ResourceManager.loadImage("images/flag.png");
setToolBarData(new ToolBarData(icon, "1"));
setPopupMenuData(new MenuData(new String[] { "Accept Implied Match" }, icon, "1"));
setHelpLocation(new HelpLocation("VersionTrackingPlugin", "Accept_Implied_Match"));
setEnabled(false);
}
protected Icon computeIcon() {
ImageIcon icon = BrowserUtils.ICON_PRIMITIVE;
if (isStatic()) {
icon = BrowserUtils.createStaticIcon(icon);
}
return icon;
}
public ImageIcon getScreenShotImage() {
if (img.getHeight() > img.getWidth()) {
scaleFactor = label.getHeight() / (double) img.getHeight();
} else {
scaleFactor = label.getWidth() / (double) img.getWidth();
}
int width = (int) (img.getWidth() * scaleFactor);
int height = (int) (img.getHeight() * scaleFactor);
Image scaled = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
return new ImageIcon(scaled);
}
private JFrame createSharingFrame() {
Config config = Config.getInstance();
ResourceBundle resourceBundle = config.getResourceBundle();
String title = resourceBundle.getString("share_panel_title");
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setIconImage(new ImageIcon(config.getResDir()+File.separator+"logo48.png").getImage());
return frame;
}
private void setQrImage(Image img)
{
ImageIcon ii = new ImageIcon(img);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
address_qr_label.setIcon(ii);
}
});
}
private RemoveParameterAction()
{
final URL resource = CdaDataSourceEditor.class.getResource
("/org/pentaho/reporting/ui/datasources/cda/resources/Remove.png");
if (resource != null)
{
putValue(Action.SMALL_ICON, new ImageIcon(resource));
}
else
{
putValue(Action.NAME, Messages.getString("ParameterEditorDialog.RemoveParameter.Name"));
}
putValue(Action.SHORT_DESCRIPTION, Messages.getString("ParameterEditorDialog.RemoveParameter.Description"));
}
public static ImageIcon createImageIconFromPath(String path){
try {
return new ImageIcon(new URL(path));
}catch (Exception e) {
return new ImageIcon(path);
}
}
ZapToggleButton getEnableToggleButton() {
if (enableButton == null) {
enableButton =
new ZapToggleButton(
Constant.messages.getString("wappalyzer.toolbar.toggle.state.enabled"),
true);
enableButton.setIcon(
new ImageIcon(
TechPanel.class.getResource(
ExtensionWappalyzer.RESOURCE + "/off.png")));
enableButton.setToolTipText(
Constant.messages.getString(
"wappalyzer.toolbar.toggle.state.disabled.tooltip"));
enableButton.setSelectedIcon(
new ImageIcon(
TechPanel.class.getResource(ExtensionWappalyzer.RESOURCE + "/on.png")));
enableButton.setSelectedToolTipText(
Constant.messages.getString("wappalyzer.toolbar.toggle.state.enabled.tooltip"));
enableButton.addItemListener(
event -> {
if (event.getStateChange() == ItemEvent.SELECTED) {
enableButton.setText(
Constant.messages.getString(
"wappalyzer.toolbar.toggle.state.enabled"));
extension.setWappalyzer(true);
} else {
enableButton.setText(
Constant.messages.getString(
"wappalyzer.toolbar.toggle.state.disabled"));
extension.setWappalyzer(false);
}
});
}
return enableButton;
}
/**
* 创建窗口
* filePath为图片地址
*/
@SuppressWarnings("serial")
public QRCodeFrame(final String filePath) {
setBackground(Color.WHITE);
this.setResizable(false);
//this.setUndecorated(true);//二维码窗口无边框
this.setTitle("\u626b\u7801\u767b\u9646\u5fae\u4fe1");//扫码登陆微信
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 295, 315);
this.contentPane.setBackground(new Color(102, 153, 255));
this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.setContentPane(contentPane);
this.contentPane.setLayout(null);
JPanel qrcodePanel = new JPanel(){
public void paintComponent(Graphics g) {
ImageIcon icon = new ImageIcon(filePath);
// 图片随窗体大小而变化
g.drawImage(icon.getImage(), 0, 0, 301, 301, this);
}
};
qrcodePanel.setBounds(0, 0, 295, 295);
this.contentPane.add(qrcodePanel);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
/**
* Creates a new instance of AttributeResultItem
*/
public AttributeResultItem(AbstractAttribute attribute, CompletionContext context) {
super(attribute, context);
itemText = attribute.getName();
icon = new ImageIcon(CompletionResultItem.class.
getResource(ICON_LOCATION + ICON_ATTRIBUTE));
}
private static ImageIcon convertStrokeToIcon(Stroke stroke) {
Shape strokeShape = new Line2D.Double(-40, 0, 40, 0);
final Rectangle rectangle = strokeShape.getBounds();
BufferedImage image = new BufferedImage((int) (rectangle.getWidth() - rectangle.getX()),
1,
BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = image.createGraphics();
graphics.translate(-rectangle.x, -rectangle.y);
graphics.setColor(Color.BLACK);
graphics.setStroke(stroke);
graphics.draw(strokeShape);
graphics.dispose();
return new ImageIcon(image);
}
public ImageIcon getIcon(String name)
{
String imagePath = "/toolbarButtonGraphics/" + name;
java.net.URL url = getClass().getResource(imagePath);
if(url != null)
return new ImageIcon(url);
else
return null;
}
/**
* Returns the image of a specific card.
*
* @param card
* The card.
*
* @return The image.
*/
public static ImageIcon getCardImage(Card card) {
// Use image order, which is different from value order.
int sequenceNr = card.getSuit() * Card.NO_OF_RANKS + card.getRank();
String sequenceNrString = String.valueOf(sequenceNr);
if (sequenceNrString.length() == 1) {
sequenceNrString = "0" + sequenceNrString;
}
String path = String.format(IMAGE_PATH_FORMAT, sequenceNrString);
return getIcon(path);
}
public static ImageIcon getImageIcon(String imageName) {
try {
final URL imageURL = getURL(imageName);
return new ImageIcon(imageURL);
}
catch (Exception ex) {
Log.error(imageName + " not found.");
}
return null;
}
/** Creates a new instance of MenuExecAction */
public MenuExecAction(AppView app, String icon, String keytext, String sMyView) {
putValue(Action.SMALL_ICON, new ImageIcon(JPrincipalApp.class.getResource(icon)));
putValue(Action.NAME, AppLocal.getIntString(keytext));
putValue(AppUserView.ACTION_TASKNAME, sMyView);
m_App = app;
m_sMyView = sMyView;
}
public void drawImage(Object img, int x, int y) {
if(trackDrawing && trackedDrawing != null) {
trackedDrawing.addRow(new Object[] {
"drawImage(" + x + ", " + y + ")",
"Image size: " + ((BufferedImage) img).getWidth() + "x" + ((BufferedImage) img).getHeight(),
"",
getStackTrace(new Throwable()),
new ImageIcon((BufferedImage)img)
});
}
}
public OpenQualifierAction() {
putValue(ACTION_COMMAND_KEY, "Action.OpenQualifier");
putValue(
SMALL_ICON,
new ImageIcon(getClass().getResource(
"/com/ramussoft/gui/open.png")));
this.putValue(
ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK
| KeyEvent.SHIFT_MASK));
}
private void init() {
treeModel.setRoot(createRoot());
tree = new JTree(treeModel) {
@Override
public TreeCellRenderer getCellRenderer() {
TreeCellRenderer renderer = super.getCellRenderer();
if (renderer == null)
return null;
((DefaultTreeCellRenderer) renderer).setLeafIcon(new ImageIcon(
getClass().getResource("/images/function.png")));
return renderer;
}
};
tree.setCellRenderer(new Renderer());
tree.setEditable(true);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if ((e.getButton() == MouseEvent.BUTTON1)
&& (e.getClickCount() == 2)) {
openDiagram();
}
}
});
tree.setRootVisible(true);
JScrollPane pane = new JScrollPane();
pane.setViewportView(tree);
this.add(pane, BorderLayout.CENTER);
}
/**
* Creates a new instance which acts on the currently focused component.
*/
public DeleteAction() {
super(ID);
putValue(NAME, BUNDLE.getString("deleteAction.name"));
putValue(SHORT_DESCRIPTION, BUNDLE.getString("deleteAction.shortDescription"));
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("DEL"));
ImageIcon image = ImageDirectory.getImageIcon("/menu/edit-delete-2.png");
putValue(SMALL_ICON, image);
putValue(LARGE_ICON_KEY, image);
}
@Override
// return diabled icon if enabled is true else null
public Image getIcon(int i) {
URL imageURL;
if (!enabled){
imageURL = this.getClass().getResource("icons/disabledNode.png");
if (imageURL != null) {
return new ImageIcon(imageURL, "Controller").getImage();
} else {
return null;
}
}
return null;
}