當我輸入所有的值,然後點擊生成,它的工作, ,但它不工作時,我再試一次。我的java程序只運行一次,然後停止
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class colRand {
static JPanel[][] square;
static JFrame colRand = new JFrame();
static JPanel settings = new JPanel();
static JPanel panel = new JPanel();
public static void main(String[] args) {
colRand.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colRand.setLocationRelativeTo(null);
colRand.setTitle("Color Randomizer");
JTextArea dim = new JTextArea("Grid Dimensions");
dim.setEditable(false);
JTextField width = new JTextField("Width");
JTextField height = new JTextField("Height");
JCheckBox reds = new JCheckBox("reds");
JCheckBox greens = new JCheckBox("greens");
JCheckBox blues = new JCheckBox("blues");
JButton generate = new JButton("Generate!");
settings.add(dim);
settings.add(width);
settings.add(height);
settings.add(reds);
settings.add(greens);
settings.add(blues);
settings.add(generate);
settings.setVisible(true);
generate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int w = Integer.parseInt(width.getText());
int h = Integer.parseInt(height.getText());
boolean R = reds.isSelected();
boolean G = greens.isSelected();
boolean B = blues.isSelected();
square = new JPanel[w][h];
for(int i = 1; i < Integer.parseInt(width.getText()); i++) {
for(int j = 1; j < Integer.parseInt(height.getText()); j++) {
square[i][j] = new JPanel();
square[i][j].setBackground(Color.black);
panel.add(square[i][j]);
square[i][j].setVisible(true);
}
}
paint(w, h, R, G, B);
colRand.setSize(w * 10, h * 10);
}
});
panel.setBackground(Color.black);
colRand.add(panel);
colRand.add(settings, BorderLayout.SOUTH);
colRand.pack();
colRand.setVisible(true);
}
public static void paint(int w, int h, boolean reds, boolean greens, boolean blues) {
for(int i = 1; i < w; i++) {
for(int j = 1; j < h; j++) {
square[i][j].setBackground(randColor(reds, greens, blues));
}
}
}
public static Color randColor(boolean reds, boolean greens, boolean blues) {
int R, G, B;
R = (int)(Math.random() * 255);
G = (int)(Math.random() * 255);
B = (int)(Math.random() * 255);
if(reds == false) {
R = 0;
}
if(greens == false) {
G = 0;
}
if(blues == false) {
B = 0;
}
return new Color(R, G, B);
}
}
請幫助我,我已經很長一段時間struggeling。
發佈堆棧跟蹤或您遇到的錯誤 –
「但是當我再次嘗試時它不起作用」您是什麼意思? 「再試一次」的確切步驟是什麼?另外,會發生什麼? –
小方評論:你應該使用變量'w'和'h',而不是在循環中調用'parseInt()'。 –