Java Reference
In-Depth Information
storyPanel.add(story, BorderLayout.CENTER);
JLabel storyLabel = new JLabel("Enter your story here:");
storyPanel.add(storyLabel, BorderLayout.NORTH);
add(storyPanel);
JPanel buttonPanel = new JPanel( );
buttonPanel.setLayout( new FlowLayout( ));
buttonPanel.setBackground(Color.PINK);
JButton actionButton = new JButton("Click me");
actionButton.addActionListener(this);
buttonPanel.add(actionButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("Click me"))
{
int lineCount = getLineCount();
story.setText("Your story is "
+ lineCount + " lines long.");
}
else if (actionCommand.equals("Clear"))
story.setText("");
else
story.setText("Unexpected error.");
}
private int getLineCount()
{
String storyString = story.getText();
int count = 0;
for ( int i = 0; i < storyString.length(); i++)
if (storyString.charAt(i) == '\n')
count++;
return count + 1; //The last line has no '\n'.
}
}
Search WWH ::




Custom Search