mirror jtextarea to jtextpane - jtextarea

I was trying to mirror JTextArea to JTextPane.
For JTextArea to JTextArea
JTextArea a = new JTextArea ();
JTextArea b = new JTextArea ();
b.setDocument(a.getDocument());
The reason I want to use JTextPane is whenever I type html tags in JTextArea it will be automatically formatted in JTextPane like a webpage.
When I replaced it with JTextPane , it gives me
Model must be StyledDocument
so I've tried adding StyledDocument.
StyledDocument doc = (StyledDocument) a.getDocument();
which results to
javax.swing.text.PlainDocument cannot be cast to
javax.swing.text.StyledDocument
How can I achieve this with JTextPane?

Your approach is wrong. To achieve what you want, you will need to setup your JTextPane to hold an HTMLDocument, and use the methods of this HTMLDocument to insert the content of your JTextArea with something like insertHTML or using an HTMLEditorKit and its read method.
Try something like that:
JTextArea myJta = new JTextArea();
JTextPane myJtp = new JTextPane();
myJtp.setContentType("text/html");
...
public void insertHTML(String html, int location) {
try {
HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
Document doc = editor.getDocument();
StringReader reader = new StringReader(html);
kit.read(reader, doc, location);
} catch (Exception ex) {
ex.printStackTrace();
}
}
...
insertHTML(myJta.getText(),0);

Related

How to update a binary file

I'm creating a GUI, and I use a method "getStudentInfo()" of the Student object return data type to retrieve information from the JTextFields and storing them into the "student" object.
public Student getStudentInfo() {
Student student = new Student();
String name = jtfName.getText();
student.setName(name);
String idNumber = jtfIDNumber.getText();
student.setIdNumber(idNumber);
String address = jtfAddress.getText();
student.setAddress(address);
String phoneNumber = jtfPhoneNumber.getText();
student.setPhoneNumber(phoneNumber);
String major = jtfMajor.getText();
student.setMajor(major);
return student;
}
Then, in a different class, I create an "Add" button that, when clicked, is supposed to add the "student" object into an ArrayList, and then write the ArrayList into a binary file.
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
File studentFile = new File(FILENAME);
ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(text.getStudentInfo());
try {
FileOutputStream fos = new FileOutputStream(studentFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
}
catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
But when I run the program and I write a student's info and add it to the binary file, then I go to add another student, it overwrites the previous student's info completely. Any help would be greatly appreciated.
In the actionPerformed method of your class, AddButtonListener, you have the following line of code:
FileOutputStream fos = new FileOutputStream(studentFile);
This constructor will open the file so bytes are written to the beginning of your file. Since you reopen this file each time the button is clicked, you are replacing the file contents with new data. Instead, use the constructor with the boolean parameter for appending bytes rather than overwriting...
FileOutputStream fos = new FileOutputStream(studentFile, true);
You can check out this constructor's details in the java documentation...
FileOutputStream constructor documentation

Convert awesomium webview to String

I am new to awesomium and I only want to load a page using webview and get the current document to sting
webView.Source = New Uri("http://www.google.com")
// somewhere in your code that initializes your webView...
webView.LoadingFrameComplete += new FrameEventHandler(WebView_LoadFramingComplete);
private void WebView_LoadFramingComplete(object sender, FrameEventArgs e)
{
if (e.IsMainFrame)
{
JSValue html = view.ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML");
}
}

Display image in table

I am trying to insert an image into table view in JavafX. Here is how I set up my table view:
TableColumn prodImageCol = new TableColumn("IMAGES");
prodImageCol.setCellValueFactory(new PropertyValueFactory<Product, Image>("prodImage"));
prodImageCol.setMinWidth(100);
// setting cell factory for product image
prodImageCol.setCellFactory(new Callback<TableColumn<Product,Image>,TableCell<Product,Image>>(){
#Override
public TableCell<Product,Image> call(TableColumn<Product,Image> param) {
TableCell<Product,Image> cell = new TableCell<Product,Image>(){
public void updateItem(Product item, boolean empty) {
if(item!=null){
ImageView imageview = new ImageView();
imageview.setFitHeight(50);
imageview.setFitWidth(50);
imageview.setImage(new Image(product.getImage()));
}
}
};
return cell;
}
});
viewProduct.setEditable(false);
viewProduct.getColumns().addAll(prodImageCol, prodIDCol, prodNameCol, prodDescCol, prodPriceCol, col_action);
viewProduct.getItems().setAll(product.populateProductTable(category));
private SimpleObjectProperty prodImage;
public void setprodImage(Image value) {
prodImageProperty().set(value);
}
public Object getprodImage() {
return prodImageProperty().get();
}
public SimpleObjectProperty prodImageProperty() {
if (prodImage == null) {
prodImage = new SimpleObjectProperty(this, "prodImage");
}
return prodImage;
}
And this is how I retrieve the image from database:
Blob blob = rs.getBlob("productImage");
byte[] data = blob.getBytes(1, (int) blob.length());
bufferedImg = ImageIO.read(new ByteArrayInputStream(data));
image = SwingFXUtils.toFXImage(bufferedImg, null);
However I am getting error at the setting up of table view: imageview.setImage(new Image(product.getImage()));
The error message as:
no suitable constructor found for Image(Image)
constructor Image.Image(String,InputStream,double,double,boolean,boolean,boolean) is not applicable
(actual and formal argument lists differ in length)
constructor Image.Image(int,int) is not applicable
(actual and formal argument lists differ in length)
constructor Image.Image(InputStream,double,double,boolean,boolean) is not applicable
(actual and formal argument lists differ in length)
constructor Image.Image(InputStream) is not applicable
(actual argument Image cannot be converted to InputStream by method invocation conversion)
constructor Image.Image(String,double,double,boolean,boolean,boolean) is not applicable
(actual and formal argument lists differ in length)
constructor Image.Image(String,double,double,boolean,boolean) is not applicab...
I did managed to retrieve and display an image inside an image view but however, I can't display it in table column. Any help would be appreciated. Thanks in advance.
The problem that's causing the exception is that your method product.getImage() is returning an javafx.scene.Image. There's no need to do anything else at this point: You have an image, so use it (before you were trying to construct new Image(Image) - which is not even possible). This is what you want to be using:
imageview.setImage(product.getImage());
Your second problem is that while you're creating an ImageView every time you update the cell, you're not doing anything with it. Here's your original code:
TableCell<Product,Image> cell = new TableCell<Product,Image>(){
public void updateItem(Product item, boolean empty) {
if(item!=null){
ImageView imageview = new ImageView();
imageview.setFitHeight(50);
imageview.setFitWidth(50);
imageview.setImage(new Image(product.getImage()));
}
}
};
return cell;
Like #tomsontom suggested, I'd recommend using setGraphic(Node) to attach your ImageView to the TableCell. So you might end up with something like this:
//Set up the ImageView
final ImageView imageview = new ImageView();
imageview.setFitHeight(50);
imageview.setFitWidth(50);
//Set up the Table
TableCell<Product,Image> cell = new TableCell<Product,Image>(){
public void updateItem(Product item, boolean empty) {
if(item!=null){
imageview.setImage(product.getImage()); //Change suggested earlier
}
}
};
// Attach the imageview to the cell
cell.setGraphic(imageview)
return cell;
The first point #tomsontom was making is that your method of creating an Image is a little roundabout. Sure, it seems to work... but there's a simpler way. Originally you were using:
bufferedImg = ImageIO.read(new ByteArrayInputStream(data));
image = SwingFXUtils.toFXImage(bufferedImg, null);
But a better way of doing it would be switching those lines with:
image = new Image(new ByteArrayInputStream(data));
why are not creating the Image directly from the data new Image(new ByteArrayInputStream(data)) no need to rewrap it our use Swing stuff
I don't see a public Image(Object) constructor in FX8 - why passing it anyways if you are already have an image instance?
you need to set the ImageView on the cell with setGraphic()

How can I remove the tables rendered around the webparts in the Rich Content area?

How would I override the tables rendered around the webparts in the "Rich Content" area?
I have successfully removed the tables around webpartzones and their webparts but can't figure how to remove the tables around Rich Content area webparts.
I am not using the Content Editor WebPart.
The "Rich Content" area I am using is created using the PublishingWebControls:RichHtmlField.
This is the control which has content and webparts.
Bounty here.
I have pondered this myself in the past and I've come up with two options, though none are very appealing, so have not implemented them:
Create a custom rich text field. Override render, call base.Render using a TextWriter object and place the resulting html in a variable, which you then "manually" clean up, before writing to output.
Create a custom rich text field. Override render, but instead of calling base.Render, take care of the magic of inserting the webparts yourself. (This is probably trickier.)
Good luck!
Update, some example code I use to minimize the output of the RichHtmlField:
public class SlimRichHtmlField : RichHtmlField
{
protected override void Render(HtmlTextWriter output)
{
if (IsEdit() == false)
{
//This will remove the label which precedes the bodytext which identifies what
//element this is. This is also identified using the aria-labelledby attribute
//used by for example screen readers. In our application, this is not needed.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
htw.Flush();
string replaceHtml = GetReplaceHtml();
string replaceHtmlAttr = GetReplaceHtmlAttr();
sb.Replace(replaceHtml, string.Empty).Replace(replaceHtmlAttr, string.Empty);
output.Write(sb.ToString());
}
else
{
base.Render(output);
}
}
private string GetReplaceHtmlAttr()
{
return " aria-labelledby=\"" + this.ClientID + "_label\"";
}
private string GetReplaceHtml()
{
var sb = new StringBuilder();
sb.Append("<div id=\"" + this.ClientID + "_label\" style='display:none'>");
if (this.Field != null)
{
sb.Append(SPHttpUtility.HtmlEncode(this.Field.Title));
}
else
{
sb.Append(SPHttpUtility.HtmlEncode(SPResource.GetString("RTELabel", new object[0])));
}
sb.Append("</div>");
return sb.ToString();
}
private bool IsEdit()
{
return SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New;
}
}
This code is then used by your pagelayout like this:
<YourPrefix:SlimRichHtmlField ID="RichHtmlField1" HasInitialFocus="false" MinimumEditHeight="200px" FieldName="PublishingPageContent" runat="server" />
Got it:
https://sharepoint.stackexchange.com/a/32957/7442

How to add a new item into ObjectListView?

I tried the demo code in demo project but I can't add new item successfully.
It just add new new NULL group and NULL item.
Please give me an simple example code to add new item (text and image).
Thank you!
Oh sorry! I forgot it. This is the first time I participate in this site.
I use C#. And the code is:
objectListView1.BeginUpdate();
objectListView1.AddObject(new string [] {"Hello","dfdsF" });
objectListView1.EndUpdate();
and
objectListView1.BeginUpdate();
OLVListItem item = new OLVListItem(new string [] {"Hello","dfdsF" });
objectListView1.Items.Add(item);
objectListView1.EndUpdate();
It's so different form ListView and EXListView which I can define a text or a image when creating new item. But in ObjectListView, I don't understand OBJECT?
I get ObjectListView anh it's demo code form here http://nchc.dl.sourceforge.net/project/objectlistview/objectlistview/v2.5/ObjectListViewFull-2.5.0.zip
I will show you what to do to add items. Try to create a class, then make getters and setters for the properties you want to show on your ObjectListView.
SetObjects method takes a List<T>:
public Form1()
{
InitializeComponent();
this.objectListView1.SetObjects(haha.GET());
}
Now this is my class, I called it haha, I've two properties in it (Name and Detail):
class haha
{
string name;
string detail;
public haha(string name , string detail)
{
this.name = name;
this.detail = detail;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Detail
{
get { return detail; }
set { detail = value; }
}
static internal List<haha> GET()
{
haha item = new haha("zeko", "dunno");
haha xx = new haha("sheshe", "dunno");
haha ww = new haha("murhaf", "dunno");
haha qq = new haha("soz", "dunno");
haha ee = new haha("HELLO", "dunno");
List<haha> x = new List<haha>();
x.Add(item);
x.Add(xx);
x.Add(ww);
x.Add(qq);
x.Add(ee);
return x;
}
}
Now
change ShowGroups in ObjectListView to false
then add the columns that you want; I've added two columns, one for Name and one for Detail
and as in the picture when you add a column, see the AspectName and write exactly the same name of its property that you want to show from your class
Here's the result:
If you want to use AddObject(), which takes an object, I'd write this:
private void button1_Click(object sender, EventArgs e)
{
haha newObject = new haha("memo","zezo");
objectListView1.AddObject(newObject);
}
Happy coding :)
The best thing is to use an entity class. Then make a list of items and add this list to your ObjectListView.
myObjectListView.SetObjects(myListofEntityItems);
But before you do that, you have to setup the columns in your designer. Just add a column, and in the field AspectName enter the exact name of the attribute of your entity item.

Resources