Special right-click-event in java - events

So, here's the scenario: I have a basic JTextField in a frame and want to give the user the option, to right click in the textfield and then, like in Eclipse or Microsoft Word, give him in a popup-menu the option to copy the text or paste text he already has created.
How do I make this special kind of right click event?
That's a short version of the program, I have so far:
import java.awt.*;
import javax.swing.*;
public class TestClass extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Main method
* #param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestClass window = new TestClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the window
*/
public TestClass() {
initialize();
}
/**
* Initialize components (TextField)
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 200, 100);
textField = new JTextField();
textField.setText("TextField");
textField.setFont(new Font("Arial", Font.PLAIN, 20));
frame.add(textField);
}
}

You should use Mouse Event to register an event for you then you must use a popupmenu to be popped up when you click so far here is an example code for you!
privatevoidformMouseClicked(java.awt.event.MouseEventevt){
if (evt.isPopupTrigger()){
pop.show(evt.getComponent(),evt.getX(), evt.getY());
}
}

private void textfiledMousePressed(java.awt. event.MouseEvent evt) {
if (evt.getModifiers() == MouseEvent.BUTTON3_MASK){
p.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
This can also be done for right click

Related

Drag and drop with JavaFX TreeView

I implemented Drag and Drop feature as recommended in other threads in this forum. I have a cellFactory on a TreeView and set the events on the cells.
tvProject.setCellFactory(new Callback<TreeView<PlanningItem>, TreeCell<PlanningItem>>() {
#Override
public PlanningCheckBoxTreeCell call(TreeView<PlanningItem> siTreeView) {
final PlanningCheckBoxTreeCell source = new PlanningCheckBoxTreeCell();
final PlanningCheckBoxTreeCell target = new PlanningCheckBoxTreeCell();
source.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture */
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();
}
});
target.setOnDragOver(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data is dragged over the target */
System.out.println("onDragOver");
...
event.consume();
}
});
The setOnDragDetected is executed/hit as wanted but all other events are NOT (I did not post them all here: setOnDragOver,setOnDragEntered,setOnDragExited,setOnDragDropped,setOnDragDone).
The PlanningCheckBoxTreeCell is a custom implementation of a treecell as follows:
public class PlanningCheckBoxTreeCell extends CheckBoxTreeCell<PlanningItem> {
public PlanningCheckBoxTreeCell() {
}
#Override
public void updateItem(PlanningItem item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(null);
}
}
}
UPDATE PlanningItem:
package at.v2c2.testplaygroundui;
import java.io.Serializable;
public class PlanningItem implements Serializable {
private static final long serialVersionUID = 1L;
private Double scene = null;
private Integer path = null;
private String move = null;
/**
* #return the scene
*/
public Double getScene() {
return scene;
}
/**
* #param scene the scene to set
*/
private void setScene(Double scene) {
this.scene = scene;
}
/**
* #return the path
*/
public Integer getPath() {
return path;
}
/**
* #param path the path to set
*/
private void setPath(Integer path) {
this.path = path;
}
/**
* #return the move
*/
public String getMove() {
return move;
}
/**
* #param move the move to set
*/
private void setMove(String move) {
this.move = move;
}
public PlanningItem(Object item) {
super();
if (item instanceof Double) {
setScene((Double) item);
} else if (item instanceof Integer) {
setPath((Integer) item);
} else if (item instanceof String) {
setMove((String) item);
}
}
}
UPDATE The MCVE:
package at.v2c2.testplaygroundui;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public final class TestplaygroundUi extends Application {
private final DataFormat objectDataFormat = new DataFormat("application/x-java-serialized-object");
/**
* Constructor.
*/
public TestplaygroundUi() {
// empty.
}
/**
* #param args Program arguments.
*/
public static void main(final String[] args) {
launch(args);
}
#Override
public void start(final Stage primaryStage) throws Exception {
TreeItem<PlanningItem> treeItemRoot = new TreeItem<>(new PlanningItem(1.0));
TreeItem<PlanningItem> nodeItemA = new TreeItem<>(new PlanningItem(2));
TreeItem<PlanningItem> nodeItemB = new TreeItem<>(new PlanningItem(2));
treeItemRoot.getChildren().addAll(nodeItemA, nodeItemB);
TreeItem<PlanningItem> nodeItemA1 = new TreeItem<>(new PlanningItem("A1"));
TreeItem<PlanningItem> nodeItemB1 = new TreeItem<>(new PlanningItem("B1"));
nodeItemA.getChildren().addAll(nodeItemA1);
nodeItemB.getChildren().addAll(nodeItemB1);
TreeView<PlanningItem> treeView = new TreeView<>(treeItemRoot);
treeView.setCellFactory(new Callback<TreeView<PlanningItem>, TreeCell<PlanningItem>>() {
#Override
public TreeCell<PlanningItem> call(TreeView<PlanningItem> siTreeView) {
final TreeCell<PlanningItem> cell = new TreeCell<>();
cell.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture */
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = cell.startDragAndDrop(TransferMode.MOVE);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.put(objectDataFormat, cell.getItem());
// content.putString("Hello");// cell.getText());
db.setContent(content);
event.consume();
}
});
cell.setOnDragOver(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data is dragged over the target */
System.out.println("onDragOver");
/*
* accept it only if it is not dragged from the same node and if it has a string data
*/
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
/* allow for both copying and moving, whatever user chooses */
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
});
cell.setOnDragEntered(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture entered the target */
System.out.println("onDragEntered");
/* show to the user that it is an actual gesture target */
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
// target.setFill(Color.GREEN);
}
event.consume();
}
});
cell.setOnDragExited(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
System.out.println("onDragExited");
/* mouse moved away, remove the graphical cues */
// target.setFill(Color.BLACK);
event.consume();
}
});
cell.setOnDragDropped(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data dropped */
System.out.println("onDragDropped");
/* if there is a string data on dragboard, read it and use it */
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
cell.setText(db.getString());
success = true;
}
/*
* let the source know whether the string was successfully transferred and used
*/
event.setDropCompleted(success);
event.consume();
}
});
cell.setOnDragDone(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture ended */
System.out.println("onDragDone");
/* if the data was successfully moved, clear it */
if (event.getTransferMode() == TransferMode.MOVE) {
cell.setText("");
}
event.consume();
}
});
return cell;
};
});
StackPane root = new StackPane();
root.getChildren().add(treeView);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.setTitle("Test TreeView");
primaryStage.show();
}
}
Thanks in advance

Panel background color won't change on menuitem mouse click

below is my code. It's fairly simple, just changing a panel color upon selecting one of three menu items, I think it's setup right(?) but it doesn't seem to be doing anything, also no errors. Any tips?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Joe
*/
public class menuframe extends javax.swing.JFrame {
/**
* Creates new form menuframe
*/
public menuframe() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
jMenu1.setText("Color");
jMenuItem1.setText("Red");
jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem1MouseClicked(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Green");
jMenuItem2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem2MouseClicked(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Blue");
jMenuItem3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem3MouseClicked(evt);
}
});
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {
panel.setBackground(Color.red);
}
private void jMenuItem2MouseClicked(java.awt.event.MouseEvent evt) {
panel.setBackground(Color.green);
}
private void jMenuItem3MouseClicked(java.awt.event.MouseEvent evt) {
panel.setBackground(Color.blue);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(menuframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(menuframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(menuframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(menuframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new menuframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JPanel panel;
// End of variables declaration
}

Image won't display in JFrame

I am trying to get an image to display inside my JFrame and having no success. I have followed the Oracle tutorial exactly and I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at net.ultibyte.TheDo.CreateLoginScreen.DisplayImage(CreateLoginScreen.java:35)
at net.ultibyte.TheDo.CreateLoginScreen.main(CreateLoginScreen.java:41)
Below is my code.
public class CreateLoginScreen extends JFrame {
CreateLoginScreen() {
setTitle("TheDo");
setSize(1280, 720);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static Image loadImage() {
Image i = null;
try {
i = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException e) {
}
return i;
}
public static void DisplayImage(Image i) {
Graphics g = i.getGraphics();
g.drawImage(i, 0, 0, null);
}
public static void main(String[] args) {
CreateLoginScreen a = new CreateLoginScreen();
DisplayImage(loadImage());
}
}
And the image is named "LoginScreen.png", and is located in a package called "resources" which is in the src folder.
I have no idea what's wrong and would very much appreciate any help :).
Update: Corrected file path, pointed out by peeskillet. This fixed the NullPointerException. Still won't display image though.
"located in a package called "resources" which is in the src folder."
You need to use this file path. "src/resources/LoginScreen.png"
Your IDE will first look in the main project folder. since src is direct child of the project root, you need to add that to the path
EDIT
"The window loads up but no image is displayed. Any idea on this? "
Yes, you need to override a paint method in order to draw the image on to the component. I wouldn't use JFrame though. I would use a JPanel and override the paintComponent method.
Try this out
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class JPanelTemplate extends JPanel {
private static final int SCREEN_WIDTH = 400;
BufferedImage img;
public JPanelTemplate() {
try {
img = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_WIDTH);
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JPanelTemplate());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

how to receive user data in a new window in javafx2

I want to show a new window by clicking (say )on a menu item. The new window would contain two TextFields and one cancel button and one Ok button. When user gives data in the text fields and press Ok then in the parent window i should receive the values given by the user.
How can i do this?
Please show me with an example code.
Thanks
here is the solution, you click window menu then click new window, new window opens with two text fields and ok and cancel button, I get the text value from first text field and display it in the parent window. Let me know if you have any questions, I used singleton design pattern along with MVC. Let me know if you have any questions to run the code.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
/**
*
* #author Burak Firik
*/
public class ButtonListener implements MouseListener{
String value;
public ButtonListener(String str){
value=str;
}
#Override
public void mouseClicked(MouseEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
MainFrame mainGUI=singleton.getGUI();
mainGUI.setLabelValue(inputFrame.getTextField1().getText());
mainGUI.repaint();
}
#Override
public void mousePressed(MouseEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(false);
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
And cancel button listener for the popup window
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Burak Firik
*/
public class CancelButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(false);
}
}
And inputFrame where the popup jframe will display two text fields and two button for OK and Cancel
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* #author Burak Firik
*/
public class InputFrame extends JFrame {
JTextField txt1;
JTextField txt2;
JButton btnOk;
JButton btnCancel;
public InputFrame(){
initGUI();
initHandlers();
}
void initGUI(){
this.setLayout(new BorderLayout());
this.setSize(300,300);
this.setLocation(200,200);
txt1=new JTextField(10);
txt2=new JTextField(10);
btnOk=new JButton("OK");
btnCancel=new JButton("Cancel");
JPanel northPanel=new JPanel();
northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
northPanel.add(txt1);
northPanel.add(txt2);
JPanel centerPanel=new JPanel();
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel.add(btnOk);
centerPanel.add(btnCancel);
add(northPanel,BorderLayout.NORTH );
add(centerPanel, BorderLayout.CENTER);
}
void initHandlers(){
ButtonListener btnListern=new ButtonListener(txt1.getText());
btnOk.addMouseListener(btnListern);
CancelButtonListener btnCancelListen=new CancelButtonListener();
btnCancel.addActionListener(btnCancelListen);
}
JFrame getInputFrame(){
return this;
}
JTextField getTextField1(){
return this.txt1;
}
JTextField getTextField2(){
return this.txt2;
}
public static void main(){
InputFrame frame=new InputFrame();
frame.setVisible(false);
}
}
mainframe where the newWindow ManuItem located;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
/**
*
* #author Burak Firik
*/
public class MainFrame extends JFrame{
private JMenuBar menuBar;
private JMenu menuWindow;
private JMenuItem menunewWindow;
private JLabel labelInputValue;
public MainFrame(){
this.setVisible(true);
this.setSize(300,300);
initGUI();
initHandlers();
}
private void initGUI() {
// Create the menu bar
this.setLayout(new BorderLayout());
menuBar = new JMenuBar();
menuWindow = new JMenu( "Window" );
menuWindow.setMnemonic( 'N' );
menuBar.add( menuWindow );
menunewWindow = CreateMenuItem( menuWindow, ITEM_PLAIN,
"New Window", null, 'N', null );
add(menuBar, BorderLayout.NORTH);
labelInputValue=new JLabel("SELAM");
add(labelInputValue, BorderLayout.CENTER);
}
public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
ImageIcon image, int acceleratorKey,
String sToolTip )
{
// Create the item
JMenuItem menuItem;
switch( iType )
{
case ITEM_RADIO:
menuItem = new JRadioButtonMenuItem();
break;
case ITEM_CHECK:
menuItem = new JCheckBoxMenuItem();
break;
default:
menuItem = new JMenuItem();
break;
}
// Add the item test
menuItem.setText( sText );
// Add the optional icon
if( image != null )
menuItem.setIcon( image );
// Add the accelerator key
if( acceleratorKey > 0 )
menuItem.setMnemonic( acceleratorKey );
// Add the optional tool tip text
if( sToolTip != null )
menuItem.setToolTipText( sToolTip );
// Add an action handler to this menu item
menu.add( menuItem );
return menuItem;
}
private final int ITEM_PLAIN = 0; // Item types
private final int ITEM_CHECK = 1;
private final int ITEM_RADIO = 2;
private void initHandlers() {
MenuListener menuListen=new MenuListener();
menunewWindow.addActionListener(menuListen);
}
public void setLabelValue(String str){
labelInputValue.setText(str);
this.repaint();
}
}
this class contains the singleton object it is very quick for lazy programmers :))
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
/**
*
* #author Burak Firik
*/
public class MainSingleton {
private static MainSingleton singleton=null;
private MainFrame gui;
private InputFrame inputGUI;
//private constructor for singleton design pattern
private MainSingleton(){}
public static MainSingleton getMainSingleton()
{
// ONLY CONSTRUCT THE SINGLETON THE FIRST TIME
if (singleton == null)
{
singleton = new MainSingleton();
}
// GET THE SINGLETON NO MATTER WHAT
return singleton;
}
public static void main(String[] args) {
MainSingleton mainFrame=MainSingleton.getMainSingleton();
mainFrame.init();
}
public void init(){
// INITALIZE THE GUI
gui = new MainFrame();
inputGUI=new InputFrame();
}
public void requestExit()
{
// WE MAY HAVE TO SAVE CURRENT WORK
boolean continueToExit = true;
// IF THE USER REALLY WANTS TO EXIT THE APP
if (continueToExit)
{
// EXIT THE APPLICATION
System.exit(0);
}
}
public MainFrame getGUI() { return gui; }
public InputFrame getinputGUI() { return inputGUI; }
}
this is the menu listener, when you click new Window this listener will be invoked.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
/**
*
* #author Burak Firik
*/
public class MenuListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(true);
}
}

how to add Zoom in/out functionality on bitmapfield?

I want to add functionality for the zoom in/out image that display by the bitmapfield.
I have search for this but couldn't get any useful tips for that,
can any one tell me how to add UI and functionality for the zooming image in/out.
Try this code
public final class ZoomScreenDemo extends UiApplication
{
public static void main(final String[] args)
{
// Create a new instance of the application and make the currently
// running thread the application's event dispatch thread.
UiApplication app = new ZoomScreenDemo();
app.enterEventDispatcher();
}
/**
* Creates a new ZoomScreenDemo object
*/
public ZoomScreenDemo()
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Click trackball or screen to zoom");
}
});
pushScreen(new ZoomScreenDemoScreen());
}
public final static class ZoomScreenDemoScreen extends MainScreen
{
private EncodedImage _image;
/**
* Creates a new ZoomScreenDemoScreen object
*/
public ZoomScreenDemoScreen()
{
setTitle("Zoom Screen Demo");
_image = EncodedImage.getEncodedImageResource("img/building.jpg");
BitmapField bitmapField = new BitmapField(_image.getBitmap(), FIELD_HCENTER | FOCUSABLE);
add(bitmapField);
}
/**
* #see Screen#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time)
{
// Push a new ZoomScreen if track ball or screen is clicked
UiApplication.getUiApplication().pushScreen(new ZoomScreen(_image));
return true;
}
/**
* #see Screen#touchEvent(TouchEvent)
*/
protected boolean touchEvent(TouchEvent message)
{
if(message.getEvent() == TouchEvent.CLICK)
{
UiApplication.getUiApplication().pushScreen(new ZoomScreen(_image));
}
return super.touchEvent(message);
}
}
}

Resources