java定义了两个JPanel面板,希望把两个面板放入JFrame容器中,出现cuo'w
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;classPanel1extendsJPanel{...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Panel1 extends JPanel{
JTextField text;
Panel1(){
text=new JTextField("请点击按钮");
add(text);
}
}
class Panel2 extends JPanel{
JButton button1,button2,button3;
Panel2(){
setLayout(new GridLayout(1,3));
button1=new JButton("red");
button2=new JButton("green");
button3=new JButton("blue");
add(button1);
add(button2);
add(button3);
}
}
class ButtonClick extends JFrame implements ActionListener{
Panel1 panel1;
Panel2 panel2;
ButtonClick(){
setSize(300,400);
Container conPane=getContentPane();
conPane.setLayout(new FlowLayout());
conPane.add(panel1);
conPane.add(panel2);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==panel2.button1){
panel1.text.setText("red");
}
else if(e.getSource()==panel2.button2){
panel1.text.setText("green");
}
else if(e.getSource()==panel2.button3){
panel1.text.setText("blue");
}
}
}
public class Question5_7 {
public static void main(String[] args) {
ButtonClick bc=new ButtonClick();
bc.setVisible(true);
}
}
eclipse编译时出错,显示如下:请问是何原因?
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at ButtonClick.<init>(Question5_7.java:30)
at Question5_7.main(Question5_7.java:49) 展开
import java.awt.event.*;
import javax.swing.*;
class Panel1 extends JPanel{
JTextField text;
Panel1(){
text=new JTextField("请点击按钮");
add(text);
}
}
class Panel2 extends JPanel{
JButton button1,button2,button3;
Panel2(){
setLayout(new GridLayout(1,3));
button1=new JButton("red");
button2=new JButton("green");
button3=new JButton("blue");
add(button1);
add(button2);
add(button3);
}
}
class ButtonClick extends JFrame implements ActionListener{
Panel1 panel1;
Panel2 panel2;
ButtonClick(){
setSize(300,400);
Container conPane=getContentPane();
conPane.setLayout(new FlowLayout());
conPane.add(panel1);
conPane.add(panel2);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==panel2.button1){
panel1.text.setText("red");
}
else if(e.getSource()==panel2.button2){
panel1.text.setText("green");
}
else if(e.getSource()==panel2.button3){
panel1.text.setText("blue");
}
}
}
public class Question5_7 {
public static void main(String[] args) {
ButtonClick bc=new ButtonClick();
bc.setVisible(true);
}
}
eclipse编译时出错,显示如下:请问是何原因?
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at ButtonClick.<init>(Question5_7.java:30)
at Question5_7.main(Question5_7.java:49) 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询