gpt4 book ai didi

java - 使用 JButton 作为图像

转载 作者:行者123 更新时间:2023-12-01 16:50:29 24 4
gpt4 key购买 nike

所以,我面临的问题是我想采用 JButton 的图像模型,并将其用作图像。我以前没有在 swing 中实现过图标,所以我决定做一些搜索。然而,我找不到任何东西来解释这里发生的事情。

我尝试过以下代码:

JButton button = new JButton("Text");
JLabel buttonIcon = new JLabel(button.getIcon());

但是,当我去显示 JLabel 时,什么也没有出现。这种互动有错吗?

我也很满意将 JButton 的模型保存为图像格式,然后将其导入。

任何帮助将不胜感激!

最佳答案

因此,如果您想对可见组件进行快照并将其显示在 JLabel 内,您可以

  1. 将按钮的大小设置为其preferredSize
  2. 创建一个BufferedImage
  3. 调用 button.paint(image.createGraphics()) 将按钮绘制到图像上。
  4. JLabelIcon 设置为包含图像的新图标。
<小时/>

这是一个示例(感谢 camickr helped me 使流程更加清晰):

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Example {

public void createAndShowGUI() {
JButton button = new JButton("Text");
button.setSize(button.getPreferredSize());

JLabel label = new JLabel();
label.setIcon(new ImageIcon(snapshot(button)));

JPanel contentPane = new JPanel();
contentPane.add(label);

JFrame frame = new JFrame();
frame.setContentPane(contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

private BufferedImage snapshot(Component component) {
BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(),
BufferedImage.TYPE_INT_RGB);
component.paint(image.createGraphics());
return image;
}

public static void main(String[] args) {
EventQueue.invokeLater(() -> new Example().createAndShowGUI());
}
}

关于java - 使用 JButton 作为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com