我正在尝试创建一个简单的GUI应用程序,当你输入一个整数,即“w”到文本字段时,它被放入for循环,循环运行“w”次。当它运行时,我想让它在每次循环运行时打印一个“X”。希望看到代码时更有意义。一些帮助将不胜感激。
提前致谢。
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame();// creating instance of JFrame
int w = 0;
JTextField textfield = new JTextField();
JTextArea textarea = new JTextArea(6, 37);
JButton bSquare = new JButton("Square");// creating instance of JButton
JButton bRATriangle = new JButton("Right Angle Triangle");
JButton bETriangle = new JButton("Equilateral Triangle");
bSquare.setBounds(0, 100, 200, 40);
bRATriangle.setBounds(200, 100, 200, 40);
bETriangle.setBounds(400, 100, 200, 40);
textarea.setBounds(0, 500, 600, 100);
textfield.setBounds(200, 200, 200, 80);
textfield.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
int w = Integer.parseInt(textfield.getText());
textarea.setText(String.valueOf(w));
} catch(NumberFormatException nfe){
textarea.setText("Error!");
}
}
});
bSquare.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int j = 0; j < w; j++) {
textarea.append("");
for(int i = 0; i < w; i++) {
textarea.append("X");
}
}
}
});
答案 0 :(得分:1)
我只会在bSquare
按钮的动作侦听器中执行所有逻辑。此外,您不需要使用int w = 0;
,因为它无法在动作侦听器之间正确共享。
示例强>:
bSquare.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// just use a new variable here
// default to 0 (if a NumberFormatException occurs)
int val = 0;
try
{
val = Integer.parseInt(textfield.getText());
textarea.setText(String.valueOf(val));
}
catch (NumberFormatException nfe)
{
textarea.setText("Error!");
}
for (int j = 0; j < val; j++)
{
textarea.append("");
for (int i = 0; i < val; i++)
{
textarea.append("X");
}
}
}
});