The Artima Developer Community
Sponsored Link

Java Answers Forum
String padding

6 replies on 1 page. Most recent reply: Jul 2, 2002 2:10 PM by Thomas SMETS

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 6 replies on 1 page
Richard

Posts: 1
Nickname: ricmel
Registered: Jun, 2002

String padding Posted: Jun 29, 2002 2:13 AM
Reply to this message Reply
Advertisement
I need to display various strings in a textarea.
How does one use string padding to get correct alignment of strings?


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: String padding Posted: Jun 29, 2002 12:26 PM
Reply to this message Reply
In a TextArea or JTextArea there are no methods to make a line of text centered or left or right justified.

So to get a desired affect you have to program it yourself to add lines with extra space or tabs to make it appear as deisred.

You would have to step up to a JTextPane to use styled text that can be easily programmed to align as desired. The following code uses some of the built in editor text actions.


/* DocumentEditor.java
* @author: Charles Bell
* @version: June 29, 2002

*
*/

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;
import javax.swing.text.*;


public class DocumentEditor extends JFrame implements ActionListener{

private StyledDocument document;
private JTextPane textPane;
private boolean debug = false;
private File currentFile;

public DocumentEditor(){
super("DocumentEditor");
document = new DefaultStyledDocument();
init();
}
public DocumentEditor(StyledDocument document){
super("DocumentEditor");
this.document = document;
init();
}

public static void main(String[] args){
DocumentEditor editor = new DocumentEditor();
}

public void init(){

addWindowListener(new FrameListener());

Action cutAction = new DefaultEditorKit.CutAction();
Action copyAction = new DefaultEditorKit.CopyAction();
Action pasteAction = new DefaultEditorKit.PasteAction();

Action boldAction = new StyledEditorKit.BoldAction();
Action underlineAction = new StyledEditorKit.UnderlineAction();
Action italicAction = new StyledEditorKit.ItalicAction();
Action insertAction = new StyledEditorKit.InsertContentAction();
Action insertBreakAction = new DefaultEditorKit.InsertBreakAction();
Action tabAction = new DefaultEditorKit.InsertTabAction();
Action leftAlignmentAction = new StyledEditorKit.AlignmentAction("Left",StyleConstants.ALIGN_LEFT);
Action centerAlignmentAction = new StyledEditorKit.AlignmentAction("Center",StyleConstants.ALIGN_CENTER);
Action rightAlignmentAction = new StyledEditorKit.AlignmentAction("Right",StyleConstants.ALIGN_RIGHT);

JMenuBar menuBar = new JMenuBar();
getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu formatMenu = new JMenu("Fomat");
JMenu helpMenu = new JMenu("Help");

menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(formatMenu);
menuBar.add(helpMenu);

JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem saveAsItem = new JMenuItem("Save As");
JMenuItem exitItem = new JMenuItem("Exit");

newItem.addActionListener(this);
openItem.addActionListener(this);
saveItem.addActionListener(this);
saveAsItem.addActionListener(this);
exitItem.addActionListener(this);

fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.add(exitItem);


JMenuItem cutItem = new JMenuItem(cutAction);
JMenuItem copyItem = new JMenuItem(copyAction);
JMenuItem pasteItem = new JMenuItem(pasteAction);
JMenuItem clearItem = new JMenuItem("Clear");
JMenuItem selectAllItem = new JMenuItem("Select All");

cutItem.setText("Cut");
copyItem.setText("Copy");
pasteItem.setText("Paste");

cutItem.setIcon(new ImageIcon("cut.gif"));
copyItem.setIcon(new ImageIcon("copy.gif"));
pasteItem.setIcon(new ImageIcon("paste.gif"));

clearItem.addActionListener(this);
selectAllItem.addActionListener(this);

editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.add(clearItem);
editMenu.add(selectAllItem);

JMenu fontTypeMenu = new JMenu("Font Type");
formatMenu.add(fontTypeMenu);

String[] fontTypes = {"SansSerif", "Serif", "Monospaced", "Dialog", "DialogInput"};
for (int i = 0; i < fontTypes.length;i++){
if (debug) System.out.println(fontTypes[i]);
JMenuItem nextTypeItem = new JMenuItem(fontTypes[i]);
nextTypeItem.setAction(new StyledEditorKit.FontFamilyAction(fontTypes[i], fontTypes[i]));
fontTypeMenu.add(nextTypeItem);
}

JMenu fontSizeMenu = new JMenu("Font Size");
formatMenu.add(fontSizeMenu);

int[] fontSizes = {6, 8,10,12,14, 16, 20,24, 32,36,48,72};
for (int i = 0; i < fontSizes.length;i++){
if (debug) System.out.println(fontSizes[i]);
JMenuItem nextSizeItem = new JMenuItem(String.valueOf(fontSizes[i]));
nextSizeItem.setAction(new StyledEditorKit.FontSizeAction(String.valueOf(fontSizes[i]), fontSizes[i]));
fontSizeMenu.add(nextSizeItem);
}

JMenuItem leftMenuItem = new JMenuItem(leftAlignmentAction);
JMenuItem centerMenuItem = new JMenuItem(centerAlignmentAction);
JMenuItem rightMenuItem = new JMenuItem(rightAlignmentAction);

formatMenu.add(leftMenuItem);
formatMenu.add(centerMenuItem);
formatMenu.add(rightMenuItem);

JMenuItem helpItem = new JMenuItem("Help");
helpItem.addActionListener(this);
helpMenu.add(helpItem);

JMenuItem shortcutsItem = new JMenuItem("Keyboard Shortcuts");
shortcutsItem.addActionListener(this);
helpMenu.add(shortcutsItem);


JPanel editorControlPanel = new JPanel();
editorControlPanel.setLayout(new FlowLayout());

/* JButtons */
JButton cutButton = new JButton(cutAction);
JButton copyButton = new JButton(copyAction);
JButton pasteButton = new JButton(pasteAction);

JButton boldButton = new JButton(boldAction);
JButton underlineButton = new JButton(underlineAction);
JButton italicButton = new JButton(italicAction);

//JButton insertButton = new JButton(insertAction);
//JButton insertBreakButton = new JButton(insertBreakAction);
//JButton tabButton = new JButton(tabAction);

cutButton.setText("Cut");
copyButton.setText("Copy");
pasteButton.setText("Paste");

boldButton.setText("Bold");
underlineButton.setText("Underline");
italicButton.setText("Italic");

//insertButton.setText("Insert");
//insertBreakButton.setText("Insert Break");
//tabButton.setText("Tab");

cutButton.setIcon(new ImageIcon("cut.gif"));
copyButton.setIcon(new ImageIcon("copy.gif"));
pasteButton.setIcon(new ImageIcon("paste.gif"));

boldButton.setIcon(new ImageIcon("bold.gif"));
underlineButton.setIcon(new ImageIcon("underline.gif"));
italicButton.setIcon(new ImageIcon("italic.gif"));

editorControlPanel.add(cutButton);
editorControlPanel.add(copyButton);
editorControlPanel.add(pasteButton);

editorControlPanel.add(boldButton);
editorControlPanel.add(underlineButton);
editorControlPanel.add(italicButton);

//editorControlPanel.add(insertButton);
//editorControlPanel.add(insertBreakButton);
//editorControlPanel.add(tabButton);


textPane = new JTextPane(document);
JScrollPane scrollPane = new JScrollPane(textPane);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension scrollPaneSize = new Dimension(5*screenSize.width/8,5*screenSize.height/8);
scrollPane.setPreferredSize(scrollPaneSize);

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(editorControlPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.SOUTH);
getContentPane().add(panel, BorderLayout.CENTER);

pack();
setLocationRelativeTo(null);
show();

}

public void actionPerformed(ActionEvent ae){
String actionCommand = ae.getActionCommand();
if (debug){
int modifier = ae.getModifiers();
long when = ae.getWhen();
String parameter = ae.paramString();
System.out.println("actionCommand: " + actionCommand);
System.out.println("modifier: " + modifier);
System.out.println("when: " + when);
System.out.println("parameter: " + parameter);
}
if (actionCommand.compareTo("New") == 0){
startNewDocument();
} else if (actionCommand.compareTo("Open") == 0){
openDocument();
} else if (actionCommand.compareTo("Save") == 0){
saveDocument();
} else if (actionCommand.compareTo("Save As") == 0){
saveDocumentAs();
} else if (actionCommand.compareTo("Exit") == 0){
exit();
} else if (actionCommand.compareTo("Clear") == 0){
clear();
} else if (actionCommand.compareTo("Select All") == 0){
selectAll();
} else if (actionCommand.compareTo("Help") == 0){
help();
} else if (actionCommand.compareTo("Keyboard Shortcuts") == 0){
showShortcuts();
}
}

public void startNewDocument(){
document = new DefaultStyledDocument();
textPane.setDocument(document);
}

public void openDocument(){
try{
File current = new File(".");
JFileChooser chooser = new JFileChooser(current);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int approval = chooser.showSaveDialog(this);
if (approval == JFileChooser.APPROVE_OPTION){
currentFile = chooser.getSelectedFile();
FileInputStream fin = new FileInputStream(currentFile);
ObjectInputStream istrm = new ObjectInputStream(fin);
Document doc = (Document) istrm.readObject();
textPane.setDocument(doc);
setTitle(currentFile.getName());
}
}catch(ClassNotFoundException cnfe){
System.err.println("ClassNotFoundException: " + cnfe.getMessage());
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}

}

public void saveDocument(){
if (currentFile != null){
try{
FileOutputStream fos = new FileOutputStream(currentFile);
ObjectOutput oos = new ObjectOutputStream(fos);
oos.writeObject(textPane.getDocument());
oos.flush();
fos.close();
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}else{
saveDocumentAs();
}
}

public void saveDocumentAs(){
try{
File current = new File(".");
JFileChooser chooser = new JFileChooser(current);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int approval = chooser.showSaveDialog(this);
if (approval == JFileChooser.APPROVE_OPTION){
currentFile = chooser.getSelectedFile();
setTitle(currentFile.getName());
FileOutputStream fos = new FileOutputStream(currentFile);
ObjectOutput oos = new ObjectOutputStream(fos);
oos.writeObject(textPane.getDocument());
oos.flush();
fos.close();
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}

public void exit(){
if (JOptionPane.showConfirmDialog(this,
"Are you sure you want to exit?") == JOptionPane.YES_OPTION) System.exit(0);
}

public void clear(){
startNewDocument();
}

public void selectAll(){
textPane.selectAll();
}

public void help(){
JOptionPane.showMessageDialog(this,"DocumentEditor.java\n" +
"Author: Charles Bell\n" +
"Version: June 29, 2002");
}

public void showShortcuts(){
String shortcuts = "Navigate in | Tab\n" +
"Navigate out | Ctrl+Tab\n" +
"Navigate out backwards | Shift+Ctrl+Tab\n" +
"Move up/down a line | Up/Down Arrown\n" +
"Move left/right a component or char | Left/Right Arrow\n" +
"Move up/down one vertical block | PgUp/PgDn\n" +
"Move to start/end of line | Home/End\n" +
"Move to previous/next word | Ctrl+Left/Right Arrow\n" +
"Move to start/end of data | Ctrl+Home/End\n" +
"Move left/right one block | Ctrl+PgUp/PgDn\n" +
"Select All | Ctrl+A\n" +
"Extend selection up one line | Shift+Up Arrow\n" +
"Extend selection down one line | Shift+Down Arrow\n" +
"Extend selection to beginning of line | Shift+Home\n" +
"Extend selection to end of line | Shift+End\n" +
"Extend selection to beginning of data | Ctrl+Shift+Home\n" +
"Extend selection to end of data | Ctrl+Shift+End\n" +
"Extend selection left | Shift+Right Arrow\n" +
"Extend selection right | Shift+Right Arrow\n" +
"Extend selection up one vertical block | Shift+PgUp\n" +
"Extend selection down one vertical block | Shift+PgDn\n" +
"Extend selection left one block | Ctrl+Shift+PgUp\n" +
"Extend selection right one block | Ctrl+Shift+PgDn\n" +
"Extend selection left one word | Ctrl+Shift+Left Arrow\n" +
"Extend selection right one word | Ctrl+Shift+Right Arrow\n";
JOptionPane.showMessageDialog(this,shortcuts);
}


class FrameListener extends WindowAdapter{
public void windowClosing(WindowEvent we){
exit();
}
}

}

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: String padding Posted: Jun 30, 2002 12:49 PM
Reply to this message Reply
If you want perfect placement of text and don't need all the other features of a JTextPane (like selection, copying, pasting, etc.), then you could use a simple JPanel and draw your text exactly where you want it.

Thomas SMETS

Posts: 307
Nickname: tsmets
Registered: Apr, 2002

Re: String padding Posted: Jul 1, 2002 3:48 PM
Reply to this message Reply
Charles,
Under what JDK does yr code compiles ?

I tried :
_ 1.1.8 + swing : Nope
_ 1.2 : Nope
_ 1.3 : Nope
_ 1.4 : Nope

:-(

With the 1.4 I have the least errors :
--------------------Configuration: 1.4 <Default>--------------------
Command : "C:\jdk\1.4\bin\javac.exe" -g -deprecation -classpath "C:\cygwin\data\classes\test\;C:\jdk\libs\log4j\log4j-1.2rc1.jar;C:\jdk\libs\ju nit\junitperf.jar;C:\jdk\libs\junit\junit.jar;C:\jdk\1.4\jre\lib\rt.jar;C:\jdk\1 .4\jre\lib\i18n.jar;C:\jdk\1.4\lib\dt.jar;C:\jdk\1.4\lib\tools.jar;C:\jdk\1.4\jr e\lib\ext\dnsns.jar;C:\jdk\1.4\jre\lib\ext\ldapsec.jar;C:\jdk\1.4\jre\lib\ext\su njce_provider.jar" -d "C:\cygwin\data\classes\test" C:\cygwin\data\test\gui\test\DocumentEditor.java
Directory : C:\cygwin\data\test\gui\test
C:\cygwin\data\test\gui\test\DocumentEditor.java:1 20: cannot resolve symbol
symbol : constructor JMenuItem (java.lang.String[])
location: class javax.swing.JMenuItem
JMenuItem nextTypeItem = new JMenuItem(fontTypes);
^
C:\cygwin\data\test\gui\test\DocumentEditor.java:121: cannot resolve symbol
symbol : constructor FontFamilyAction (java.lang.String[],java.lang.String[])
location: class javax.swing.text.StyledEditorKit.FontFamilyAction
nextTypeItem.setAction(new StyledEditorKit.FontFamilyAction(fontTypes, fontTypes));
^
C:\cygwin\data\test\gui\test\DocumentEditor.java:132: cannot resolve symbol
symbol : constructor FontSizeAction (java.lang.String,int[])
location: class javax.swing.text.StyledEditorKit.FontSizeAction
nextSizeItem.setAction(new StyledEditorKit.FontSizeAction(String.valueOf(fontSizes), fontSizes));
^
C:\cygwin\data\test\gui\test\DocumentEditor.java:224: cannot resolve symbol
symbol : method getWhen ()
location: class java.awt.event.ActionEvent
long when = ae.getWhen();
^
4 errors
Process completed.


Thomas SMETS,
SCJP2 - Brussels

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: String padding Posted: Jul 2, 2002 12:02 PM
Reply to this message Reply
You can get the source code at:

http://www.quantumhyperspace.com/SourceBank/DocumentEditor.java

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: String padding Posted: Jul 2, 2002 12:10 PM
Reply to this message Reply
Yes, it compiles fine with j2sdk1.4.0
There is nothing non-standard in the source.
I don't put source up unless it comiles and runs.


Now you can see the effects of not having all the proper source code indents, and new line characters when you cut, copy, and paste in this forum.


Please see the java source at:
http://www.quantumhyperspace.com/SourceBank/DocumentEditor.java

Sorry for the inconvenience.

Thomas SMETS

Posts: 307
Nickname: tsmets
Registered: Apr, 2002

Re: String padding Posted: Jul 2, 2002 2:10 PM
Reply to this message Reply
Charles,

It's because I knew (for long already) that your code always compiles that I was really amazed it did not !

After try to explain what my problem was I came accross a very simple Eclispe configuration problem !

Sorry for bothering you !

Thomas,

Thomas SMETS,
SCJP2 - Brussels

Flat View: This topic has 6 replies on 1 page
Topic: Help needed with script Previous Topic   Next Topic Topic: Java Mail

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use