[英]How to resize JComponent forcefully in a null layout?
我正在嘗試在容器面板的布局設置為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()。 您可能要在此處參考有關使用絕對/空布局的教程。
這是我編寫的用於更改另一個具有空布局(僅使用setBounds)的JPanel內的JPanel大小的示例。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.