【发布时间】:2015-09-24 22:09:17
【问题描述】:
我对编程很陌生,我决定介绍一下 java 类。我有一个任务,我必须使用 for 循环创建一堵墙,该循环根据用户输入改变墙的高度。我想我的大部分代码都是正确的,但我似乎无法将用户输入与 for 循环连接起来。任何帮助将不胜感激。
//Package List
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
public class Wall extends JApplet implements ActionListener{
//Component declaration
JLabel directions;
JTextField input = new JTextField( 10 );
private JButton go;
//Variable declaration
int userinput;
//Method declaration
public void init()
{
getContentPane().setBackground(new Color (128, 128, 128));//Changes backround of JApplet to black
//Set JButton and JLabel
setLayout (new FlowLayout( ));
directions = new JLabel("Enter in any number between 1 and 20 and then press Enter on your keyboard.");
go = new JButton( "Go!" );
go.setBackground( Color.GREEN );
go.setFocusPainted( false );
go.addActionListener( this );
add (directions );
add (input);
add( go );
}
public void actionPerformed( ActionEvent ae )
{
String text = input.getText();
userinput = Integer.parseInt( text );
repaint();
}
//Method declaration
public void paint(Graphics g)
{
super.paint(g);
int startX = 50;
int startY = 650;
int width = 50;
int height = 20;
int spacing = 2;
int xOffset = 0;
for (int row = 0; row < userinput; row++) {
int y = startY + (row * ( height + spacing));
if ( row % 2 == 0) {
xOffset = width / 2;
} else {
xOffset = 0;
}
for (int col = 0; col < 8; col++) {
int x = xOffset + (startX + (col * (width + spacing)));
System.out.println(x + "x" + y);
g.setColor( Color.RED );
g.fillRect( x, y, width, height);
}
}
}
}
【问题讨论】:
-
您的代码有效,但您的
y偏移量太大
标签: java swing for-loop repaint