我用GUI创建了一个Java Calculator。我使用数组创建了按钮的JPanel,但我从一开始就注意到,当窗口出现时,按钮会在3-4秒后加载。我检查了一切,但找不到问题。这是代码:
主要
package main;
import ui.Calculator;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
calculator.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
计算器
package ui;
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame {
public Calculator() {
super("Calculator");
setSize(400, 400);
setLocation(400, 400);
setLayout(new BorderLayout());
Buttons buttons = new Buttons();
add(buttons);
}
}
按钮 这就是我认为的问题根源
package ui;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Creates a JPanel with the buttons that is going to be on the Window
*/
class Buttons extends JPanel{
private static JButton[] numbers = new JButton[10];
private static JButton bdot, bsum, bsubstract, bdivide, bmultiply, bequal;
Buttons() {
initializeButtons();
JButton[] buttonNumbers = {numbers[7], numbers[8], numbers[9], bdivide, numbers[4], numbers[5], numbers[6], bmultiply,
numbers[1], numbers[2], numbers[3], bsubstract, numbers[0], bdot, bsum, bequal};
setLayout(new GridLayout(4, 4));
int counter = 0;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
add(buttonNumbers[counter]);
counter ++;
}
}
}
/**
* Function that initialize all the buttons with their respective text
*/
private static void initializeButtons() {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = new JButton("" + i);
}
bdot = new JButton(".");
bsum = new JButton("+");
bsubstract = new JButton("-");
bdivide = new JButton("/");
bmultiply = new JButton("*");
bequal = new JButton("=");
}
}
注意:我知道还有其他方法可以做到这一点,但我找不到这种方法的问题,希望你能帮帮我,谢谢。