如何将标签放在按钮上?
How can I place Label over Button?
题目已经说明了一切,如何将Label直接放在Button上?尝试了多种方法,没有任何效果。我不能使用 button.setTest("xxx");在这种情况下。
编辑:我认为在标签中提及 SWT 库就足够了。我有点为代码感到羞耻,因此我不想 post 它。
问题是我创建了 很多 按钮使用 for 循环,所以我不能通过它们的变量名来寻址它们.我的想法是创建另一个 "layer" 标签并将它们放在按钮上。单击按钮 后 应显示标签。
MouseListener posluchac = new MouseAdapter() {
@Override
public void mouseDown(MouseEvent me) {
for (int k = 0;k<sirka;k++)
{
for (int l = 0;l<vyska;l++)
{
if(me.getSource() == cudliky[k][l])
{
System.out.println(k +" "+ l);
Label lbl4 = new Label(cmpst2, SWT.NONE);
lbl4.setText("X");
lbl4.setBounds((990-sirka*25)/2+k*25,(800-vyska*25)/2+l*25,25,25);
}
}
}
}
}
此代码创建隐藏的标签。
你打错了。
button.setText("xxx"); // works
即使您不希望按钮有初始文本,也无需在 Button
之上放置 Label
。这一切都可以通过使用右Layout
或LayoutData
来实现。下面是一个使用 5 列的 GridLayout
的示例。这些按钮最初没有文字,但在您点击它们之后(如您在问题中所述):
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(5, true));
for (int i = 0; i < 30; i++)
{
Button button = new Button(shell, SWT.PUSH);
button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
button.addListener(SWT.Selection, e -> button.setText(UUID.randomUUID().toString().substring(0, 10)));
}
shell.pack();
shell.open();
shell.setSize(600, 300);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
看起来像这样:
题目已经说明了一切,如何将Label直接放在Button上?尝试了多种方法,没有任何效果。我不能使用 button.setTest("xxx");在这种情况下。
编辑:我认为在标签中提及 SWT 库就足够了。我有点为代码感到羞耻,因此我不想 post 它。
问题是我创建了 很多 按钮使用 for 循环,所以我不能通过它们的变量名来寻址它们.我的想法是创建另一个 "layer" 标签并将它们放在按钮上。单击按钮 后 应显示标签。
MouseListener posluchac = new MouseAdapter() {
@Override
public void mouseDown(MouseEvent me) {
for (int k = 0;k<sirka;k++)
{
for (int l = 0;l<vyska;l++)
{
if(me.getSource() == cudliky[k][l])
{
System.out.println(k +" "+ l);
Label lbl4 = new Label(cmpst2, SWT.NONE);
lbl4.setText("X");
lbl4.setBounds((990-sirka*25)/2+k*25,(800-vyska*25)/2+l*25,25,25);
}
}
}
}
}
此代码创建隐藏的标签。
你打错了。
button.setText("xxx"); // works
即使您不希望按钮有初始文本,也无需在 Button
之上放置 Label
。这一切都可以通过使用右Layout
或LayoutData
来实现。下面是一个使用 5 列的 GridLayout
的示例。这些按钮最初没有文字,但在您点击它们之后(如您在问题中所述):
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(5, true));
for (int i = 0; i < 30; i++)
{
Button button = new Button(shell, SWT.PUSH);
button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
button.addListener(SWT.Selection, e -> button.setText(UUID.randomUUID().toString().substring(0, 10)));
}
shell.pack();
shell.open();
shell.setSize(600, 300);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
看起来像这样: