问题
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?
回答1:
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.
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.
来源:https://stackoverflow.com/questions/24337311/make-jbutton-invisible-but-respect-its-original-space