java simple JPanel management (see screenshot)
I have a JPanel that encapsulates two JPanels, one on top of the other.
The first holds two JLabels which hold the开发者_运维知识库 playing cards.
The second holds the player's text (name and score).
However, when I remove the player's cards, the lower JPanel moves up to the top, which i would prefer that it not do. Is there a way to keep it in place regardless of whether the top JPanel is occupied or not?
Thanks
What layout managers are you using? The default layout manager for a JPanel is a FlowLayout which render child components one after the other.
Maybe you could set the root JPanel to have a BorderLayout. Then set the top JPanel to the root panel's "top" spot:
JPanel rootPanel = ...;
JPanel topPanel = ...;
rootPanel.add(topPanel, BorderLayout.TOP);
Then set a minimum size for your top JPanel:
topPanel.setMinimumSize(new Dimension(someWidth, someHeight));
And add the second panel to the bottom or middle spot:
rootPanel.add(secondPanel, BorderLayout.CENTER);
Check out http://java.sun.com/docs/books/tutorial/uiswing/layout/border.html
I had time to do an example:
public class TestJpanel extends JFrame {
public TestJpanel() {
this.setLayout( new BorderLayout() );
final JLabel card1 = new JLabel( "card1" );
final JLabel card2 = new JLabel( "card2" );
final JPanel topPanel = new JPanel();
topPanel.setPreferredSize( new Dimension( 1024, 100 ) );
topPanel.add( card1 );
topPanel.add( card2 );
this.add( topPanel, BorderLayout.NORTH );
JPanel centerPanel = new JPanel();
final JButton hideCardsButton = new JButton( "Hide cards" );
hideCardsButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
if ( topPanel.getComponentCount() == 0 ) {
topPanel.add( card1 );
topPanel.add( card2 );
hideCardsButton.setText( "Hide cards" );
} else {
topPanel.removeAll();
hideCardsButton.setText( "Show cards" );
}
topPanel.validate();
topPanel.repaint();
}
} );
centerPanel.add( hideCardsButton );
this.add( centerPanel, BorderLayout.CENTER );
}
public static void main( String[] args ) {
TestJpanel window = new TestJpanel();
window.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
window.setSize( 1024, 768 );
window.setVisible( true );
}
}
Note that this code if full of bad practices but helps demonstrate what I want with a short number of lines.
精彩评论