2
我正在编写一个程序,通过JLabel数组和JTextfield的方式将十进制转换为二进制以供用户输入。我有一个Step按钮,它可以将文本框中的十进制数字和每次按下时显示的二进制数字相加。但是,当数字达到256时,它应该“绕回”到00000000,将1放在前面。我不知道如何在Listener中做到这一点,尤其是没有访问私有JLabel数组(因此为什么我不能只做一个“如果num等于256,然后数组将文本设置为0”语句)。我所有使用的是文本框中的十进制数和小数点到二进制方法。我已经试过:如何在数组中将二进制数字“换行”为0?
int i = Integer.parseInt(box.getText());
if(i == 256);
{
display.setValue(0); //setValue is method to convert dec. to binary
box.setText("" + i); //box is the JTextfield that decimal # is entered in
}
和
if(i == 256)
{
i = i - i;
display.setValue(i);
}
,但他们都没有工作,我的想法。我会很感激一些帮助。很抱歉,请提供冗长的解释并提前致谢!
public class Display11 extends JPanel
{
private JLabel[] output;
private int[] bits;
public Display11()
{
public void setValue(int num)//METHOD TO CONVERT DECIMAL TO BINARY
{
for(int x = 0; x < 8; x++) //reset display to 0
{
bits[x] = 0;
}
int index = 0; //increments in place of a for loop
while(num > 0)
{
int temp = num%2; //gives lowest bit
bits[bits.length - 1 - index] = temp; //set temp to end of array
index++;
num = num/2; //updates num
if(num == 0) //0 case
{
for(int x = 0; x < 8; x++)
{
output[x].setText("0");
}
}
}
for(int x = 0; x < bits.length; x++)
{
output[x].setText("" + bits[x]); //output is the JLabel array
} //bits is a temporary int array
//display the binary number in the JLabel
public class Panel11 extends JPanel
{
private JTextField box;
private JLabel label;
private Display11 display;
private JButton button2;
public Panel11()
{
private class Listener2 implements ActionListener //listener for the incrementing button
{
public void actionPerformed(ActionEvent e)
{
int i = Integer.parseInt(box.getText()); //increments decimal #
i++;
box.setText("" + i);
display.setValue(i); //converts incremented decimal # to binary
}
}