JPanel类型的数组循环如何添加JLabel标签
importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;importjavax.swin...
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.CardLayout;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.applet.Applet;
public class lll extends Applet implements ActionListener
{
JPanel shang=new JPanel();
JPanel xia=new JPanel();
JPanel []xianshi=new JPanel[10];
CardLayout shanglayout=new CardLayout();
public void init()
{
shang.setLayout(shanglayout);
for(int x=0;x<10;x++)
{
xianshi[x].add(new JLabel("我是第"+(x+1)+"个标签"));//就是这里老出问题
shang.add(""+x,xianshi[x]);
}
xia.setLayout(new CardLayout());
JButton jb1=new JButton("下一张");
JButton jb2=new JButton("前一张");
jb1.addActionListener(this);
jb2.addActionListener(this);
xia.add("1",jb1);xia.add("2",jb2);
JPanel quan=new JPanel();
quan.setLayout(new BorderLayout());
quan.add(shang,BorderLayout.CENTER);quan.add(xia,BorderLayout.SOUTH);
quan.setVisible(true);
add(quan);
setSize(500,500);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("下一张")) shanglayout.next(shang);
if(e.getActionCommand().equals("前一张")) shanglayout.previous(shang);
}
} 展开
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.CardLayout;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.applet.Applet;
public class lll extends Applet implements ActionListener
{
JPanel shang=new JPanel();
JPanel xia=new JPanel();
JPanel []xianshi=new JPanel[10];
CardLayout shanglayout=new CardLayout();
public void init()
{
shang.setLayout(shanglayout);
for(int x=0;x<10;x++)
{
xianshi[x].add(new JLabel("我是第"+(x+1)+"个标签"));//就是这里老出问题
shang.add(""+x,xianshi[x]);
}
xia.setLayout(new CardLayout());
JButton jb1=new JButton("下一张");
JButton jb2=new JButton("前一张");
jb1.addActionListener(this);
jb2.addActionListener(this);
xia.add("1",jb1);xia.add("2",jb2);
JPanel quan=new JPanel();
quan.setLayout(new BorderLayout());
quan.add(shang,BorderLayout.CENTER);quan.add(xia,BorderLayout.SOUTH);
quan.setVisible(true);
add(quan);
setSize(500,500);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("下一张")) shanglayout.next(shang);
if(e.getActionCommand().equals("前一张")) shanglayout.previous(shang);
}
} 展开
1个回答
展开全部
for ( int x = 0; x < 10; x++ )
{
if (null == xianshi[x])
{
xianshi[x] = new JPanel ();
}
xianshi[x].add (new JLabel ("我是第" + ( x + 1 ) + "个标签"));// 这里不出问题了
shang.add ("" + x, xianshi[x]);
}
追问
大侠风度偏偏,气宇轩昂,何不留个详细解释和大侠的个联系方法,好让小弟我再追加财富值
追答
空指针异常,你new了JPanel数组,但是里面的每个对象还没有new
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询