第一学期计算机科学学生。我正在开展一个 self 激励的项目,该项目的灵感来自于之前的任务。
使用 swing 和 awt,我尝试创建一个 JFrame 并在其中进行绘制,但我无法使窗口正确缩放以适合我使用 pack() 添加的组件。
我已经注释掉了 setPreferredSize() 行,因为它什么也没做,这就是我感到困惑的地方。 MyCanvas 类是组件,对吧?在该组件内部,我正在绘制形状和线条。据我所知, setPreferredSize() 应该在组件中调用,而不是组件内部的方法。我已经在 NewGrid()、组件和 Paint() 方法内部尝试了 setPreferredSize(),但无论如何,窗口都会以以下两种方式之一显示:
586 x 593,在 NewGrid() 内使用 setPreferredSize():
在代码中的其他位置使用 setPreferredSize() :
import java.awt.*;
import javax.swing.*;
public class NewGrid extends JFrame {
private MyCanvas canvas = new MyCanvas();
private int size = 600;
public static void main(String[] args) {
NewGrid newGrid = new NewGrid();
}
public NewGrid() {
add(canvas);
pack();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
}
private class MyCanvas extends Canvas {
//setPreferredSize(new Dimension(600, 600)); // this line does nothing and I can't figure out why
@Override
public void paint(Graphics g) {
int number = 10;
int spacing = size / number;
g.setColor(Color.darkGray);
g.fillRect(0, 0, size, size); // creates a background square on which I can draw some grid lines
// grid line loop
for (int i = 0; i < number + 1; i++) {
int lineStart = i * spacing;
g.setColor(Color.green);
// Vertical lines
g.drawLine(lineStart, 0, lineStart, size);
// Horizontal lines
g.drawLine(0, lineStart, size, lineStart);
}
}
}
}
最佳答案
简短回答
//setPreferredSize(new Dimension(600, 600));
// this line does nothing and I can't figure out why
首先,代码无法编译。
该语句需要成为该类的构造函数的一部分。 Sp您需要使用上面的语句添加构造函数。
此外,pack()
和 setVisible(...)
语句应该是在所有组件都添加到框架并且框架的属性已设置。
请注意 setResizable(...) 方法在放置在 pack() 之前/之后时如何影响框架。
更好的答案
Using swing and awt,
不要混合使用 Swing 和 AWT 组件。
不要扩展 Canvas 。而是使用 JPanel
。
I can't get the window to scale properly to fit the components
Swing 中的自定义绘制是通过扩展 JPanel
来完成的,然后重写 paintComponent(...)
来进行自定义绘制。
最后,您在面板上实现 getPreferredSize()
,以便布局管理器和 pack() 方法可以完成其工作。
public class MyPanel extend JPanel
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent( g );
// add custom painting code
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(...);
}
}
阅读 Swing 教程中关于 Custom Painting 的部分了解更多信息和帮助您入门的工作示例。
关于java - 使用 pack() 将 JFrame 缩放到适当大小时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48814064/