使JButton不可见,但要尊重其原始空间 [英] Make JButton invisible but respect its original space

查看:83
本文介绍了使JButton不可见,但要尊重其原始空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GridBagLayout,并且我想将某些按钮设置为不可见(即无法看到或单击),但是当我使用wdButton.setVisible(false)进行操作时,其余按钮会移动.我想将原来由不透明按钮占据的空间保留为空白,并使其余部分保持不变(与提出的问题类似[a href ="https://stackoverflow.com/questions/9495463/how-to-make-a -组件不可见,而无需更改其他元素的位置).那里提出的解决方案对我没有用,因为我不想更改布局.

I am using a GridBagLayout and I want to set some buttons as invisible (i.e. they cannot be seen nor clicked), but when I do so using wdButton.setVisible(false) the rest of the buttons move. I would like to leave the space originally occupied by the invisibilized button blank and keep the rest unaltered (similar problem to the one presented here). The solutions proposed there are not useful to me, since I do not want to change the layout.

目前,我已经可以通过使用以下几行代码来做到这一点:

For the moment, I have been able to do so by using the following lines of code:

wdButton.setText("");
wdButton.setOpaque(false);
wdButton.setContentAreaFilled(false);
wdButton.setBorderPainted(false);
wdButton.setEnabled(false);

有没有更短的方法来实现这一目标?

Is there a shorter way of achieving this?

推荐答案

有没有更短的方法来实现这一目标?

Is there a shorter way of achieving this?

创建一个方法并将按钮作为参数传递.

Create a method and pass in the button as a parameter.

那里提出的解决方案对我没有用,因为我不想更改布局.

The solutions proposed there are not useful to me, since I do not want to change the layout.

该解决方案不涉及更改整个面板的布局管理器.它涉及到使用CardLayout将面板添加到您的主面板中,该面板包含您的按钮和一个空白面板.

The solution did not involve changing the layout manager for then entire panel. It involved adding a panel using a CardLayout containing your button and an empty panel to your main panel.

我想将一些按钮设置为不可见

I want to set some buttons as invisible

您可以将按钮替换为另一个组件:

You could replace the button with another component:

GridBagConstraints gbc = layout.getConstraints( button );
panel.remove( button );
panel.add( new JLabel(" ");
panel.revalidate();

因此,正如您所看到的,您将需要多行代码,因此,请选择最简单的解决方案,然后将代码移至一个方法,这样您只需为要隐藏的每个组件使用一个语句即可.

So as you can see whatever you do it will require multiple lines of code, so pick the easiest solution and just move the code to a method so that you only need to use a single statement for each component you want to hide.

这篇关于使JButton不可见,但要尊重其原始空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆