import java.awt.Color;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import java.util.Scanner;
public class BarGraph extends JPanel
{
private int n1, n2, n3, n4, n5;
BarGraph(int num1, int num2, int num3, int num4, int num5)
{
int n1 = num1;
int n2 = num2;
int n3 = num3;
int n4 = num4;
int n5 = num5;
}
public void paintComponent( Graphics g )
{
super.paintComponent(g);
g.drawRect(0, 100, 100, 10);
g.drawRect(0, 0, n1 * 10, 10);
g.drawRect(0,20, n2 * 10, 10);
g.drawRect(0,40, n3 * 10, 10);
g.drawRect(0,60, n4 * 10, 10);
g.drawRect(0,80, n5 * 10, 10);
System.out.print(n1);
}
}
BarGraphTest
package BarGraph;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author AJ
*/
public class BarGraphTest
{
public static void main( String[] args)
{
System.out.print("Enter 5 integers seperated by spaces:");
Scanner input = new Scanner(System.in);
int n1 = input.nextInt();
int n2 = input.nextInt();
int n3 = input.nextInt();
int n4 = input.nextInt();
int n5 = input.nextInt();
BarGraph panel = new BarGraph(n1, n2, n3, n4, n5);
JFrame application = new JFrame();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.add( panel );
application.setSize( 300, 300);
application.setVisible( true );
}
}
基本上尝试获得5个整数并绘制5个相应缩放的矩形。我的变量虽然是空的。我错过了什么吗?我System.out.printed了变量n1,但它没有任何内容。
答案 0 :(得分:2)
在BarGraph
的构造函数中,您已声明了局部变量并忽略了类变量,因此不会分配类变量。局部变量优先于类变量。删除int
以删除声明,类变量将得到正确解析。
更改
BarGraph(int num1, int num2, int num3, int num4, int num5)
{
int n1 = num1;
int n2 = num2;
int n3 = num3;
int n4 = num4;
int n5 = num5;
}
到
BarGraph(int num1, int num2, int num3, int num4, int num5)
{
n1 = num1;
n2 = num2;
n3 = num3;
n4 = num4;
n5 = num5;
}