我在JCreator Pro版本5.10中的JavaWorkspace下创建了一个名为“LabelTest”的项目
在项目文件夹中,我添加了文件LabelFrame.java,LabelTest.java和来自Deitel的图标bug1.png“java如何编程”第8版第14章图6和7
项目建设成功但不运行。 以下是错误:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at labeltest.LabelFrame.<init>(LabelFrame.java:30)
at labeltest.LabelTest.main(LabelTest.java:11)
和代码:
// Fig. 14.6: LabelFrame.java
// Demonstrating the JLabel class.
//package labeltest;
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.JFrame; // provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.SwingConstants; // common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images
public class LabelFrame extends JFrame
{
private JLabel label1; // JLabel with just text
private JLabel label2; // JLabel constructed with text and icon
private JLabel label3; // JLabel with added text and icon
// LabelFrame constructor adds JLabels to JFrame
public LabelFrame()
{
super( "Testing JLabel" );
setLayout( new FlowLayout() ); // set frame layout
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
add( label1 ); // add label1 to JFrame
// JLabel constructor with string, Icon and alignment arguments
Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
label2 = new JLabel( "Label with text and icon", bug,
SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
add( label2 ); // add label2 to JFrame
label3 = new JLabel(); // JLabel constructor no arguments
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug ); // add icon to JLabel
label3.setHorizontalTextPosition( SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
add( label3 ); // add label3 to JFrame
} // end LabelFrame constructor
} // end class LabelFrame
// Fig. 14.7: LabelTest.java
// Testing LabelFrame.
//package labeltest;
import javax.swing.JFrame;
public class LabelTest
{
public static void main( String[] args )
{
LabelFrame labelFrame = new LabelFrame(); // create LabelFrame
labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
labelFrame.setSize( 260, 180 ); // set frame size
labelFrame.setVisible( true ); // display frame
} // end main
} // end class LabelTest
答案 0 :(得分:0)
您的程序无法运行编译,因为它在此行遇到异常:
Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
该异常是无法找到名为bug1.png
的文件的结果。
确保使用正确的 路径名 和 文件名 。