Panel background color won't change on menuitem mouse click - panel

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
}

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

Camera not initialization issue with rpi3 camera v2 on Android Things

I am trying to run a simple Android Thing project that simply captures and renders the captured image in the display. I took the sample code from (https://github.com/googlecodelabs/androidthings-imageclassifier/tree/master/imageclassifier-add-camera) without the image recognition part. But I'm getting the following error-
I/InstantRun: starting instant run server: is main process
I/CameraManagerGlobal: Connecting to camera service
D/CameraHandler: Using camera id 0
W/CameraHandler: Cannot capture image. Camera not initialized.
D/CameraHandler: Opened camera.
So it seems it detects the camera but it can't capture images from the camera. Anyone faced similar issues on AndroidThings platform?
Main Camera Handler code provided below-
public class CameraHandler {
private static final String TAG = CameraHandler.class.getSimpleName();
public static final int IMAGE_WIDTH = 320;
public static final int IMAGE_HEIGHT = 240;
private static final int MAX_IMAGES = 1;
private CameraDevice mCameraDevice;
private CameraCaptureSession mCaptureSession;
/**
* An {#link android.media.ImageReader} that handles still image capture.
*/
private ImageReader mImageReader;
// Lazy-loaded singleton, so only one instance of the camera is created.
private CameraHandler() {
}
private static class InstanceHolder {
private static CameraHandler mCamera = new CameraHandler();
}
public static CameraHandler getInstance() {
return InstanceHolder.mCamera;
}
/**
* Initialize the camera device
*/
public void initializeCamera(Context context,
Handler backgroundHandler,
ImageReader.OnImageAvailableListener imageAvailableListener) {
// Discover the camera instance
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] camIds = {};
try {
camIds = manager.getCameraIdList();
} catch (CameraAccessException e) {
Log.d(TAG, "Cam access exception getting IDs", e);
}
if (camIds.length < 1) {
Log.d(TAG, "No cameras found");
return;
}
String id = camIds[0];
Log.d(TAG, "Using camera id " + id);
// Initialize the image processor
mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
ImageFormat.JPEG, MAX_IMAGES);
mImageReader.setOnImageAvailableListener(
imageAvailableListener, backgroundHandler);
// Open the camera resource
try {
manager.openCamera(id, mStateCallback, backgroundHandler);
} catch (CameraAccessException cae) {
Log.d(TAG, "Camera access exception", cae);
}
}
/**
* Callback handling device state changes
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
Log.d(TAG, "Opened camera.");
mCameraDevice = cameraDevice;
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
Log.d(TAG, "Camera disconnected, closing.");
closeCaptureSession();
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int i) {
Log.d(TAG, "Camera device error, closing.");
closeCaptureSession();
cameraDevice.close();
}
#Override
public void onClosed(#NonNull CameraDevice cameraDevice) {
Log.d(TAG, "Closed camera, releasing");
mCameraDevice = null;
}
};
/**
* Begin a still image capture
*/
public void takePicture() {
if (mCameraDevice == null) {
Log.w(TAG, "Cannot capture image. Camera not initialized.");
return;
}
// Here, we create a CameraCaptureSession for capturing still images.
try {
mCameraDevice.createCaptureSession(
Collections.singletonList(mImageReader.getSurface()),
mSessionCallback,
null);
} catch (CameraAccessException cae) {
Log.d(TAG, "access exception while preparing pic", cae);
}
}
/**
* Callback handling session state changes
*/
private CameraCaptureSession.StateCallback mSessionCallback =
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (mCameraDevice == null) {
return;
}
// When the session is ready, we start capture.
mCaptureSession = cameraCaptureSession;
triggerImageCapture();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Log.w(TAG, "Failed to configure camera");
}
};
/**
* Execute a new capture request within the active session
*/
private void triggerImageCapture() {
try {
final CaptureRequest.Builder captureBuilder =
mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
//captureBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
Log.d(TAG, "Capture request created.");
mCaptureSession.capture(captureBuilder.build(), mCaptureCallback, null);
} catch (CameraAccessException cae) {
Log.d(TAG, "camera capture exception");
}
}
/**
* Callback handling capture session events
*/
private final CameraCaptureSession.CaptureCallback mCaptureCallback =
new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureProgressed(#NonNull CameraCaptureSession session,
#NonNull CaptureRequest request,
#NonNull CaptureResult partialResult) {
Log.d(TAG, "Partial result");
}
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session,
#NonNull CaptureRequest request,
#NonNull TotalCaptureResult result) {
session.close();
mCaptureSession = null;
Log.d(TAG, "CaptureSession closed");
}
};
private void closeCaptureSession() {
if (mCaptureSession != null) {
try {
mCaptureSession.close();
} catch (Exception ex) {
Log.e(TAG, "Could not close capture session", ex);
}
mCaptureSession = null;
}
}
/**
* Close the camera resources
*/
public void shutDown() {
closeCaptureSession();
if (mCameraDevice != null) {
mCameraDevice.close();
}
}
}
The pitfall with camera:
Check the permissions in Manifest file, and restart the device.
The camera-permission is granted not after installing the application, but first after install and RESTART of device.
see https://developer.android.com/things/sdk/index.html

isSelected method for jRadioButton doesnt work

my isSelected method for the radio buttons are not working, even if i select them when i run the program, i am new to java gui coding so plz explain according to that, i am posting the whole gui's class code.And i am using eclipse swing designer
public class gui {
private JFrame frame;
private final ButtonGroup buttonGroup = new ButtonGroup();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws FileNotFoundException
*/
public gui() throws FileNotFoundException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws FileNotFoundException
*/
private void initialize() throws FileNotFoundException {
FileReader reader=new FileReader("C:\\Users\\kkj\\workspace\\javaproject\\src\\Database.txt");
Scanner in=new Scanner(reader);
BList Restaurant=new BList();
BList ATM=new BList();
BList Hospital=new BList();
BList Hotels=new BList();
BList Petrol=new BList();
final Llist locations=new Llist();
System.out.println("Loading");
while(in.hasNextLine())
{
BNode bnode=new BNode();
bnode.name=in.nextLine();
//System.out.println(bnode.name);
String type=in.nextLine();
bnode.loc=in.nextLine();
if(type.equals("Restaurant"))
{
Restaurant.insert(bnode);
}
if(type.equals("ATM"))
{
ATM.insert(bnode);
}
if(type.equals("Hospital"))
{
Hospital.insert(bnode);
}
if(type.equals("Hotels"))
{
Hotels.insert(bnode);
}
if(type.equals("Petrol"))
{
Petrol.insert(bnode);
}
}
FileReader reader2=new FileReader("C:\\Users\\kkj\\workspace\\javaproject\\src\\locations.txt");
Scanner inL=new Scanner(reader2);
int s=0;
while(inL.hasNextLine())
{
LNode loc=new LNode();
loc.Name=inL.nextLine();
loc.dist=s++;
BNode temp;
temp=Restaurant.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.rest=temp;break;}
temp=temp.next;
}
temp=Hospital.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.Hospital=temp;break;}
temp=temp.next;
}
temp=Hotels.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.Hotels=temp;break;}
temp=temp.next;
}
//loc.hotels=temp;
temp=ATM.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.ATM=temp;break;}
temp=temp.next;
}
locations.insert(loc);
}
System.out.println("Loaded");
System.out.println(">>>>>>>>>>>Restaurants<<<<<<<<<<<<");
Restaurant.disp();
System.out.println(">>>>>>>>>>>Hotels<<<<<<<<<<<<");
Hotels.disp();
System.out.println(">>>>>>>>>>>Hospital<<<<<<<<<<<<");
Hospital.disp();
System.out.println(">>>>>>>>>>>ATM's<<<<<<<<<<<<");
ATM.disp();
System.out.println(">>>>>>>>>>>Locations<<<<<<<<<<<<");
locations.disp();
final String curr="Bsk";
String locin;
final String typein="Hospital";
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JRadioButton rdbtnBsk = new JRadioButton("Bsk");
buttonGroup.add(rdbtnBsk);
rdbtnBsk.setBounds(26, 35, 109, 23);
frame.getContentPane().add(rdbtnBsk);
JRadioButton rdbtnKoramangala = new JRadioButton("Koramangala");
buttonGroup.add(rdbtnKoramangala);
rdbtnKoramangala.setBounds(26, 72, 109, 23);
frame.getContentPane().add(rdbtnKoramangala);
JRadioButton rdbtnMgRoad = new JRadioButton("MG Road");
buttonGroup.add(rdbtnMgRoad);
rdbtnMgRoad.setBounds(26, 125, 109, 23);
frame.getContentPane().add(rdbtnMgRoad);
if(rdbtnBsk.isSelected())
{
locin="Bsk";
}
if(rdbtnKoramangala.isSelected())
{
locin="Koramangala";
}
if(rdbtnMgRoad.isSelected())
{
locin="MG Road";
}
else System.exit(2);
final String locinn=locin;
JButton btnOutput = new JButton("output");
btnOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
Output out1=new Output();
System.out.println(">>>>>>>>>>>"+typein+" in "+locinn+"<<<<<<<<<<<<");
out1.display(locations, locinn, typein,curr);
}
});
btnOutput.setBounds(182, 193, 89, 23);
frame.getContentPane().add(btnOutput);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "SwingAction");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Am also new to Java Programming, but this might work, it worked for me.
Put the whole if/else block inside the actionPerformed() method of the "output" Button, like this :
JButton btnOutput = new JButton("output");
btnOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{ if(rdbtnBsk.isSelected())
{
locin="Bsk";
}
else if(rdbtnKoramangala.isSelected())
{
locin="Koramangala";
}
else if(rdbtnMgRoad.isSelected())
{
locin="MG Road";
}
final String locinn=locin;
Output out1=new Output();
System.out.println(">>>>>>>>>>>"+typein+" in "+locinn+"<<<<<<<<<<<<");
out1.display(locations, locinn, typein,curr);
}
});
btnOutput.setBounds(182, 193, 89, 23);
frame.getContentPane().add(btnOutput);
}

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);
}
}

Special right-click-event in java

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

Resources