gpt4 book ai didi

java - 在SWT中添加背景图像到按钮

转载 作者:行者123 更新时间:2023-12-01 22:58:17 25 4
gpt4 key购买 nike

谁能告诉我如何在 SWT 中向按钮添加背景图像?我需要类似附件中的东西。 bg_image

最佳答案

好吧,如果您基本上想要绘制完全不同类型的按钮,Button 并不是最好的起点。但是,您可以使用this创建您自己的小部件。教程。我在这里写了一个例子:

public class ImageButton extends Composite
{
private Color textColor;
private Image image;
private String text;
private int width;
private int height;

public ImageButton(Composite parent, int style)
{
super(parent, style);

textColor = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);

/* Add dispose listener for the image */
addListener(SWT.Dispose, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
if (image != null)
image.dispose();
}
});

/* Add custom paint listener that paints the stars */
addListener(SWT.Paint, new Listener()
{
@Override
public void handleEvent(Event e)
{
paintControl(e);
}
});

/* Listen for click events */
addListener(SWT.MouseDown, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
System.out.println("Click");
}
});
}

private void paintControl(Event event)
{
GC gc = event.gc;

if (image != null)
{
gc.drawImage(image, 1, 1);
Point textSize = gc.textExtent(text);
gc.setForeground(textColor);
gc.drawText(text, (width - textSize.x) / 2 + 1, (height - textSize.y) / 2 + 1, true);
}
}

public void setImage(Image image)
{
this.image = new Image(Display.getDefault(), image, SWT.IMAGE_COPY);
width = image.getBounds().width;
height = image.getBounds().height;
redraw();
}

public void setText(String text)
{
this.text = text;
redraw();
}

@Override
public Point computeSize(int wHint, int hHint, boolean changed)
{
int overallWidth = width;
int overallHeight = height;

/* Consider hints */
if (wHint != SWT.DEFAULT && wHint < overallWidth)
overallWidth = wHint;

if (hHint != SWT.DEFAULT && hHint < overallHeight)
overallHeight = hHint;

/* Return computed dimensions plus border */
return new Point(overallWidth + 2, overallHeight + 2);
}

public static void main(String[] args)
{
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));

ImageButton button = new ImageButton(shell, SWT.NONE);
button.setImage(new Image(display, "button.png"));
button.setText("Button");

shell.pack();
shell.open();

while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

看起来像这样:

enter image description here

<小时/>

当然,您必须处理不同的状态,例如按下悬停等。

关于java - 在SWT中添加背景图像到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729981/

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