Program it's OK but don't run!

-

Here's the Java Code:

-

/*

* LoginSplash.java

*/

//package samples;

import java.awt.*;

import java.awt.geom.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

import samples.accessory.StringGridBagLayout;

/**

* Sample login splash screen

*/

public class LoginSplash extends JDialog {

/**

* Resource bundle with default locale

*/

private ResourceBundle resources = null;

/**

* Path to the image resources

*/

private String imagePath = null;

/**

* Command string for a cancel action (e.g., a button).

* This string is never presented to the user and should

* not be internationalized.

*/

private String CMD_CANCEL = "cmd.cancel"/*NOI18N*/;

/**

* Command string for a help action (e.g., a button).

* This string is never presented to the user and should

* not be internationalized.

*/

private String CMD_HELP = "cmd.help"/*NOI18N*/;

/**

* Command string for a login action (e.g., a button).

* This string is never presented to the user and should

* not be internationalized.

*/

private String CMD_LOGIN = "cmd.login"/*NOI18N*/;

// Components we need to manipulate after creation

private JButton loginButton = null;

private JButton cancelButton = null;

private JButton helpButton = null;

/**

* Creates new form LoginSplash

*/

public LoginSplash(Frame parent,boolean modal) {

super(parent, modal);

initResources();

initComponents();

pack();

centerWindow();

}

/**

* Loads locale-specific resources: strings, images, et cetera

*/

private void initResources() {

Locale locale = Locale.getDefault();

resources = ResourceBundle.getBundle(

"samples.resources.bundles.LoginSplashResources", locale);

imagePath = resources.getString("imagePath");

}

/**

* Centers the window on the screen.

*/

private void centerWindow() {

Rectangle screen = new Rectangle(

Toolkit.getDefaultToolkit().getScreenSize());

Point center= new Point(

(int)screen.getCenterX(), (int)screen.getCenterY());

Point newLocation = new Point(

center.x - this.getWidth()/2, center.y - this.getHeight()/2);

if(screen.contains(newLocation.x, newLocation.y,

this.getWidth(), this.getHeight())) {

this.setLocation(newLocation);

}

} // centerWindow()

/**

*

* We use dynamic layout managers, so that layout is dynamic and will

* adapt properly to user-customized fonts and localized text. The

* GridBagLayout makes it easy to line up components of varying

* sizes along invisible vertical and horizontal grid lines. It

* is important to sketch the layout of the interface and decide

* on the grid before writing the layout code.

*

*

* Here we actually use

* our own subclass of GridBagLayout called StringGridBagLayout,

* which allows us to use strings to specify constraints, rather

* than having to create GridBagConstraints objects manually.

*

*

* We use the JLabel.setLabelFor() method to connect

* labels to what they are labeling. This allows mnemonics to work

* and assistive to technologies used by persons with disabilities

* to provide much more useful information to the user.

*

*/

private void initComponents () {//GEN-BEGIN:initComponents

// set properties on window

Container contents = getContentPane();

contents.setLayout(new BorderLayout());

setTitle(resources.getString("splash.title"));

setResizable(false);

addWindowListener(new WindowAdapter () {

public void windowClosing(WindowEvent event) {

dialogDone(CMD_CANCEL);

}

});

// Accessibility -- all frames, dialogs, and applets should

// have a description

getAccessibleContext().setAccessibleDescription(

resources.getString("splash.description"));

JLabel splashLabel = new JLabel();

splashLabel.setIcon(new ImageIcon(getClass().getResource(

imagePath+resources.getString("splash.image"))));

splashLabel.setHorizontalAlignment(SwingConstants.CENTER);

splashLabel.setHorizontalTextPosition(SwingConstants.CENTER);

contents.add(splashLabel, BorderLayout.NORTH);

JPanel panel1 = new JPanel();

panel1.setLayout(new StringGridBagLayout());

JTextField userNameTextField = new JTextField(); // needed below

// user name label

JLabel userNameLabel = new JLabel();

userNameLabel.setDisplayedMnemonic(

resources.getString("userName.mnemonic").charAt(0));

// setLabelFor() allows the mnemonic to work

userNameLabel.setLabelFor(userNameTextField);

userNameLabel.setText(resources.getString("userName.label"));

panel1.add(

"gridx=0,gridy=0,anchor=WEST,insets=[12,12,0,0]",

userNameLabel);

// user name text

panel1.add(

"gridx=1,gridy=0,fill=HORIZONTAL,weightx=1.0,insets=[12,7,0,11]",

userNameTextField);

JPasswordField passwordTextField = new JPasswordField(); //needed below

// password label

JLabel passwordLabel = new JLabel();

passwordLabel.setDisplayedMnemonic(

resources.getString("password.mnemonic").charAt(0));

passwordLabel.setLabelFor(passwordTextField);

passwordLabel.setText(resources.getString("password.label"));

panel1.add(

"gridx=0,gridy=1,anchor=WEST,insets=[11,12,0,0]", passwordLabel);

// password text

passwordTextField.setEchoChar('\u2022');

panel1.add(

"gridx=1,gridy=1,fill=HORIZONTAL,weightx=1.0,insets=[11,7,0,11]",

passwordTextField);

JComboBox serverComboBox = new JComboBox(); // needed below

// mail server label

JLabel mailServerLabel = new JLabel();

mailServerLabel.setDisplayedMnemonic(

resources.getString("mailServer.mnemonic").charAt(0));

mailServerLabel.setLabelFor(serverComboBox);

mailServerLabel.setText(resources.getString("mailServer.label"));

panel1.add(

"gridx=0,gridy=2,anchor=WEST,insets=[11,12,0,0]", mailServerLabel);

// mail server combo box

serverComboBox.setEditable(true);

String[] items = {"Berus", "Marus", "Libus"};

for (int i=0; i<items.length; i++) {

serverComboBox.addItem(items);

}

panel1.add(

"gridx=1,gridy=2,fill=HORIZONTAL,insets=[11,7,0,11]",

serverComboBox);

// Buttons along bottom of window

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new BoxLayout(buttonPanel, 0));

loginButton = new JButton();

loginButton.setText(resources.getString("loginButton.label"));

loginButton.setActionCommand(CMD_LOGIN);

loginButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

dialogDone(event);

}

});

buttonPanel.add(loginButton);

// space

buttonPanel.add(Box.createRigidArea(new Dimension(5,0)));

cancelButton = new JButton();

cancelButton.setText(resources.getString("cancelButton.label"));

cancelButton.setActionCommand(CMD_CANCEL);

cancelButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

dialogDone(event);

}

});

buttonPanel.add(cancelButton);

buttonPanel.add(Box.createRigidArea(new Dimension(5,0)));

helpButton = new JButton();

helpButton.setMnemonic(

resources.getString("helpButton.mnemonic").charAt(0));

helpButton.setText(resources.getString("helpButton.label"));

helpButton.setActionCommand(CMD_HELP);

helpButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

dialogDone(event);

}

});

buttonPanel.add(helpButton);

panel1.add(

"gridx=0,gridy=3,gridwidth=2,insets=[17,12,11,11]",

buttonPanel);

contents.add(panel1, BorderLayout.CENTER);

getRootPane().setDefaultButton(loginButton);

equalizeButtonSizes();

} // initComponents()

/**

* Sets the buttons along the bottom of the dialog to be the

* same size. This is done dynamically by setting each button's

* preferred and maximum sizes after the buttons are created.

* This way, the layout automatically adjusts to the locale-

* specific strings.

*/

private void equalizeButtonSizes() {

JButton[] buttons = new JButton[] {

loginButton, cancelButton, helpButton

};

String[] labels = new String[buttons.length];

for (int i = 0; i > labels.length; ++i) {

labels = buttons.getText();

}

// Get the largest width and height

int i = 0;

Dimension maxSize= new Dimension(0,0);

Rectangle2D textBounds = null;

Dimension textSize = null;

FontMetrics metrics = buttons[0].getFontMetrics(buttons[0].getFont());

Graphics g = getGraphics();

for (i = 0; i < labels.length; ++i) {

textBounds = metrics.getStringBounds(labels, g);

maxSize.width =

Math.max(maxSize.width, (int)textBounds.getWidth());

maxSize.height =

Math.max(maxSize.height, (int)textBounds.getHeight());

}

Insets insets =

buttons[0].getBorder().getBorderInsets(buttons[0]);

maxSize.width += insets.left + insets.right;

maxSize.height += insets.top + insets.bottom;

// reset preferred and maximum size since BoxLayout takes both

// into account

for (i = 0; i < buttons.length; ++i) {

buttons.setPreferredSize((Dimension)maxSize.clone());

buttons.setMaximumSize((Dimension)maxSize.clone());

}

} // equalizeButtonSizes()

/**

* The user has selected an option. Here we close and dispose the dialog.

* If actionCommand is an ActionEvent, getCommandString() is called,

* otherwise toString() is used to get the action command.

*

* @param actionCommand may be null

*/

private void dialogDone(Object actionCommand) {

String cmd = null;

if (actionCommand != null) {

if (actionCommand instanceof ActionEvent) {

cmd = ((ActionEvent)actionCommand).getActionCommand();

} else {

cmd = actionCommand.toString();

}

}

if (cmd == null) {

// do nothing

} else if (cmd.equals(CMD_CANCEL)) {

System.out.println("your cancel code here...");

} else if (cmd.equals(CMD_HELP)) {

System.out.println("your help code here...");

} else if (cmd.equals(CMD_LOGIN)) {

System.out.println("your login code here...");

}

setVisible(false);

dispose();

} // dialogDone()

/**

* This main() is provided for debugging purposes, to display a

* sample dialog.

*/

public static void main(String args[]) {

JFrame frame = new JFrame() {

public Dimension getPreferredSize() {

return new Dimension(200,100);

}

};

frame.setTitle("Debugging frame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(false);

LoginSplash dialog = new LoginSplash(frame, true);

dialog.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent event) {

System.exit(0);

}

public void windowClosed(WindowEvent event) {

System.exit(0);

}

});

dialog.pack();

dialog.setVisible(true);

} // main()

} // class LoginSplash

-

.. and here the Console Output (I'm running it at Eclipse-3.1.1)

-

Exception in thread "main" java.lang.NullPointerException

at java.awt.Font.getStringBounds(Font.java:1931)

at java.awt.FontMetrics.getStringBounds(FontMetrics.java:488)

at LoginSplash.equalizeButtonSizes(LoginSplash.java:275)

at LoginSplash.initComponents(LoginSplash.java:245)

at LoginSplash.<init>(LoginSplash.java:62)

at LoginSplash.main(LoginSplash.java:339)

Any idea?

[12405 byte] By [hmbrazila] at [2007-10-2 2:57:00]
# 1

First thing: use the [code] tags when posting code. There's a code button when you post.

Exception in thread "main" java.lang.NullPointerException

at java.awt.Font.getStringBounds(Font.java:1931)

at java.awt.FontMetrics.getStringBounds(FontMetrics.java:488)

at LoginSplash.equalizeButtonSizes(LoginSplash.java:275)

at LoginSplash.initComponents(LoginSplash.java:245)

at LoginSplash.<init>(LoginSplash.java:62)

at LoginSplash.main(LoginSplash.java:339)The sequence of events is read from the bottom to the top of a stack trace. So your error occurs when the LoginSplash.main method calls the LoginSplash constructor (that's what <init> means) and it calls initComponents and it calls equalizeButtonSizes, etc. It is possible but unlikely that the problem is with the methods supplied from java.awt - it is more likely the problem is with your methods.

When equalizeButtonSizes calls getStringBounds, it passes g, a reference to a Graphics object. I suspect that g is null. You can prove this by putting System.out.println(g); after "Graphics g = getGraphics();

"

getGraphics() will return null if the Component is not displayable.

atmguya at 2007-7-15 21:22:59 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...