how to creat a hyperlink url string in a Java MessageDialog? - url

a simple MessageDialog(or MessageBox,any method can open a dialog )like follows:
MessageDialog.openInformation(shell, "Test", "Get help form this link www.google.com");
is there any way to make www.google.com a hyperlink? click the url and open browser.

thats not possible out of the box. I created a class of my own, named MyMessageDialog to do this:
https://gist.github.com/andydunkel/8914008
Its basically all the source code from MessageDialog. Then I overwrote the createMessageArea method and added a Link instead of a label and added an event listener:
protected Control createMessageArea(Composite composite) {
// create composite
// create image
Image image = getImage();
if (image != null) {
imageLabel = new Label(composite, SWT.NULL);
image.setBackground(imageLabel.getBackground());
imageLabel.setImage(image);
//addAccessibleListeners(imageLabel, image);
GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING)
.applyTo(imageLabel);
}
// create message
if (message != null) {
linkLabel = new Link(composite, getMessageLabelStyle());
linkLabel.setText(message);
linkLabel.addSelectionListener(new SelectionAdapter(){
#Override
public void widgetSelected(SelectionEvent e) {
System.out.println("You have selected: "+e.text);
try {
// Open default external browser
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
}
catch (PartInitException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
catch (MalformedURLException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
});
GridDataFactory
.fillDefaults()
.align(SWT.FILL, SWT.BEGINNING)
.grab(true, false)
.hint(
convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH),
SWT.DEFAULT).applyTo(linkLabel);
}
return composite;
}
The MessageDialog can be called with HTML code in it now:
MyMessageDialog.openError(parent.getShell(), "Hehe", "Google.com Test");
Not a very optimal solution, but it works:
Andy

Related

How hide items when print current page?

I create my web project by Vaadin 7.3.6
When I want to print current page I use this:
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
private ClickListener printListener;
printListener = new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
JavaScript.getCurrent().execute("print();");
}
};
As result it's print current page.
The page content from text and two buttons (Print, OK) on the bottom of page. Nice.
But I want to print only text. Without this 2 buttons.
I want to hide buttons ONLY when printing current page.
When return to page I want to see again this two buttons.
How I can do this?
P.S. I try this:
final Button okButton = new Button(MessageService.getMessage("ok"));
final Button printButton = new Button(MessageService.getMessage("print"));
printButton.setStyleName("small-top-margin");
final JavaScript js = JavaScript.getCurrent();
final UI ui = UI.getCurrent();
printButton.addClickListener(event -> {
logger.debug("click_print");
Thread thread = new Thread(() -> {
ui.access(() -> {
logger.debug("hide_all_buttons");
printButton.setVisible(false);
okButton.setVisible(false);
js.execute("print();");
});
try {
logger.debug("wating_n_seconds");
Thread.sleep(3000);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
ui.access(() -> {
logger.debug("show_all_buttons");
printButton.setVisible(true);
okButton.setVisible(true);
});
});
thread.start();
}); // click listener
First click on printButton - nothing happened
Second click on printButton - print all buttons. It's not correct.
You can hide the button easily with button.setVisible(false). The true trick is to get the button back. One one is to do this in thread and have sufficient delay before switching the button back visible. Here is an example (Java 8 syntax to make it more compact) This works both with Vaadin 7 & 8.
final Button print = new Button("Print");
final UI ui = this; // or UI.getCurrent() or getUI() depending where you are
final JavaScript js = JavaScript.getCurrent();
print.addClickListener(event -> {
Thread t = new Thread(() -> {
ui.access(() -> {
print.setVisible(false);
js.execute("print();");
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ui.access(() -> print.setVisible(true));
});
t.start();
});
layout.addComponent(print);
Alternative approach is to use theming, I.e.
Button print = new Button("Print");
print.addStyleName("no-print");
And the following into your mytheme.scss file, before #mixin mytheme
#media print {
.no-print {
display:none;
}
}

add webview links to favorites

I am developing News app which shows over 50 News sites in webview and users can open links and read the news. I want to save some news as headlines or their links and show them in favourite page. and in favourite page can be clicked and deleted after reading it.
I worked on an thought with long press on page write link to a file and then read the file and make list of favorites. I tested with text view and writing file seems OK but reading it does not. my codes are:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myInflater= inflater.inflate(R.layout.fragment_main, container, false);
TextView txtView = (TextView) myInflater.findViewById(R.id.txtView);
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You have pressed it long :)", Toast.LENGTH_LONG).show();
String filename ="favoritessss.txt";
File file = new File(getActivity().getFilesDir(), filename);
File directory = getActivity().getDir("SunShine", Context.MODE_WORLD_READABLE);
//String filename = "myfile";
String string = "Hello world000000000!"+"\r\n";
FileOutputStream outputStream;
try {
outputStream = getActivity().openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
//Find the view by its id
final TextView tv = (TextView)myInflater.findViewById(R.id.text_view);
txtView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Find the directory for the SD Card using the API
//Don't hardcode "/sdcard"
File sdcard = getActivity().getFilesDir();
//Get the text file
File file = new File(sdcard,"favoritessss.txt");
String[] text = new String[15];
try {
BufferedReader br = new BufferedReader(new FileReader(file));
for (int j=0; j>15; j++) text[j] = br.readLine();
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
tv.setText(text[0]);
Toast.makeText(getActivity(), text[0],
Toast.LENGTH_SHORT).show();
}
});
return myInflater;
}
any comments?

Umbraco unpublish Event not working for the current node

I am developing Umbraco 7 MVC application and my requirement is to add Item inside Umbraco. Item name should be unique. For that used the below code but I am getting the error "Oops: this document is published but is not in the cache (internal error)"
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
if(newsItemExists)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
Then I tried adding code to unpublish but its not working i.e the node is getting published. Below is my code
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
int itemId=1234; //CurrentPublishedNodeId
if(newsItemExists)
{
IContent content = ContentService.GetById(itemId);
ContentService.UnPublish(content);
library.UpdateDocumentCache(item.Id);
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
But with the above code, if you give the CurrentPublishedNodeId=2345 //someOthernodeId its unpublished correctly.
Can you please help me on this issue.
You don't have to do this, Umbraco will automatically append (1) to the name if the item already exists (so it IS unique).
If you don't want this behavior you can check in the following way:
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
var contentService = UmbracoContext.Current.Application.Services.ContentService;
// It's posible to batch publish items, so go through all items
// even though there might only be one in the list of PublishedEntities
foreach (var item in e.PublishedEntities)
{
var currentPage = contentService.GetById(item.Id);
// Go to the current page's parent and loop through all of it's children
// That way you can determine if any page that is on the same level as the
// page you're trying to publish has the same name
foreach (var contentItem in currentPage.Parent().Children())
{
if (string.Equals(contentItem.Name.Trim(), currentPage.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))
e.Cancel = true;
}
}
}
I think your problem might be that you're not looping through all PublishedEntities but using some other way to determine the current page Id.
Note: Please please please do not use the library.UpdateDocumentCache this, there's absolutely no need, ContentService.UnPublish will take care of the cache state.

How to on the Camera Flash for a long time like Torch Light

In my application, when i will click a button, it should open the camera flash for a long time like torch. This implementation is pretty easy in Android. But in BlackBerry i did not get any direct API for this. I have tried some sort of things by which i am able to on the Video and able to make the flash for few seconds. But if you check this app, they made it possible: Flashlight Free(in App World).
Here is my code:
if(field == btnTorch)
{
Player player;
VideoControl _videoControl;
vfmScreen.delete(btnTorch);
try {
player = Manager.createPlayer("capture://video");
player.realize();
Logger.out("Torch", "player realized");
_videoControl = (VideoControl) player.getControl("VideoControl");
FlashControl flashControl = new FlashControl()
{
public int getMode() {
// TODO Auto-generated method stub
Logger.out("Torch", "inside getmode");
return 0;
}
public int[] getSupportedModes() {
// TODO Auto-generated method stub
Logger.out("Torch", "inside getSupportedModes");
return null;
}
public boolean isFlashReady() {
// TODO Auto-generated method stub
return false;
}
public void setMode(int arg0) {
// TODO Auto-generated method stub
Logger.out("Torch", "inside setMode");
}
};
flashControl = (FlashControl) player
.getControl("javax.microedition.amms.control.camera.FlashControl");
if(flashControl!= null) {
Logger.out("Torch", "before Forced fully set the mode");
flashControl.setMode(FlashControl.FORCE);
Logger.out("Torch", "Forced fully set the mode");
}
if (_videoControl != null)
{
Field _videoField = (Field) _videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
_videoControl.setVisible(true);
_videoControl.setDisplayFullScreen(true);
vfmScreen.add(_videoField);
player.start();
EnhancedFocusControl efc = (EnhancedFocusControl)player.getControl("net.rim.device.api.amms.control.camera.EnhancedFocusControl");
efc.startAutoFocus();
Logger.out("Torch", "player started ");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MediaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So what is the possible way to make it?
Thanks,
Arindam.

I want to show splash screen until i am done with downloading xml files from server and after completion show next screen

I am trying to download xml files from server when my application starts. So i want to show splash screen until am done with downloading and then show next screen. below is my code:
Here, i want to show My splash screen when getTopNotDoc() method is under execution. and after completion of that method show next screen.
//get _topics and notification document<br>
_getDoc = new ServerConnectivity(this);
public class ServerConnectivity {
private Document _questionDoc;
private Document _topics;
private Document _notifications;
public ServerConnectivity(ApplicationSession appSession){
//getTopNotDoc();
_this = this;
_appSession = appSession;
new Thread(new Runnable(){
public void run(){
getTopNotDoc();
}
}).start();
}
}
private void getTopNotDoc(){
InputStream inputStream = null ;
try{
// Build a document based on the XML file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
inputStream = getClass().getResourceAsStream("topics.xml");
_topics = builder.parse( inputStream );
inputStream = getClass().getResourceAsStream("notification.xml");
_notifications = builder.parse( inputStream );
if(_topics == null || _notifications == null){
Dialog.alert("Unable to connect to internet");
}
}
catch ( Exception e ){
System.out.println( e.toString() );
}
finally{
if(inputStream != null){
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usually when I do this, I create a loading screen, then I just extend the Thread class.
So I would create a loading screen like this:
public class LoadingScreen extends MainScreen {
public LoadingScreen() {
super();
this.setTitle("loading...");
// add a spinning animated gif or whatever here
final Screen me = this;
new Thread(new Runnable(){
public void run(){
// do something that takes a long time
try { Thread.sleep(1000);} catch (Exception e) {}
}
}){
public void run() {
super.run();
synchronized (UiApplication.getEventLock()) {
UiApplication.getUiApplication().popScreen(me);
}
}
}.start();
}
}
Then I push this screen, it will perform the long task, and then pop itself when its done.
(you may or may not want to disable the back button and menus on this screen)
I made the Runnable as an anonymous inner class just to compact the code, but you probably have this code already in a class somewhere else, so you would pass it in instead.
To add some flexibility and keep your classes loosely coupled together, you could make some modifications to your ServerConnectivity class so your calls could go something like the following:
// push your splash screen on to the stack
//
final SplashScreen splashScreen = new SplashScreen();
UiApplication.getUiApplication().pushScreen(splashScreen);
_getDoc = new ServerConnectivity(this, new ServerConnectivityListener() {
public void onCompleted(ServerConnectivity sender) {
// display next screen
//
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
splashScreen.close();
UiApplication.getUiApplication().pushScreen(new NextScreen());
}
});
}
public void onError(ServerConnectivity sender) {
splashScreen.close();
// display error message, retry, etc...
}
});
For this to work, you need an interface with the following definition:
public interface ServerConnectivityListener {
void onCompleted(ServerConnectivity sender);
void onError(ServerConnectivity sender);
}
So, your ServerConnectivity class maintains a reference to some object that implements the interface called ServerConnectivityListener This allows you to maintain loose coupling between the subject class and any observers that need to listen for events.
Within ServerConnectivity, you would make calls to the listener's methods something like this:
// begin excerpt from above...
//
if(_topics == null || _notifications == null) {
_listener.onError(this);
} else {
_listener.onCompleted(this);
}
catch ( Exception e ){
System.out.println( e.toString() );
_listener.onError(this);
//
// end excerpt from above...
Here is code for splash screen in java........after and call that view.........
http://www.randelshofer.ch/oop/javasplash/javasplash.html
import java.awt.*;
import java.awt.event.*;
public class SplashTest extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(130,250,280,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 130, 260);
g.fillRect(130,270,(frame*10)%280,20);
}
public SplashTest() {
super("SplashScreen demo");
setSize(500, 300);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = (Graphics2D)splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(200);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
public static void main (String args[]) {
SplashTest test = new SplashTest();
}
}
Since,it is a thread based one,We cannot do it the normal way.So Check the following link
http://supportforums.blackberry.com/t5/Java-Development/What-is-the-Event-Thread/ta-p/446865
and Check whether parsing is done,Until that have the same screen,Check the condition of whehter it is downloaded or not ,and then push the screen

Resources