我正在尝试调整容器面板中的面板大小,其中容器面板的布局设置为 null。
我正在设置位置并更改大小,如下所示:
panelCapture.setLocation(
scale.scale(((capture.getTotalBounds().width + 500) / 2) - (capture.getTotalBounds().width / 2)),
scale.scale(((capture.getTotalBounds().height + 500) / 2) - (capture.getTotalBounds().height / 2))
);
Dimension pcSize = panelCapture.getSize();
Dimension pcNewSize = new Dimension(scale.scale(pcSize.width), scale.scale(pcSize.height));
panelCapture.setSize(pcNewSize);
panelCapture.setPreferredSize(pcNewSize);
缩放比例将其乘以我当前的比例,即 1.0f、1.1f 等。
更改位置似乎有效,但更改大小无效。
最佳答案
不要使用 setLocation 和 setSize,而是尝试 setBounds(...)或setPreferredSize(...) 。之后您可能还需要调用 repaint() 。您可能需要引用使用绝对/空布局的教程 here .
这是我编写的一个示例,用于更改另一个 JPanel 中 JPanel 的大小,该 JPanel 具有空布局(仅使用 setBounds)。
public class Capture
{
JPanel capture;
JPanel panelCapture;
JTextField scaleField;
JButton changeScale;
static final int PARENT_WIDTH = 800;
static final int PARENT_HEIGHT = 600;
static final int CHILD_WIDTH = 100;
static final int CHILD_HEIGHT = 100;
public static void main(String [] args)
{
Capture c = new Capture();
c.doStuff();
}
public void doStuff()
{
capture = new JPanel();
capture.setLayout(null);
capture.setPreferredSize(new Dimension(PARENT_WIDTH, PARENT_HEIGHT));
scaleField = new JTextField();
scaleField.setBounds(100, 550, 200, 25);
capture.add(scaleField);
changeScale = new JButton("Scale");
changeScale.setBounds(325, 550, 100, 25);
changeScale.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
panelCapture.setBounds(getBounds(CHILD_WIDTH * Float.parseFloat(scaleField.getText()), CHILD_HEIGHT * Float.parseFloat(scaleField.getText())));
}
});
capture.add(changeScale);
panelCapture = new JPanel();
panelCapture.setBackground(Color.blue);
panelCapture.setBounds(getBounds(CHILD_WIDTH, CHILD_HEIGHT));
capture.add(panelCapture);
JFrame frame = new JFrame();
frame.setContentPane(capture);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private Rectangle getBounds(float width, float height)
{
int left = (int) (PARENT_WIDTH - width) / 2;
int top = (int) (PARENT_HEIGHT - height) / 2;
return new Rectangle(left, top, (int) width, (int) height);
}
}
关于java - 如何在空布局中强制调整 JComponent 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512700/