简体   繁体   中英

make JLabel fit its parent JPanel or give a minimum size to it

I have a gridlayout that consist from jPanels. Every JPanel containst a JLabel, they are 9x9. For this is a chess game, I need to be able to highlight every jPanel or its jLabel upon some events (such as being possible move option or an endangered field). However, I can only highlight fields that have their icons (figures) set, which means an empty jLabel has probably zero dimensions.

This is how I put a figure in jLabel ( it sucks , but it somewhat works):

public void drawFigureAt(Figure fg, int x, int y) {
    //retrieve the Jlabel from the field array
    JLabel pole = policka_l[y*8+x];
    //Set icon from file
    pole.setIcon(new ImageIcon(fg.imageName()+(fg.color==1?"_white":"_black")+".png"));
    //force redraw or whatever it is
    pole.revalidate();
}

Some of the fields are now highlighted in very transparent black, so I can see that the JLabels ar as large as their icon is.
This is how I highlight:

public void highlightField(int x, int y, Color color) {
    //Get the JLabel obejct
    JLabel pole = policka_l[y*8+x];
    //Set the color as the background
    pole.setBackground(color);
    //What is this?
    pole.setOpaque(true);
    //Another magic
    pole.revalidate();
    repaint();
}

But, as I've said, if JLabel has no icon, it can't be highlighted and that's very sad form me. I's much worse that this is a school project that must work this morning, so using different rendering system is not in question.
I've found some clues how to deal with it, however, they don't work. I hoped a lot in this:

JLabelinstance.setMinimumSize(new Dimension(70, 70));

No effect unfortunatelly.

So what I want now is to either make the function above work, or even better - configure JLabels to fill their parent JPanels so that highlighting will look nice, not stupid.
Also my figures do not resize with the window at all, so they tend to overflow.

I have a gridlayout that consist from jPanels.

You could:

1) Just add the labels directly to the GridLayout. Then the label will be the size of the grid
2) Set the layout manager of the panel to be a BorderLayout, then the label will be resized to fill the entire space of the panel.

 pole.setBackground(color);
 pole.setOpaque(true);
 //pole.revalidate();
 //repaint();

The revalidate() and repaint() methods are not needed. Swing components will automatically repaint themselves when a property changes.

Also my figures do not resize with the window at all, so they tend to overflow.

Don't use setSize(). You should add the icons to the label and then labels to the grid. Then pack() the frame and the grid will be sized to hold the largest icon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM