我正在处理我的代码以绘制用户输入的多条线,并且第一个端点以y坐标为中心,而第二个端点以高度/(线数)彼此分开用户输入)。我验证了我的代码,一切似乎工作得很好,除了JPanel没有按照它应该缩放的事实,对应于主框架的大小。有人可以给我一个建议吗?
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
}
}
答案 0 :(得分:3)
JPanel
的默认布局为FlowLayout
,它使用所包含组件的首选大小。相反,请使用GridLayout
。随着框架调整大小,它会增长和缩小。不是setSize()
,而是为您的小组提供preferred size的初始here。
答案 1 :(得分:0)
感谢您的反馈。我已经弄清楚如何做到这一点,因为我不应该使用Scanner类来询问用户输入。以下是我为此作业编辑的代码:
public class DrawPanel extends JPanel
{
private int userChoice;
public DrawPanel(int choice)
{
userChoice = choice;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);//call paintComponent to ensure the window displays correctly
int width = getWidth(); //total width
int height = getHeight();//total height
int endX = width; //starting position of second pt for x
int endY = height; //starting position of second pt for y
//increment from 0 to the user inputted stepSize to draw lines
for(int i = 1; i <= userChoice + 1; i++)
{
int verticalStep = height / userChoice; //separate y-coordinate second endpts apart
int midPoint = height / 2; //center the starting position in the y-axis of first endpoint
g.drawLine(0, midPoint, endX, endY); //draw lines
endY = endY - verticalStep; //move the second endpoints either up or down
}
}
}
public class DrawPanelTest
{
public static void main(String[] args)
{
int choice = Integer.parseInt(args [0]);
DrawPanel panel = new DrawPanel(choice);//create a panel that contains the lines
JFrame window = new JFrame(); //create a frame to hold the panel
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set frame to exit when closed
window.add(panel); //add panel to the frame
window.setSize(500, 500);//set size for the frame
window.setVisible(true); //display the frame
}