Anda di halaman 1dari 18

Inserting Formatted Data into Database Using JTextPane

Two Swing classes support styled text: JEditorPane and its subclass JTextPane.
The JEditorPane class is the foundation for Swing's styled text components and provides a
mechanism through which you can add support for custom text formats.

Editor Panes vs. Text Panes:


The differences between editor panes and text panes, and when to use which are following:

Editor panes, by default, know how to read, write, and edit plain, HTML, and RTF text.
Text panes inherit this capability but impose certain limitations.
As mentioned previously, a text pane requires its document to implement
the StyledDocument interface. The Swing text package provides a default
implementation of this interface, DefaultStyledDocument, which is the document that
text panes use by default. A text pane also requires that its editor kit be an instance of
a StyledEditorKit (or a subclass). Be aware that the read and write methods
for StyleEditorKit work with plain text.
Through their styled document and styled editor kit, text panes provide support for
named styles and logical styles. The JTextPane class itself contains many methods for
working with styles that simply call methods in its document or editor kit.
Through the API provided in the JTextPane class, you can embed images and
components in a text pane. You can embed images in an editor pane, too, but only by
including the images in an HTML or RTF file.
A text pane insists that its document implement
the StyledDocument
interface. HTMLDocument and RTFDocument are both StyledDocuments so HTML and
RTF work as expected within a text pane. If you load a text pane with plain text though,
the text pane's document is not a PlainDocumentas you might expect, but
a DefaultStyledDocument.
To support a custom text format, implement an editor kit that can read, write, and edit
text of that format. Then call theregisterEditorKitForContentType method to register
your kit with the JEditorPane class. By registering an editor kit in this way, all editor
panes and text panes in your program will be able to read, write, and edit the new
format. However, if the new editor kit is not a StyledEditorKit, text panes will not
support the new format.

Required Libraries:

ojdbc6.jar

Creating a Java Application


1.

File --> New Project...

2. Select Java from Categories and Java Application from Projects. Then Next.
3. Give the name of the application and click Finish.
4. Add required libraries .
5. Main Class
package jdbcstroedprocedures;

/**
*
* @author faisalijaz
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import static jdbcstroedprocedures.App.conn;
import static jdbcstroedprocedures.App.makeList;

public class Main extends JTextPane {

static String storedText;


static String Insertquery;
final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
final String DB_URL = "jdbc:oracle:thin:@192.192.9.205:1521:legacy";
static Connection conn = null;
static PreparedStatement stmt = null;

static ResultSet rs2;


static String rtfText;
static String SelectQuery;
static String retrievedText;
static InputStream fi;
private static final Integer[] ITEMS = {9, 10, 11, 12, 14, 16, 18, 20, 24,
32};
private static StyledDocument doc = new DefaultStyledDocument();
private static StyledEditorKit styledEditorKit = new StyledEditorKit();

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {

public void run() {


JFrame frame = new JFrame("My HTML Editor");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);
frame.setLayout(new BorderLayout());

JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


JPanel buttonsSecondPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
HTMLDocument document = new HTMLDocument();

final JTextPane htmlEditorPane = new JTextPane(document);


final JTextPane textPane_1 = new JTextPane();
JScrollPane scroll2 = new JScrollPane(textPane_1);
JScrollPane scroll1 = new JScrollPane(htmlEditorPane);
JPanel panel = new JPanel(new GridLayout(1, 2));

panel.add(scroll1);
panel.add(scroll2);
frame.getContentPane().add(panel, BorderLayout.CENTER);
Action bold = new StyledEditorKit.BoldAction();
Action italic = new StyledEditorKit.ItalicAction();
Action underline = new StyledEditorKit.UnderlineAction();
Action highlight = new StyledEditorKit.ForegroundAction(null, Color.red);
JButton boldButton = new JButton(bold);
boldButton.setText("Bold");
buttonsPanel.add(boldButton);

JButton italicButton = new JButton(italic);


italicButton.setText("Italic");
buttonsPanel.add(italicButton);

JButton underlineButton = new JButton(underline);


underlineButton.setText("Underline");

buttonsPanel.add(underlineButton);
JButton highlightButton = new JButton(highlight);
highlightButton.setText("Highlight");
buttonsPanel.add(highlightButton);

JButton saveButton = new JButton("save");


// underlineButton.setText("Underline");
//

buttonsSecondPanel.add(saveButton);

saveButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


Document document = htmlEditorPane.getStyledDocument();
EditorKit kit = htmlEditorPane.getEditorKit();
try {
kit.write(new FileOutputStream(new File("htmlfile.html")), document, 0, document.getLength());
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadLocationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

}
});
JButton loadButton = new JButton("load");
// buttonsSecondPanel.add(loadButton);
loadButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


try {
EditorKit kit = textPane_1.getEditorKit();
Document doc = kit.createDefaultDocument();
kit.read(new FileInputStream(new File("htmlfile.html")), doc, 0);
textPane_1.setDocument(doc);
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadLocationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});

JButton readintoDatabaseButton = new JButton("ReadfromDatabase");

readintoDatabaseButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


try {
EditorKit kit = textPane_1.getEditorKit();
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.192.9.205:1521:legacy", "awais",
"12345678");
System.out.println("connection successfull");
SelectQuery = "SELECT * FROM awais.clobpractice";
stmt = conn.prepareStatement(SelectQuery);
rs2 = stmt.executeQuery();
while (rs2.next()) {
if (rs2.getInt("id") == 67) {
retrievedText = rs2.getString("name");
fi = new ByteArrayInputStream(retrievedText.getBytes());
kit.read(fi, textPane_1.getDocument(), 0);

}
}

// System.out.println("retrieve text is "+retrievedText);


} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

} catch (IOException ex) {


Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadLocationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

});

buttonsPanel.add(readintoDatabaseButton);

JButton writeButton = new JButton("write");


// buttonsSecondPanel.add(writeButton);

writeButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


try {
writeDataIntoDb();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {

Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);


}
}
});
JButton saveintoDatabaseButton = new JButton("SavetoDatabase");
saveintoDatabaseButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


try {
ByteArrayOutputStream str = new ByteArrayOutputStream();
Document document = htmlEditorPane.getStyledDocument();
EditorKit kit = htmlEditorPane.getEditorKit();

kit.write(str, htmlEditorPane.getDocument(), 0, htmlEditorPane.getDocument().getLength());


storedText = str.toString();
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.192.9.205:1521:legacy", "awais",
"12345678");
System.out.println("connection successfull");
Insertquery = "INSERT INTO awais.clobpractice (id,name) VALUES (74,'" + storedText + "')";
stmt = conn.prepareStatement(Insertquery);

int inserted = stmt.executeUpdate();


JOptionPane.showMessageDialog(htmlEditorPane, "File successfully inserted at \n awais.clobpractice at
id=67");

} catch (Exception ex) {


Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
buttonsPanel.add(saveintoDatabaseButton);

final JComboBox<Integer> fontBox = new JComboBox<Integer>(ITEMS);


fontBox.setPreferredSize(new Dimension(100, 20));
htmlEditorPane.setDocument(doc);
htmlEditorPane.setEditorKit(styledEditorKit);

Document doc = htmlEditorPane.getDocument();


fontBox.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

int size = (Integer) fontBox.getSelectedItem();


Action fontAction = new StyledEditorKit.FontSizeAction(String
.valueOf(size), size);
fontAction.actionPerformed(e);

}
});

buttonsPanel.add(fontBox);

HTMLEditorKit.InsertHTMLTextAction bulletAction = new HTMLEditorKit.InsertHTMLTextAction("Bullet",


"<ul><li> </li></ul>", HTML.Tag.BODY, HTML.Tag.UL);
final JButton bulletButton = new JButton(bulletAction);
bulletButton.setText("Bullet");
buttonsPanel.add(bulletButton);

JButton printButton = new JButton("Print to Console");


printButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


System.out.println(htmlEditorPane.getText());
}
});

buttonsPanel.add(printButton);

htmlEditorPane.setContentType("text/html");
textPane_1.setContentType("text/html");

HTMLEditorKit editorKit = new HTMLEditorKit();


htmlEditorPane.setEditorKit(editorKit);
textPane_1.setEditorKit(editorKit);

frame.add(buttonsPanel, BorderLayout.NORTH);
frame.add(buttonsSecondPanel, BorderLayout.SOUTH);

// frame.add(new JScrollPane(htmlEditorPane), BorderLayout.CENTER);


// frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public static void writeDataIntoDb() throws SQLException, IOException {


Connection myConn = null;
PreparedStatement myStmt = null;

FileReader input = null;

try {
// 1. Get a connection to database

myConn = DriverManager.getConnection(
"jdbc:oracle:thin:@192.192.9.205:1521:legacy", "awais", "12345678");

// 2. Prepare statement
String sql = "update clobpractice set info=? where id=67";
// String query ="INSERT INTO employees (id,info) VALUES (3,'" + p.getText().toString() + "')";
myStmt = myConn.prepareStatement(sql);

// 3. Set parameter for file name


File theFile = new File("D:\\faisalWork\\mysqljdbc\\htmlfile.html");
input = new FileReader(theFile);
myStmt.setCharacterStream(1, input);

System.out.println("Reading input file: " + theFile.getAbsolutePath());

// 4. Execute statement
System.out.println("\nStoring resume in database: " + theFile);
System.out.println(sql);

myStmt.executeUpdate();

System.out.println("\nCompleted successfully!");
//

else{

//

JOptionPane.showMessageDialog(null, "File already exist");


//

} catch (Exception exc) {


exc.printStackTrace();
} finally {
if (input != null) {
input.close();
}

//

close(myConn, myStmt);
}
}

6. Run it

7. For Inserting formatted data into database the SaveToDatabase button reads the formatted
data from textpane that is on left side and insert it into database table(clob column) using
following command:
INSERT INTO awais.clobpractice (id,info) VALUES (74,'" + storedText + "')
Where storedText is the string that we get from textpane.

8. For reading formatted data from database that we just inserted using savetodatabase button
we will be using ReadFromDatabase button. By using this button we will get the formatted data
from database table(clobpratice) on the right sided textpane.

Anda mungkin juga menyukai