【发布时间】:2021-12-02 20:55:12
【问题描述】:
目前我正在尝试添加一个应该与按钮一样大的图标(添加到GridBagLayout)。我想将图标缩放到按钮的大小,但我的按钮显示其大小为 0。
我尝试打印出按钮的大小(在创建按钮之后以及添加之后)。它总是给我0,因此ArgumentException(宽度(0)和高度(0)必须非零)。
我还想动态调整字体的大小,使其与按钮一样大(目前还没有实现,但也不起作用,因为按钮没有给出它的大小)。
有人有使用LayoutManager 动态调整大小的解决方案吗?也许有一种方法可以获取单元格大小,然后将图像缩放到单元格大小?
这是我的测试代码:
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);
}
}
【问题讨论】:
-
虽然不常用,Icon is an interface 可以自己实现。
-
另见this answer 如何根据 JButton 的大小更改其字体大小?
标签: java swing layout-manager image-resizing gridbaglayout