The problem is:
new JCheckBox("Goes to 11");
Is never set to to your variable check
check = new JCheckBox("Goes to 11");
题
I am learning Java. I created a Program that has a text area and a checkbox. Every time I check or uncheck, I want it to write the checkbox's state on the text area. I learn about innerclasses and Action Events. The following code seems legit, but it is showing an error:
Exception in thread "main" java.lang.NullPointerException
at TextArea1.go(TextArea1.java:26)
at TextArea1.main(TextArea1.java:14)
I am not sure what I am doing wrong.
Line 14 is gui.go(); Line 26 is text = new JTextArea(10, 20);
Another question. I know I can get million results in google. But can you suggest a good tutorial to learn debugging in Eclipse.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextArea1
{
JTextArea text;
JCheckBox check;
public static void main (String[] args)
{
TextArea1 gui = new TextArea1();
gui.go();
}
public void go()
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
new JCheckBox("Goes to 11");
check.addItemListener(new CheckListener());
text = new JTextArea(10, 20);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.getContentPane().add(BorderLayout.SOUTH,check);
frame.setSize(350,300);
frame.setVisible(true);
}
class CheckListener implements ItemListener
{
public void itemStateChanged(ItemEvent ev)
{
String onOrOff = "off";
if (check.isSelected())
onOrOff = "on";
text.append("Check = " + onOrOff);
}
}
}
解决方案
The problem is:
new JCheckBox("Goes to 11");
Is never set to to your variable check
check = new JCheckBox("Goes to 11");
其他提示
Modified your code, you weren't initializing your checkbox
public class TextArea1 {
JTextArea text;
JCheckBox check;
public static void main(String[] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
check = new JCheckBox("Goes to 11");
check.addItemListener(new CheckListener());
text = new JTextArea(10, 20);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.SOUTH, check);
frame.setSize(350, 300);
frame.setVisible(true);
}
class CheckListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent ev) {
String onOrOff = "off";
if (check.isSelected())
onOrOff = "on";
text.append("\nCheck = " + onOrOff);
}
}
}