I am using the YouTube embedded link in my website .I want to validate the link as if user paste something else other then embedded link then it should give me an alert invalid URL. I have used so many regex some has already in my code i have commented it .I want regular expression of YouTube embedded link only. Here i my code:
package com.edubot.client.lecture;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialTextBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
public class EmbeddedLink extends Composite {
private static EmbeddedLinkUiBinder uiBinder = GWT
.create(EmbeddedLinkUiBinder.class);
interface EmbeddedLinkUiBinder extends UiBinder<Widget, EmbeddedLink> {
}
#UiField MaterialButton buttonembedded;
// #UiField IFrameElement youtubevideo;
#UiField HTMLPanel htmlpanel;
#UiField MaterialTextBox textbox ;
public EmbeddedLink() {
super();
sinkEvents( Event.ONPASTE );
initWidget(uiBinder.createAndBindUi(this));
}
#Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (event.getTypeInt()) {
case Event.ONPASTE: {
Timer timer = new Timer() {
#Override
public void run() {
// TODO Auto-generated method stub
onPasted();
Window.alert("paste");
}
};
timer.schedule(1000);
}
}
}
// #UiHandler("buttonembedded")
// void onClick(ClickEvent e) {
//// onPasted();
// }
private void onPasted(){
// youtubevideo.setSrc(addEmbeddedLink());
Window.alert("msg1");
if(testEmbeddedLink()) {
String link=textbox.getText().trim();
htmlpanel.getElement().setInnerHTML(link);
Window.alert("Valid URL");
} else {
Window.alert("Invalid URL");
}
}
public boolean testEmbeddedLink(){
String link=textbox.getText().trim();
Window.alert("msg");
String patternString = "(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/)(?:)(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/[a-zA-Z0-9\-]*";
// String patternString = "<iframe title='YouTube video player' width='' height='' src='http://www.youtube.com/embed/$1' frameborder='0' allowfullscreen='1'></iframe>";
// String patternString = "~<iframe.+?src="https?://www.youtube.com/embed/([a-zA-Z0-9_-]{11})"[^>]+?></iframe>~i";
boolean result = link.matches(patternString);
return result;
}
// "youtube.com/(?<=v|embed\\)?[a-zA-Z0-9]+[^#\\&\\?]*";
// "(?<=youtu.be/?<=v|embed\\/)?[a-zA-Z0-9]+[^#\\&\\?]*";
// "(https?://)?(www\\.)?(yotu\\.be/|youtube\\.com/)?((.+/)?(watch(\\?v=|.+&v=))?(v=)?)([\\w_-]{11})(&.+)?"
// (\"http:\/\/www\.youtube\.com\/v\/\w{11}\&rel\=1\");
// (https?://www.youtube(?:-nocookie)?.com/(?:v|embed)/([a-zA-Z0-9-]+).*)"
// /<iframe.+?src="http://www.youtube.com/embed/([a-zA-Z0-9_-]{11})"[^>]+?>";</iframe>/i";
// "(?:youtube.com)\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})\W";
// "s*(https?://www.youtube(?:-nocookie)?.com/(?:v|embed)/([a-zA-Z0-9-]+).*) ";
// "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*)
}
private String getYouTubeUrl(String text)
{
String finalUrl = null;
String p = "(//www.youtube(?:-nocookie)?.com/(?:v|embed)/([a-zA-Z0-9-_]+).*)";
if(text.contains("src"))
{
if(text.contains("//") && text.contains("frameborder"))
{
int startpos = text.indexOf("/", text.indexOf("src="));
int endpos = text.indexOf("frameborder");
String url=text.substring(startpos, endpos-2);
if(url.matches(p))
{
finalUrl = url;
}
else
{
Window.alert("You have entered a wrong embed code");
}
}
else
{
Window.alert("You have entered a wrong embed code");
}
}
else
{
Window.alert("You have entered a wrong embed code");
}
return finalUrl;
}
Related
Im a littlebit stuck with that.
Im using JxBrowser for my JavaFX project.
Im also using JFoenix to push the look.
Now when i browse to some sites, the URLBar which is a JFXTextField becomes unusable. I cant write anymore in it.
But the default JavaFX contextmenu still works.
Whats interesting is that key listeners on the website, like F for fullscreen on youtube still works.
To fix this, the only way that works, is to click a completely different Window on the PC.
For example im clicking to IntelliJ than back to the JavaFX frame, than its working again. As i wrote its only on specefic sites.
No Exceptions are thrown.
If its maybew important, im using 2 TabPanes, One for the Tab and another for the Content.
Do someone has an idea?
The class that generates the Tab:
package de.liz3.liz3web.browser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.javafx.BrowserView;
import de.liz3.liz3web.gui.controller.MainController;
import javafx.application.Platform;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.input.KeyCode;
import java.util.Vector;
/**
* Created by Liz3 on 22.02.2017.
*/
public class TabManager {
private Vector<BrowserTab> activeTabs;
private MainController controller;
public TabManager(MainController controller) {
this.controller = controller;
activeTabs = new Vector<>();
controller.getUrlField().setOnMouseClicked(event -> controller.getUrlField().requestFocus());
TabPane head = controller.getHeaderTabPane();
controller.getUrlField().setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.ENTER) {
selectedBrowserTab().browseOrSearch(TabManager.this.controller.getUrlField().getText());
}
});
controller.getBackBtn().setOnAction(event -> selectedBrowserTab().getEngine().goBack());
controller.getForwardBtn().setOnAction(event -> selectedBrowserTab().getEngine().goForward());
head.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == controller.getNewTab()) {
newTab(null);
return;
}
controller.getMainTabPane().getSelectionModel().select(getContentTab(newValue));
controller.getUrlField().setText(selectedBrowserTab().getCurrentUrl());
});
}
public void newTab(String url) {
new Thread(() -> {
Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
Tab headerTab = new Tab("New Tab");
Tab contentTab = new Tab();
contentTab.setContent(view);
BrowserTab t = new BrowserTab(browser, view, contentTab, headerTab);
activeTabs.add(t);
Platform.runLater(() -> {
controller.getHeaderTabPane().getTabs().add(headerTab);
controller.getMainTabPane().getTabs().add(contentTab);
controller.getHeaderTabPane().getTabs().remove(controller.getNewTab());
controller.getHeaderTabPane().getTabs().add(controller.getNewTab());
controller.getMainTabPane().getSelectionModel().select(contentTab);
controller.getHeaderTabPane().getSelectionModel().select(headerTab);
controller.getUrlField().setEditable(true);
controller.getUrlField().setText("");
t.browseOrSearch(url);
});
}).start();
}
public BrowserTab selectedBrowserTab() {
for (BrowserTab tab : activeTabs) {
if (tab.getHeaderTab() == controller.getHeaderTabPane().getSelectionModel().getSelectedItem()) {
return tab;
}
}
return null;
}
public Tab getSelectedHeaderTab() {
return controller.getHeaderTabPane().getSelectionModel().getSelectedItem();
}
public Tab getSelectedContentTab() {
return controller.getMainTabPane().getSelectionModel().getSelectedItem();
}
public Tab getHeaderTab(Tab contentTab) {
for (BrowserTab tab : activeTabs) {
if (tab.getContentTab() == contentTab) {
return tab.getHeaderTab();
}
}
return null;
}
public Tab getContentTab(Tab headerTab) {
for (BrowserTab tab : activeTabs) {
if (tab.getHeaderTab() == headerTab) {
return tab.getContentTab();
}
}
return null;
}
public MainController getController() {
return controller;
}
public Vector<BrowserTab> getActiveTabs() {
return activeTabs;
}
}
The Browser class:
package de.liz3.liz3web.browser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.events.*;
import com.teamdev.jxbrowser.chromium.javafx.BrowserView;
import de.liz3.liz3web.Main;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Tab;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Created by Liz3 on 21.02.2017.
*/
public class BrowserTab {
private Browser engine;
private BrowserView view;
private Tab contentTab;
private Tab headerTab;
private String currentUrl;
public BrowserTab(Browser engine, BrowserView view, Tab contentTab, Tab headerTab) {
this.engine = engine;
this.view = view;
this.contentTab = contentTab;
this.headerTab = headerTab;
this.currentUrl = "";
setUpTab();
}
public void browseOrSearch(String address) {
if (address == null) {
return;
}
if (address.startsWith("http://") || address.startsWith("https://")) {
this.engine.loadURL(address);
return;
}
if (!address.contains(" ") && address.contains(".")) {
address = "http://" + address;
this.engine.loadURL(address);
return;
}
String encode = null;
try {
encode = URLEncoder.encode(address, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.engine.loadURL("https//google.com/search?q=" + encode);
}
private void setUpTab() {
this.headerTab.setClosable(true);
this.headerTab.setOnCloseRequest(new EventHandler<Event>() {
#Override
public void handle(Event event) {
Main.tm.getController().getMainTabPane().getTabs().remove(contentTab);
Main.tm.getActiveTabs().remove(this);
}
});
this.engine.addTitleListener(titleEvent -> Platform.runLater(() -> BrowserTab.this.headerTab.setText(titleEvent.getTitle())));
this.engine.addLoadListener(new LoadListener() {
#Override
public void onStartLoadingFrame(StartLoadingEvent startLoadingEvent) {
Platform.runLater(() -> {
BrowserTab.this.currentUrl = BrowserTab.this.engine.getURL();
if (Main.tm.getSelectedHeaderTab() == BrowserTab.this.headerTab) {
Main.tm.getController().getUrlField().setText(BrowserTab.this.currentUrl);
}
});
}
#Override
public void onProvisionalLoadingFrame(ProvisionalLoadingEvent provisionalLoadingEvent) {
}
#Override
public void onFinishLoadingFrame(FinishLoadingEvent finishLoadingEvent) {
Platform.runLater(() -> {
BrowserTab.this.currentUrl = BrowserTab.this.engine.getURL();
if (Main.tm.getSelectedHeaderTab() == BrowserTab.this.headerTab) {
Main.tm.getController().getUrlField().setText(BrowserTab.this.currentUrl);
}
});
}
#Override
public void onFailLoadingFrame(FailLoadingEvent failLoadingEvent) {
}
#Override
public void onDocumentLoadedInFrame(FrameLoadEvent frameLoadEvent) {
}
#Override
public void onDocumentLoadedInMainFrame(LoadEvent loadEvent) {
}
});
this.engine.setPopupHandler(popupParams -> {
Platform.runLater(() -> Main.tm.newTab(popupParams.getURL()));
return null;
});
}
public Browser getEngine() {
return engine;
}
public BrowserView getView() {
return view;
}
public Tab getContentTab() {
return contentTab;
}
public Tab getHeaderTab() {
return headerTab;
}
public String getCurrentUrl() {
return currentUrl;
}
}
By default JxBrowser is running in HEAVYWEIGHT rendering mode. It's not recommended to use HEAVYWEIGHT rendering mode in applications like yours with tabs and layers. Please use LIGHTWEIGHT rendering mode. It should work without any issues:
Browser browser = new Browser(BrowserType.LIGHTWEIGHT);
BrowserView view = new BrowserView(browser);
JTextPane text;
text.setText("somewords <img src=\"file:///C:/filepath/fire.png\" text=\"[fire1]\" title=\"[fire2]\" alt=\"[fire3]\" style=\"width:11px;height:11px;\"> otherwords");
Gives me this , which is as expected. But when I highlight it and copy paste it, I get "somewords otherwords". The same thing done inside Firefox when copied would paste "somewords [fire3] otherwords" (it substitutes alt text for image). Is there any way to replicate this behavior where the alt text is copied, or any other indication that a picture was copied? I'm guessing it is not a built in feature, so what I probably need to know is what should be overloaded to mimic this behavior.
Its for an output/chat window so its important that when the users quote it it includes the images (like emotes would)
Update: Successfully overrode the copyAction method... now what?
// (should) allow copying of alt text in place of images
class CustomEditorKit extends HTMLEditorKit {
Action[] modifiedactions;
CustomEditorKit() {
int whereat=-1;
modifiedactions=super.getActions();
for(int k=0;k<super.getActions().length;k++) {
if(super.getActions()[k] instanceof CopyAction) //find where they keep the copyaction
{
whereat=k;
modifiedactions[whereat]=new CustomCopyAction(); //and replace it with a different one
}
}
}
#Override
public Action[] getActions() {
return modifiedactions; //returns the modified version instead of defaultActions
}
public static class CustomCopyAction extends TextAction {
public CustomCopyAction() {
super(copyAction);
}
#Override
public void actionPerformed(ActionEvent e) { //need to change this to substitute images with text, preferably their alt text.
JTextComponent target = getTextComponent(e);
//target.getText() gives full body of html, unbounded by selection area
if (target != null) {
target.copy(); //a confusing and seemingly never ending labyrinth of classes and methods
}
}
}
}
The only way I can think of accomplishing this is by writing your own TransferHandler, and overriding the getSourceActions and exportToClipboard methods.
You can convert the HTML to plain text yourself, rather than letting Swing use the getSelectedText method of JTextPane, by recursively converting each Element of the HTML Document, customizing the conversion in the case where the Element has a NameAttribute of IMG and also has an ALT attribute.
Here's what I came up with:
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.awt.EventQueue;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.TransferHandler;
import javax.swing.text.AttributeSet;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTML;
public class HTMLCopier
extends TransferHandler {
private static final long serialVersionUID = 1;
private final Collection<DataFlavor> flavors;
HTMLCopier() {
Collection<DataFlavor> flavorList = new LinkedHashSet<>();
Collections.addAll(flavorList,
new DataFlavor(String.class, null),
DataFlavor.stringFlavor);
String[] mimeTypes = {
"text/html", "text/plain"
};
Class<?>[] textClasses = {
Reader.class, String.class, CharBuffer.class, char[].class
};
Class<?>[] byteClasses = {
InputStream.class, ByteBuffer.class, byte[].class
};
String[] charsets = {
Charset.defaultCharset().name(),
StandardCharsets.UTF_8.name(),
StandardCharsets.UTF_16.name(),
StandardCharsets.UTF_16BE.name(),
StandardCharsets.UTF_16LE.name(),
StandardCharsets.ISO_8859_1.name(),
"windows-1252",
StandardCharsets.US_ASCII.name(),
};
try {
flavorList.add(new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType +
"; class=" + String.class.getName()));
for (String mimeType : mimeTypes) {
for (Class<?> textClass : textClasses) {
flavorList.add(new DataFlavor(String.format(
"%s; class=\"%s\"",
mimeType, textClass.getName())));
}
for (String charset : charsets) {
for (Class<?> byteClass : byteClasses) {
flavorList.add(new DataFlavor(String.format(
"%s; charset=%s; class=\"%s\"",
mimeType, charset, byteClass.getName())));
}
}
}
for (String mimeType : mimeTypes) {
flavorList.add(new DataFlavor(String.format(
"%s; charset=unicode; class=\"%s\"",
mimeType, InputStream.class.getName())));
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
this.flavors = Collections.unmodifiableCollection(flavorList);
}
#Override
public int getSourceActions(JComponent component) {
return COPY_OR_MOVE;
}
#Override
public void exportToClipboard(JComponent component,
Clipboard clipboard,
int action) {
JTextPane pane = (JTextPane) component;
Document doc = pane.getDocument();
int start = pane.getSelectionStart();
int end = pane.getSelectionEnd();
final String html;
final String plainText;
try {
StringWriter writer = new StringWriter(end - start);
pane.getEditorKit().write(writer, doc, start, end - start);
html = writer.toString();
StringBuilder plainTextBuilder = new StringBuilder();
appendTextContent(doc.getDefaultRootElement(), start, end,
plainTextBuilder);
plainText = plainTextBuilder.toString();
} catch (BadLocationException | IOException e) {
throw new RuntimeException(e);
}
Transferable contents = new Transferable() {
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavors.contains(flavor);
}
#Override
public DataFlavor[] getTransferDataFlavors() {
return flavors.toArray(new DataFlavor[0]);
}
#Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException,
IOException {
String data;
if (flavor.isMimeTypeEqual("text/html")) {
data = html;
} else {
data = plainText;
}
Class<?> dataClass = flavor.getRepresentationClass();
if (dataClass.equals(char[].class)) {
return data.toCharArray();
}
if (flavor.isRepresentationClassReader()) {
return new StringReader(data);
}
if (flavor.isRepresentationClassCharBuffer()) {
return CharBuffer.wrap(data);
}
if (flavor.isRepresentationClassByteBuffer()) {
String charset = flavor.getParameter("charset");
return Charset.forName(charset).encode(data);
}
if (flavor.isRepresentationClassInputStream()) {
String charset = flavor.getParameter("charset");
return new ByteArrayInputStream(
data.getBytes(charset));
}
if (dataClass.equals(byte[].class)) {
String charset = flavor.getParameter("charset");
return data.getBytes(charset);
}
return data;
}
};
clipboard.setContents(contents, null);
if (action == MOVE) {
pane.replaceSelection("");
}
}
private void appendTextContent(Element element,
int textStart,
int textEnd,
StringBuilder content)
throws BadLocationException {
int start = element.getStartOffset();
int end = element.getEndOffset();
if (end < textStart || start >= textEnd) {
return;
}
start = Math.max(start, textStart);
end = Math.min(end, textEnd);
AttributeSet attr = element.getAttributes();
Object tag = attr.getAttribute(AttributeSet.NameAttribute);
if (tag.equals(HTML.Tag.HEAD) ||
tag.equals(HTML.Tag.TITLE) ||
tag.equals(HTML.Tag.COMMENT) ||
tag.equals(HTML.Tag.SCRIPT)) {
return;
}
if (tag.equals(HTML.Tag.INPUT) ||
tag.equals(HTML.Tag.TEXTAREA) ||
tag.equals(HTML.Tag.SELECT)) {
// Swing doesn't provide a way to read input values
// dynamically (as far as I know; I could be wrong).
return;
}
if (tag.equals(HTML.Tag.IMG)) {
Object altText = attr.getAttribute(HTML.Attribute.ALT);
if (altText != null) {
content.append(altText);
}
return;
}
if (tag.equals(HTML.Tag.CONTENT)) {
content.append(
element.getDocument().getText(start, end - start));
return;
}
int count = element.getElementCount();
for (int i = 0; i < count; i++) {
appendTextContent(element.getElement(i), textStart, textEnd,
content);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JTextPane text = new JTextPane();
text.setContentType("text/html");
text.setEditable(false);
text.setText("somewords <img src=\"file:///C:/filepath/fire.png\" text=\"[fire1]\" title=\"[fire2]\" alt=\"[fire3]\" style=\"width:11px;height:11px;\"> otherwords");
text.setTransferHandler(new HTMLCopier());
JFrame window = new JFrame("HTML Copier");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new JScrollPane(text));
window.pack();
window.setLocationByPlatform(true);
window.setVisible(true);
text.selectAll();
text.copy();
}
});
}
}
Edit: Updated code to properly place only highlighted text on clipboard.
JTextPane provides method setEditorKit(EditorKit). I think you'll find your solution by providing a custom EditorKit.
You can override the copy and cut actions in a DefaultEditorKit, then pass it to JTextPane.
http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DefaultEditorKit.html#copyAction
Or Java 8 introduces HTMLEditorKit that, if compatible with JTextPane, may provide the behavior you want.
https://docs.oracle.com/javase/8/docs/api/javax/swing/text/html/HTMLEditorKit.html
I'm trying to connect my java files so I can create an app that uses main menu, but this error always persist, no matter what I do. here's my code:
Zakat.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Zakat extends MIDlet
{
private Display display;
public FormLoading FormLoading;
public Keluar Keluar;
public MenuUtama MenuUtama;
public Pengenalan Pengenalan;
public Kalkulator Kalkulator;
public About About;
public Profil Profil;
//public CanvasAwal canvasAwal;
public Zakat()
{
display = Display.getDisplay(this);
FormLoading = new FormLoading(this);
Keluar = new Keluar(this);
MenuUtama = new MenuUtama(this);
Pengenalan = new Pengenalan(this);
Kalkulator = new Kalkulator(this);
About = new About(this);
Profil = new Profil(this);
//canvasAwal = new CanvasAwal(this);
}
public void startApp()
{
Display.getDisplay(this).setCurrent(FormLoading);
}
public void pauseApp()
{
}
public void destroyApp(boolean b)
{
}
}
MenuUtama.java
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
class MenuUtama extends List implements CommandListener
{
public Zakat app;
Ticker tc;
public MenuUtama(Zakat app)
{
super("Menu Utama",List.IMPLICIT);
this.app = app;
Image img=null;
Image img1=null;
Image img2=null;
try
{
img = Image.createImage("/icon1.png");
}
catch(Exception e)
{
}
append("Pengenalan Zakat",img);
append("Kalkulator",img);
append("About",img);
append("Profil",img);
append("Keluar",img);
addCommand(new Command("Pilih",Command.OK,0));
addCommand(new Command("Keluar",Command.EXIT,0));
tc = new Ticker ("Silahkan Pilih");
setTicker(tc);
setCommandListener(this);
}
public void commandAction (Command c, Displayable d)
{
switch(getSelectedIndex())
{
case 0:
Display.getDisplay(app).setCurrent(app.Pengenalan);
break;
case 1:
Display.getDisplay(app).setCurrent(app.Kalkulator);
break;
case 2:
Display.getDisplay(app).setCurrent(app.About);
break;
case 3:
Display.getDisplay(app).setCurrent(app.Profil);
break;
case 4:
Display.getDisplay(app).setCurrent(app.Keluar);
break;
}
switch( c.getCommandType())
{
case Command.EXIT:
Display.getDisplay(app).setCurrent(app.Keluar);
break;
}
}
}
Kalkulator.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.IOException;
public class Kalkulator extends MIDlet implements CommandListener,ItemCommandListener
{
Zakat app;
private Command cmdHitung = new Command("Hitung",Command.ITEM,1);
private Command exitCommand = new Command("Kembali",Command.EXIT,1);
private Display display;
private Form form = new Form("kalkulator");
private TextField var;
private TextField hasil;
public Kalkulator(Zakat app)
{
var = new TextField("Penghasilan selama 1 Tahun",null,12,TextField.NUMERIC);
hasil = new TextField("Zakat yang harus dibayarkan",null, 12 ,TextField.NUMERIC);
form.append(var);
form.append(hasil);
form.setCommandListener(this);
}
public void startApp()
{
if(display==null)
{
display = Display.getDisplay(this);
display.setCurrent(form);
}
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction (Command c, Displayable d)
{
switch (c.getCommandType())
{
case Command.EXIT:
Display.getDisplay(app).setCurrent(app.MenuUtama);
break;
}
}
public void commandAction(Command c, Item item)
{
if(c.equals(this.cmdHitung))
{
int hsl = Integer.parseInt(var.getString()) / 40;
hasil.setString(Integer.toString(hsl));
}
}
}
please help, and thanks before.
You appear to be calling the setCurrent method on a Display instance. That method expects an argument that is an instance of some class that implements Displayable. But Kalculator is a Midlet instance and that does not implement Displayable. Hence the compilation error.
I'm not a J2ME developer, but it looks like you should be passing setCurrent a Window object; e.g. a Form, Alert, List or TextBox.
I'm writing an eclipse-plugin which creating a new Console. Please see my source code:
CliConsoleFactory.java
import java.io.IOException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleFactory;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.IOConsoleOutputStream;
public class CliConsoleFactory implements IConsoleFactory {
private static final String ENTER_KEY = "\r\n";
private static final String CLI_PROMPT = "CLI> ";
private IConsoleView m_consoleView = null;
#Override
public void openConsole() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
m_consoleView = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
} catch (PartInitException e1) {
e1.printStackTrace();
}
if (m_consoleView == null) {
return;
}
final MyIOConsole myConsole = new MyIOConsole("CLI", null);
final IDocument document = myConsole.getDocument();
document.addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(DocumentEvent event) {
if (ENTER_KEY.equals(event.getText())) {
// Print the Prompt
writeToConsole(myConsole, CLI_PROMPT);
}
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { myConsole });
m_consoleView.display(myConsole);
writeToConsole(myConsole, CLI_PROMPT);
}
private void writeToConsole(final MyIOConsole myConsole, String msg) {
IOConsoleOutputStream stream = myConsole.newOutputStream();
stream.setActivateOnWrite(true);
try {
stream.write(msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
MyIOConsole.java
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.console.IOConsole;
public class MyIOConsole extends IOConsole {
public MyIOConsole(String name, ImageDescriptor imageDescriptor) {
super(name, imageDescriptor);
}
}
It works great. When I enter to a new line, the Prompt is "CLI> ", but the Caret position is not okie, it is at the first position of the line instead of the last position. I want to make the Caret move to the last position. Who know please help me.!!!
To gain access to the caret position, you will need to implement a console viewer.
This is the setup I have for my custom console,
public class MyConsole extends IOConsole
{
....
#Override
public IPageBookViewPage createPage(IConsoleView view) {
return new MyConsolePage(this, view);
}
}
public class MyConsolePage extends TextConsolePage
{
....
#Override
protected TextConsoleViewer createViewer(Composite parent) {
return new MyConsoleViewer(parent, (MyConsole) this.getConsole());
}
}
public class MyConsoleViewer extends TextConsoleViewer
{
//This class gives you access to setting the caret position
//by getting the styled text widget and then using setCaretOffset
}
There are multiple ways of getting the styled text widget depending on which method you are overriding. I also created my own Console history class which kept track of the caret offset since I needed additional functionality of using the up and down arrow keys to navigate through previously entered commands.
The best way to implement the MyConsoleViewer is to use Eclipse's vast source code that sets a perfect example. I practically reused all of this class org.eclipse.ui.internal.console.IOConsoleViewer. It even shows examples of setting the caret.
Hope this still helps as your question was a while ago.
I want to be notified if a string is copied to the system clipboard. When a new string is copied from the same source application, the FlavorListener won't get an event. To get informed when another string is copied, i read the string from the clipboard, convert it to a SrtingSelection, which is able to take the ownership, and put it back to the clipboard. Now I got informed twice, once the StringSelection lost ownership and once it takes it back. Is there a way to check for the ownership directly, instead of storing the string and check it equals the new one?
Here is my code so far:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
// The clipboard
final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
// read clipboard and take ownership to get the FlavorListener notified
// when the content has changed but the owner has not
processClipboard(cb);
cb.addFlavorListener(new FlavorListener() {
#Override
public void flavorsChanged(FlavorEvent e) {
processClipboard(cb);
}
});
// keep thread for testing
Thread.sleep(100000L);
}
public static void processClipboard(Clipboard cb) {
// gets the content of clipboard
Transferable trans = cb.getContents(null);
if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
// cast to string
String s = (String) trans
.getTransferData(DataFlavor.stringFlavor);
System.out.println(s);
// only StringSelection can take ownership, i think
StringSelection ss = new StringSelection(s);
// set content, take ownership
cb.setContents(ss, ss);
} catch (UnsupportedFlavorException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
I hope you understand my bad english :-(
The previous answer is close to be working.
The real cure is to instead just monitor the event of ownership change. By the monitor's occupying the clipboard as owner when monitoring the clipboard, so when any application changes the clipboard, the ownership would change, so this would reliably indicate the clipboard content change. However, this approach must have sufficient wait to work, (200 ms was found to be working) after an ownership change event before accessing the clipboard and re-occupying the clipboard.
This solution was provided and proved to be working by marc weber at
http://www.coderanch.com/t/377833/java/java/listen-clipboard
I have verified for my purpose. If needed, I can post the solution here.
Yu
To avoid double notification remove the flavor listener before setting the new clipboard content and add the listener again after setting clipboard content.
public class NewClass implements FlavorListener, ClipboardOwner{
private Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
public NewClass() {
System.out.println("NewClass constructor");
clip.setContents(clip.getContents(null), this);
clip.addFlavorListener(this);
try {
Thread.sleep(100000L);
}
catch (InterruptedException e) {
}
}
#Override
public void flavorsChanged(FlavorEvent e) {
System.out.println("ClipBoard Changed!!!");
clip.removeFlavorListener(this);
clip.setContents(clip.getContents(null), this);
clip.addFlavorListener(this);
}
#Override
public void lostOwnership(Clipboard arg0, Transferable arg1) {
System.out.println("ownership losted");
}
}
I think this would work :)
import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
public final class ClipboardMonitor extends Observable implements ClipboardOwner {
private static ClipboardMonitor monitor = null;
public ClipboardMonitor() {
gainOwnership();
}
private void gainOwnership() {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
Transferable content = clip.getContents(null);
DataFlavor[] f = content.getTransferDataFlavors();
boolean imageDetected = false;
for (int i = 0; i < f.length; i++) {
// System.out.println("Name: " + f[i].getHumanPresentableName());
// System.out.println("MimeType: " + f[i].getMimeType());
// System.out.println("PrimaryType: " + f[i].getPrimaryType());
// System.out.println("SubType: " + f[i].getSubType());
if (f[i].equals(DataFlavor.imageFlavor)) {
imageDetected = true;
break;
}
}
if (imageDetected) {
System.out.println("Image content detected");
Transferable t = new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.stringFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return false;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return "dummy text instead of snapshot image";
}
};
clip.setContents(t, this);
} else {
clip.setContents(content, this);
}
setChanged();
notifyObservers(content);
} catch (IllegalArgumentException istateexception) {
istateexception.printStackTrace();
} catch (Exception ioexception) {
ioexception.printStackTrace();
}
}
private int getCurrentEventModifiers() {
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent) currentEvent).getModifiers();
} else
if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent) currentEvent).getModifiers();
}
return modifiers;
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Ownership lost ...");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(200);
gainOwnership();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void flushClipboard() {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(""), null);
}
public static final ClipboardMonitor getMonitor() {
if (monitor == null)
monitor = new ClipboardMonitor();
return (monitor);
}
public static void main(String[] args) {
JFrame f = new JFrame();
ClipboardMonitor monitor = ClipboardMonitor.getMonitor();
monitor.addObserver(new Observer() {
public void update(Observable o, Object arg) {
System.out.println("Clipboard has been regained!");
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 100);
f.setVisible(true);
}
}