Currently I am trying to add an icon which should be as big as the button (added to GridBagLayout
). I want to scale the icon to the size of the button, but my button shows its size as 0.
I tried to print out the size of the button (after creating it and also after adding it). It always gives me 0 and therefore an ArgumentException
(width (0) and height (0) must be non-zero).
Also I want to dynamically size the font as big as the button is (no implementation yet but also doesn't work because the buttons doesn't give its size).
Does anybody has a solution for dynamic resizing using LayoutManager
? Maybe there is a way to get the cell size and then scale the image to the cell size?
Here is my test code:
import javax.swing.*;
import java.awt.*;
public class TestResize extends JFrame {
private Container cp;
private JPanel levelPane;
private GridBagConstraints gbc = new GridBagConstraints();
public TestResize() {
super();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 200;
int frameHeight = 200;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("temp");
setResizable(false);
cp = getContentPane();
cp.setLayout(new BorderLayout());
createLevelMenu();
setVisible(true);
} // end of public temp
public static void main(String[] args) {
new TestResize();
} // end of main
public void createLevelMenu(){
if (levelPane == null){
levelPane = new JPanel(new GridBagLayout());
gbc.fill = GridBagConstraints.NONE;
JButton back = new JButton();
back.setOpaque(false);
back.setBackground(null);
back.setBorder(null);
addObject(0,0,1,1,GridBagConstraints.FIRST_LINE_START,back);
Image img = (new ImageIcon("Content/Graphics/UI/returnIcon.png")).getImage().getScaledInstance(back.getWidth(),back.getHeight(),Image.SCALE_SMOOTH);
back.setIcon(new ImageIcon(img));
JPanel menu = new JPanel(new BorderLayout());
menu.setBackground(Color.RED);
JLabel l = new JLabel("Demo");
l.setFont(l.getFont().deriveFont(30)); //Font Size as big as Possible (adjust
l.setHorizontalAlignment(SwingConstants.CENTER);
l.setVerticalAlignment(SwingConstants.CENTER);
menu.add(l,BorderLayout.CENTER);
gbc.fill = GridBagConstraints.BOTH;
addObject(2,2,1,4,GridBagConstraints.CENTER,menu);
JButton info = new JButton("Info");
addObject(3,3,1.25f,1.25f,GridBagConstraints.LAST_LINE_END,info);
cp.add(levelPane, BorderLayout.CENTER);
}
}
public void addObject(int gridX,int gridY, double weightX,double weightY,int anchor, JComponent comp){
gbc.gridx =gridX;
gbc.gridy = gridY;
gbc.weightx = weightX;
gbc.weighty = weightY;
gbc.anchor = anchor;
levelPane.add(comp,gbc);
}
}