调整主框架大小时,JPanel窗口无法缩放 [英] JPanel Window not scaling when resize the main frame
问题描述
我正在编写代码以绘制用户输入的多条线,并且第一个端点以y坐标为中心,而第二个端点彼此分开高度/(行数)用户输入).我验证了我的代码,除了JPanel不能按比例缩放(与主机框架的大小相对应)外,其他一切似乎都正常运行.谁能给我个建议吗?
I was working on my code to draw a number of lines that the user inputted and the first end-point is centered at the y-coordinate while the second end-points are apart from each other by height/(number of lines the user entered). I verified my code and everything seems to be working fine except the fact that the JPanel does not scale as it should, corresponding to the size of the main frame. Can anyone please give me an advice?
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Scanner;
public class DrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
Scanner input = new Scanner(System.in); //create object input from Scanner class
System.out.println("Enter number of lines + 1 to draw: "); //ask for user input
int stepSize = input.nextInt(); //initialize stepSize to take user input
int endX = width; //starting position of second pt for x
int endY = height; //starting position of second pt for y
for(int i = 0; i < stepSize + 1; i++)
{
int verticalStep = height / stepSize; //separate y-coordinate second endpts apart
int midPoint = height / 2;
g.drawLine(0, midPoint, endX, endY);
endY = endY - verticalStep;
}
}
}
import javax.swing.JFrame;
public class DrawPanelTest
{
public static void main(String[] args)
{
DrawPanel panel = new DrawPanel();
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(panel);
window.setSize(500, 500); //set size of the application
window.setVisible(true); //display the application
}
}
推荐答案
JPanel
的默认布局为FlowLayout
,它使用了所包含组件的首选大小.而是,例如,使用GridLayout
.调整框架大小时,它会增长和收缩.代替setSize()
,为面板设置一个初始的首选大小,如此处.
The default layout of JPanel
is FlowLayout
, which uses the preferred size of the enclosed components. Instead, use GridLayout
, for example. It will grow and shrink as the frame is resized. Instead of setSize()
, give your panel an initial preferred size as shown here.
这篇关于调整主框架大小时,JPanel窗口无法缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!