gpt4 book ai didi

java - Jbutton 超过 Jbutton 背景图像?

转载 作者:行者123 更新时间:2023-11-30 06:29:30 30 4
gpt4 key购买 nike

假设我创建了一个带有 jbuttons 的 2d tile map ,然后在 map 顶部创建了单位,当单位(也是一个 jbutton)位于 tile 顶部时,有没有办法显示 map 的背景,因为如何现在单元的背景只是红色,所以可以用 jbuttons 代替 jbuttons 来做到这一点吗?

最佳答案

如果 Topmost JButton 是 Translucent 可以解决您的目的,这里是一个示例代码,您可以如何做到这一点。只需将在我的案例中使用的 AlphaComposite 值即 0.7f 更改为适合您的代码实例的任何值:

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.FlowLayout;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.net.URL;

import javax.swing.*;

public class TransparentButton
{
private CustomButton button;
private ImageIcon backgroundImage;

private void displayGUI()
{
JFrame frame = new JFrame("Transparent Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.BLUE);

try
{
backgroundImage = new ImageIcon(
new URL("http://gagandeepbali.uk.to/" +
"gaganisonline/images/404error.jpg"));
}
catch(IOException ioe)
{
ioe.printStackTrace();
}

JButton baseButton = new JButton(backgroundImage);
baseButton.setOpaque(true);
baseButton.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

button = new CustomButton("Transparent Button");
baseButton.add(button);

contentPane.add(baseButton);
frame.setContentPane(contentPane);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TransparentButton().displayGUI();
}
});
}
}

class CustomButton extends JButton
{
private BufferedImage buttonImage = null;

public CustomButton(String title)
{
super(title);
setOpaque(false);
}

@Override
public void paint(Graphics g)
{
if (buttonImage == null ||
buttonImage.getWidth() != getWidth() ||
buttonImage.getHeight() != getHeight())
{
buttonImage = (BufferedImage) createImage(
getWidth(), getHeight());
}

Graphics gButton = buttonImage.getGraphics();
gButton.setClip(g.getClip());
super.paint(gButton);
/*
* Make the graphics object sent to
* this paint() method translucent.
*/
Graphics2D g2 = (Graphics2D) g;
AlphaComposite newComposite =
AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.7f);
g2.setComposite(newComposite);
/*
* Copy the JButton's image to the destination
* graphics, translucently.
*/
g2.drawImage(buttonImage, 0, 0, null);
}
}

这是相同的输出:

TRANSPARENT BUTTON

关于java - Jbutton 超过 Jbutton 背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11490622/

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