gpt4 book ai didi

Java Swing 调整 BorderLayout.CENTER 大小

转载 作者:行者123 更新时间:2023-12-02 06:30:05 25 4
gpt4 key购买 nike

如标题所说,能否重新定义Java的BorderLayout.CENTER的高度和宽度?我计划使用 Graphics2D 绘制该区域,但我并不总是提前知道它应该有多大才能容纳所有内容。

绘制类(在我的主类中声明):

@SuppressWarnings("serial")
private class Draw extends JComponent {
public void paint(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

Shape drawLine = new Line2D.Float(0, 0, 500, 500);

g.setPaint(Color.BLACK);
g.draw(drawLine);
}
}

调用 Draw 的主构造函数:

public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 640, 480);
setJMenuBar(getMenuBar_1());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(getPanelControls(), BorderLayout.SOUTH);
contentPane.add(getPanelInfo(), BorderLayout.EAST);
contentPane.add(new Draw(), BorderLayout.CENTER);
}

我当前正在直接绘制到 BorderLayout.CENTER。我应该绘制到 JPanel 并使用它的 setPreferredSize() 方法吗?

最佳答案

As the title says, can I redefine the height and width of Java's BorderLayout.CENTER? I plan to use Graphics2D to draw to this area but I won't always know ahead of time how big it should be to fit everything in.

(仅回答主题)

  • 覆盖其 getPreferredSize

  • 那么任何大小调整都会适得其反,请在 JFrame.setVisible(true);

  • 之前调用 JFrame.pack();
  • 创建一个 JFrame 作为局部变量

编辑

<小时/>
  • 覆盖paintComponent()而不是paint()paintComponent()内的第一个代码行应该是super .paintComponent(),否则绘制累积

  • Shape drawLine = new Line2D.Float(0, 0, 500, 500); 应该是 getHeight/Weight() 而不是 500 , 500

关于Java Swing 调整 BorderLayout.CENTER 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20148022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com