Simple JavaFX Browser Only Works The First Time Its Opened - java

I have this code to open a custom Java browser:
private void openNavigator(){
Navigator browser = new Navigator();
SwingUtilities.invokeLater(() -> {
browser.initComponents();
browser.setVisible(true);
browser.loadURL("http://XXXXXXXX:8888/YYYYYY/ZZZZ");
});
}
In the other hand i have the code of the navigator:
public class Navigator extends JFrame {
private static final Logger LOG = Logger.getLogger(Navegador.class.getName());
private static final long serialVersionUID = -1951385676682823399L;
private WebView view;
private JFXPanel javaFxPanel;
private WebEngine engine;
private JLabel labelStatus;
private JTextField direction;
private JProgressBar progressBar;
private java.net.CookieManager cookiesManager;
public void initComponents() {
if (cookiesManager != null) {
cookiesManager = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cookiesManager);
}
javaFxPanel = new JFXPanel();
labelStatus = new JLabel();
JPanel panelTodo = new JPanel(new BorderLayout());
JButton botonBuscar = new JButton("Search");
direction = new JTextField();
progressBar = new JProgressBar();
createScene();
ActionListener direcctionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loadURL(direction.getText());
}
};
botonBuscar.addActionListener(direcctionListener);
direction.addActionListener(direcctionListener);
progressBar.setPreferredSize(new Dimension(150, 18));
progressBar.setStringPainted(true);
JPanel topBar = new JPanel(new BorderLayout(5, 0));
topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
topBar.add(direction, BorderLayout.CENTER);
topBar.add(botonBuscar, BorderLayout.EAST);
JPanel statusBar = new JPanel(new BorderLayout(5, 0));
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
statusBar.add(labelStatus, BorderLayout.CENTER);
statusBar.add(progressBar, BorderLayout.EAST);
panelTodo.add(topBar, BorderLayout.NORTH);
panelTodo.add(javaFxPanel, BorderLayout.CENTER);
panelTodo.add(statusBar, BorderLayout.SOUTH);
getContentPane().add(panelTodo);
setPreferredSize(new Dimension(1024, 600));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
}
private void createScene() {
Platform.runLater(() -> {
view = new WebView();
engine = view.getEngine();
engine.setOnAlert((WebEvent<String> wEvent) -> {
System.out.println("JS alert() message: " + wEvent.getData());
});
engine.titleProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Navegador.this.setTitle(newValue);
}
});
}
});
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
#Override
public void handle(final WebEvent<String> event) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
labelStatus.setText(event.getData());
}
});
}
});
engine.locationProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String viejoValor, final String nuevoValor) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
direction.setText(nuevoValor);
}
});
}
});
engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(newValue.intValue());
}
});
}
});
engine.getLoadWorker().exceptionProperty()
.addListener(new ChangeListener<Throwable>() {
#Override
public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
if (engine.getLoadWorker().getState() == FAILED) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//TODO Handling Exception
}
});
}
}
});
javaFxPanel.setScene(new Scene(view));
});
}
public void loadURL(String url) {
Platform.runLater(new Runnable() {
#Override
public void run() {
String urlTemporal = toURL(url);
if (urlTemporal == null) {
urlTemporal = toURL("http://" + url);
}
engine.load(urlTemporal);
}
});
}
private static String toURL(String str) {
try {
return new URL(str).toExternalForm();
} catch (MalformedURLException exception) {
return null;
}
}
}
My problem is that when i open the navigator for the first time it works , but when i close it and then open again it only shows the TextField and the Button
Notes:
I use a javaswing button to open the navigator whit the
openNavigator() method
When i left one Navigator without closing and at the same time i
open one or more Navigators it works perfectly
First time I open the Navigator:
Second time I open the Navigator:

The JavaFX thread/toolkit must be running. Apparently, creating a JFXPanel is enough to initialize it, but once it is closed the thread is terminated automatically.
To stop it from automatically closing call
Platform.setImplicitExit(false);
so the JavaFX toolkit only closes when the Platform#exit method is called, or the entire application terminates.

Related

How can I display a JavaFX Browser in a Java JPanel application?

Good Community I am making an app and I am working with a java browser googlemap and I want to show it in a panel or in another element where it is displayed (JLabel, JPanel, etc).
I made a project in java-> javaAplication-> a form -> with a button. This is the method I am calling on the button.
locate ();
I want to display it in a JPanel not in an FXPanel like this now:
private void locate() {
String a = txtMapaBuscador.getText().replace(" ", "+");
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
frame.setVisible(true);
final JFXPanel fxpanel = new JFXPanel();
frame.add(fxpanel);
Platform.runLater(new Runnable() {
#Override
public void run() {
WebEngine engine;
WebView wv = new WebView();
engine = wv.getEngine();
fxpanel.setScene(new Scene(wv));
engine.load("https://www.google.com/maps/place/" + a);
}
});
}
This is my friend's code but I can't understand it.
package simpleswingbrowser;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import static javafx.concurrent.Worker.State.FAILED;
public class SimpleSwingBrowser extends JFrame {
private final JFXPanel jfxPanel = new JFXPanel();
private WebEngine engine;
private final JPanel panel = new JPanel(new BorderLayout());
private final JLabel lblStatus = new JLabel();
private final JButton btnGo = new JButton("Go");
private final JTextField txtURL = new JTextField();
private final JProgressBar progressBar = new JProgressBar();
public SimpleSwingBrowser() {
super();
initComponents();
}
private void initComponents() {
createScene();
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loadURL(txtURL.getText());
}
};
btnGo.addActionListener(al);
txtURL.addActionListener(al);
progressBar.setPreferredSize(new Dimension(150, 18));
progressBar.setStringPainted(true);
JPanel topBar = new JPanel(new BorderLayout(5, 0));
topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
topBar.add(txtURL, BorderLayout.CENTER);
topBar.add(btnGo, BorderLayout.EAST);
JPanel statusBar = new JPanel(new BorderLayout(5, 0));
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
statusBar.add(lblStatus, BorderLayout.CENTER);
statusBar.add(progressBar, BorderLayout.EAST);
panel.add(topBar, BorderLayout.NORTH);
panel.add(jfxPanel, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.SOUTH);
getContentPane().add(panel);
setPreferredSize(new Dimension(1024, 600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
private void createScene() {
Platform.runLater(new Runnable() {
#Override
public void run() {
WebView view = new WebView();
engine = view.getEngine();
engine.titleProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SimpleSwingBrowser.this.setTitle(newValue);
}
});
}
});
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
#Override
public void handle(final WebEvent<String> event) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
lblStatus.setText(event.getData());
}
});
}
});
engine.locationProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
txtURL.setText(newValue);
}
});
}
});
engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(newValue.intValue());
}
});
}
});
engine.getLoadWorker()
.exceptionProperty()
.addListener(new ChangeListener<Throwable>() {
#Override
public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
if (engine.getLoadWorker().getState() == FAILED) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(
panel,
(value != null)
? engine.getLocation() + "\n" + value.getMessage()
: engine.getLocation() + "\nUnexpected error.",
"Loading error...",
JOptionPane.ERROR_MESSAGE);
}
});
}
}
});
jfxPanel.setScene(new Scene(view));
}
});
}
public void loadURL(final String url) {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
private static String toURL(String str) {
try {
return new URL(str).toExternalForm();
} catch (MalformedURLException exception) {
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SimpleSwingBrowser browser = new SimpleSwingBrowser();
browser.setVisible(true);
browser.loadURL("http://oracle.com");
}
});
}
}
Add a JPanel pnlViewMap in my frame and put BorderLayout and the map appeared
pnlViewMapa.add(fxpanel,BorderLayout.CENTER);
Platform.runLater(new Runnable() {
#Override
public void run() {
WebEngine engine;
WebView wv = new WebView();
engine = wv.getEngine();
fxpanel.setScene(new Scene(wv));
engine.load("https://www.google.com/maps/place/" + a);
}
});

How to start and stop a threads in netbeans from a jButton click

I write Java desktop app to fetch and post some data from my online rails backend app. The App have to call a get request every 5 second to update the relay state(example Arduino). here is my code:
public class GUI extends javax.swing.JFrame {
private Serial serial = null;
private Service service = null;
private volatile boolean connected = false;
private Thread updateThread;
public GUI() {
initComponents();
init_serial();
service = new Service();
updateThread = new Thread() {
public void run() {
while (connected) {
updateJob();
}
}
};
updateThread.start();
}
private void init_serial() {
serial = new Serial();
serial.searchForPorts();
serial.connect();
serial.initIOStream();
serial.initListener();
}
private void updateJob() {
ActionListener actListner = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
updateState();
}
};
Timer timer = new Timer(5000, actListner);
timer.start();
}
private void updateState() {
String portState = service.get_port_state();
serial.write(portState);
System.out.println(portState);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
connected = true;
logger.setText(null);
logger.setText("connected");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
logger.setText(null);
logger.setText("disconnected");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
}
but it didn't work as expected, my question is how can i fix my code and how to put the thread correctly?
You can use a Thread object in class's member and you can start and stop in button click action events. Here is the sample to start/stop thread.
public class GUI extends javax.swing.JFrame {
Thread updateThread = null;
public GUI() {
JButton btnStart = new JButton("Start");
JButton btnStop = new JButton("Stop");
JPanel jPanel = new JPanel();
jPanel.setBounds(0, 0, 100, 200);
jPanel.add(btnStart);
jPanel.add(btnStop);
add(jPanel);
btnStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
System.out.println("Work updated");
try {
Thread.sleep(1000);//Time to wait for next routine
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
updateThread.start();
}
});
btnStop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateThread.stop();
}
});
setVisible(true);
setBounds(0, 0, 100, 200);
}
public static void main(String[] args) {
new GUI();
}
}
You can possibly use thread.join();

Overriding the process() Method in SwingWorker

I'm trying to dynamically update the GUI with a String. Can anyone see why the process method is not overriding correctly? I've looked at other questions and still cannot see how I am not overriding this correctly.
public class WorkerDemo extends JFrame {
private JLabel counterLabel = new JLabel("Not started");
private Worker worker = new Worker();
private JButton startButton = new JButton(new AbstractAction("Start") {
#Override
public void actionPerformed(ActionEvent arg0) {
worker = new Worker();
worker.execute();
}
});
private JButton stopButton = new JButton(new AbstractAction("Stop") {
#Override
public void actionPerformed(ActionEvent arg0) {
worker.cancel(true);
}
});
public WorkerDemo() {
add(startButton, BorderLayout.WEST);
add(counterLabel, BorderLayout.CENTER);
add(stopButton, BorderLayout.EAST);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
class Worker extends SwingWorker<Void, Integer> {
int counter = 0;
String abc = "abc";
#Override
protected Void doInBackground() throws Exception {
while(true) {
abc += abc;
publish(abc);
Thread.sleep(60);
}
}
#Override
protected void process(List<Object> chunk) {
// get last result
String to_return = (String) chunk.get(chunk.size()-1);
counterLabel.setText(to_return);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new WorkerDemo();
}
});
}
}
Since you have SwingWorker<Void, Integer>, you have defined Integer as a type to carry out intermediate results by publish and process methods. That means proper publish() and process() methods should use Integer:
#Override
protected Void doInBackground() throws Exception {
int someResult = 0;
...
publish(someResult);
...
}
#Override
protected void process(List<Integer> chunk) {
}
See SwingWorker for more details.

How to use executeScript called by javascript (bridge) in webview (javaFX)

I have this class:
public Palco() {
super();
initComponents();
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
}
private void initComponents() {
createScene();
progressBar.setPreferredSize(new Dimension(150, 18));
progressBar.setStringPainted(true);
JPanel topBar = new JPanel(new BorderLayout(5, 0));
topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
topBar.add(txtURL, BorderLayout.CENTER);
topBar.add(btnGo, BorderLayout.EAST);
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
statusBar.add(lblStatus, BorderLayout.CENTER);
statusBar.add(progressBar, BorderLayout.EAST);
//panel.add(topBar, BorderLayout.NORTH);
panel.add(jfxPanel, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.SOUTH);
getContentPane().add(panel);
setTitle("My App");
setPreferredSize(new Dimension(1024, 600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
private void createScene() {
Platform.runLater(new Runnable() {
public void run() {
WebView view = new WebView();
engine = view.getEngine();
engine.setJavaScriptEnabled(true);
engine.titleProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
String title = null;
public void run() {
if(newValue == null){
title = "Carregando...";
} else {
title = newValue;
}
Palco.this.setTitle(title);
}
});
}
});
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
public void handle(final WebEvent<String> event) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// lblStatus.setText(event.getData());
}
});
}
});
engine.locationProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
txtURL.setText(newValue);
}
});
}
});
engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(newValue.intValue() < 100){
statusBar.setVisible(true);
} else {
statusBar.setVisible(false);
}
progressBar.setValue(newValue.intValue());
}
});
}
});
engine.documentProperty().addListener(new ChangeListener<Document>() {
public void changed(ObservableValue<? extends Document> prop, Document oldDoc, Document newDoc) {
MainTiles tiles = new MainTiles(engine);
tiles.ShowCategory(0);
}
});
engine.getLoadWorker()
.exceptionProperty()
.addListener(new ChangeListener<Throwable>() {
public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
if (engine.getLoadWorker().getState() == FAILED) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(
panel,
(value != null) ?
engine.getLocation() + "\n" + value.getMessage() :
engine.getLocation() + "\nUnexpected error.",
"Loading error...",
JOptionPane.ERROR_MESSAGE);
}
});
}
}
});
engine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
#Override
public void changed(ObservableValue<? extends State> ov,
State oldState, State newState) {
JSObject jsobj = (JSObject) engine.executeScript("window");
jsobj.setMember("java", new Bridge());
}
}
);
jfxPanel.setScene(new Scene(view));
}
});
}
public void loadURL(final String url) {
Platform.runLater(new Runnable() {
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
private static String toURL(String str) {
try {
return new URL(str).toExternalForm();
} catch (MalformedURLException exception) {
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Palco browser = new Palco();
browser.setVisible(true);
String url = getClass().getResource("html/index.html").toExternalForm();
browser.loadURL(url);
}
});
}
public static void changeScene(){
}
And I wanted execute the command executeScript in JavaScript (bridge) callback <a onclick="java.link()">teste</a>, but I dont know how pass the webview (WebView.getEngine) in class Bridge:
public void link(){
executeScript(engine, "document.getElementById('main').innerHTML = 'test';"); // engine is WebView
}
Does anyone know if it is possible or how to do?
Sorry my english is very bad =/, I'm Brazilian!
Thanks
You could it pass it via a constructor, it's a normal Java object which can be shared, i.e.
public class Bridge{
WebEngine engine; // add a new field
public Bridge(WebEngine engine){
this.engine = engine;
}
}
// ...
JSObject jsobj = (JSObject) engine.executeScript("window");
jsobj.setMember("java", new Bridge(engine)); // pass it here

JTextField is not editable in a JPopupMenu

When I add a JtextField in a JPopupMenu, I can't edit the text when the popup is displayed. Anyone know why?
Here's a code example:
public static void main(String[] args) {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JTextField field = new JTextField("My text");
popup.insert(field, 0);
popup.setVisible(true);
}
Seems to work alright for me:
Check out this example (right click anywhere on the content pane to make the popup visible:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Main {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popup = new JPopupMenu();
final JTextField field = new JTextField(20);
field.setText("My text");
popup.insert(field, 0);
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field.requestFocusInWindow();
field.selectAll();
}
});
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
((JComponent) frame.getContentPane()).setComponentPopupMenu(popup);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().initUI();
}
});
}
}
to avoiding any speculations
I can't edit the text when the popup is displayed. Anyone know why?
JPopup nested JPopupMenu must has a parent, my code example (reason why is there hardcodes frame.setLocation(150, 100);)
in this form works correctly, JPopup accepting JFrames coordinates
change this code inside Swing Action
from
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
to
popupMenu.setVisible(true);
//popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
then PopupMenuListener firing and events, but JMenuItems aren't repainted too
from code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PopupSample {
private JPopupMenu popupMenu = new JPopupMenu();
private javax.swing.Timer timer = null;
private JFrame frame = new JFrame("Popup Example");
public PopupSample() {
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: "
+ actionEvent.getActionCommand());
}
};
PopupMenuListener popupMenuListener = new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
};
popupMenu.addPopupMenuListener(popupMenuListener);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setPreferredSize(new Dimension(2, 100));
jSeparator.setBackground(Color.red);
popupMenu.add(jSeparator);
JMenuItem cutMenuItem = new JMenuItem("Cut");
cutMenuItem.addActionListener(actionListener);
popupMenu.add(cutMenuItem);
cutMenuItem.setBorder(null);
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.addActionListener(actionListener);
popupMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.addActionListener(actionListener);
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
findMenuItem.addActionListener(actionListener);
popupMenu.add(findMenuItem);
JTextField text = new JTextField("text");
popupMenu.add(text);
MouseListener mouseListener = new JPopupMenuShower(popupMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(mouseListener);
frame.setLocation(150, 100);
frame.setSize(350, 250);
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(1000, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
}
});
}
};
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
PopupSample popupSample = new PopupSample();
}
});
}
static class JPopupMenuShower extends MouseAdapter {
private JPopupMenu popup;
public JPopupMenuShower(JPopupMenu popup) {
this.popup = popup;
}
private void showIfPopupTrigger(MouseEvent mouseEvent) {
if (popup.isPopupTrigger(mouseEvent)) {
popup.show(mouseEvent.getComponent(), mouseEvent.getX(),
mouseEvent.getY());
}
}
#Override
public void mousePressed(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
#Override
public void mouseReleased(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
}
}

Categories