我正在学习使用java.swing库。我正在尝试创建一个非常简单的计算器布局。我添加了addNumbers方法。我试图在计算器中显示按钮,我已经使用了loops.buttons没有出现我正在获得nullpointerexception。
import java.awt.*;
import javax.swing.*;
public class Calculator extends JFrame{
/**
* @param args
*/
//dEFINE WIDTH AND HEIGHT
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
//Values for buttons having numbers
private JButton[] numButton;
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator myCalculator = new Calculator();
}
public Calculator(){
setTitle("Simple Calculator");
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container Pane = getContentPane();
Pane.setLayout(new GridLayout(3,3));
//Add numbers to screen now
addNumbers(Pane);
}
//Function to add numbers on screen
public void addNumbers(Container P){
for(int i = 1; i <= 9; i++){
numButton[i] = new JButton(String.valueOf(i));
P.add(numButton[i]);
}
}
}
答案 0 :(得分:5)
您需要初始化数组:
private JButton[] numButton = new JButton[10];
这里的10允许你的数组中有10个空格。
答案 1 :(得分:0)
上面的解决方案可以工作并删除NullPointer,因为内存现已分配给numButton数组.... 这是一个工作代码片段,也包含(BODMAS)标志...... 唯一的区别是我将所有键标签都放入了ArrayList中 并且for循环现在可以在此ArrayList上运行以获取其标签 计算器... ArrayList可能不是一个好的集合。可能enum可能会更好但是 这是为了展示如何使其更加动态并添加按钮标签 或者新按钮会更容易...... 另请注意,您可以根据键标签的大小使GridSize动态化 array..gridSize = this.buttons.size()/ 4 ....
答案 2 :(得分:0)
import java.awt.Container;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Calculator extends JFrame{
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
List<String> buttons = new ArrayList<String>();
JButton[] numButton = null;
public static void main(String[] args) {
Calculator myCalculator = new Calculator();
}
public Calculator(){
setTitle("Simple Calculator");
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container Pane = getContentPane();
this.buttons.add("1");
this.buttons.add("2");
this.buttons.add("3");
this.buttons.add("4");
this.buttons.add("5");
this.buttons.add("6");
this.buttons.add("7");
this.buttons.add("8");
this.buttons.add("9");
this.buttons.add("0");
this.buttons.add("+");
this.buttons.add("=");
this.buttons.add("%");
this.buttons.add("#");
this.buttons.add("*");
this.buttons.add("/");
int gridSize = this.buttons.size() / 4;
Pane.setLayout(new GridLayout(gridSize,gridSize));
this.numButton = new JButton[this.buttons.size()];
//Add numbers to screen now
addNumbers(Pane);
}
//Function to add numbers on screen
public void addNumbers(Container P){
for(int i = 0; i < this.buttons.size(); i++){
numButton[i] = new JButton(this.buttons.get(i).toString());
P.add(numButton[i]);
}
}
}