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

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

Related

Increase JTextField number exists in another JFrame

So, if I click the button exists in First Frame, then the number would increase in JTextField exists in another Second Frame.
The First Frame contains the JButton and the Second Frame contains the JTextField.
Please Help.
Try below source code:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class FirstFrame extends JFrame {
private static final long serialVersionUID = 1L;
private SecondFrame secondFrame;
private boolean flag = new Boolean(false);
private volatile Integer number;
#SuppressWarnings("unused")
private SwingWorker<Void, Void> swingWorker;
public FirstFrame() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FirstFrame();
}
});
}
private void init() {
setTitle("First Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(2, 1));
setBounds(500, 300, 250, 110);
final JButton increaseBtn = new JButton("Increase Number");
final JButton start = new JButton("Start");
final JButton stop = new JButton("Stop");
stop.setEnabled(false);
JPanel panel = new JPanel();
increaseBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
if (!flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = true;
startContinuousIncreasing();
start.setEnabled(false);
stop.setEnabled(true);
increaseBtn.setEnabled(false);
}
});
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = false;
stop.setEnabled(false);
start.setEnabled(true);
increaseBtn.setEnabled(true);
}
});
getContentPane().add(increaseBtn);
getContentPane().add(panel);
panel.add(start);
panel.add(stop);
setVisible(true);
secondFrame = SecondFrame.getSecondFrame();
increaseBtn.requestFocus();
}
private void startContinuousIncreasing() {
swingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
while (flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
return null;
}
};
swingWorker.execute();
}
}
class SecondFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static Integer number;
private JTextField textField;
private static SecondFrame secondFrame;
private SecondFrame() {
init();
}
public synchronized static SecondFrame getSecondFrame() {
if (secondFrame == null)
secondFrame = new SecondFrame();
return secondFrame;
}
private void init() {
setTitle("Second Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1, 1));
setBounds(500, 412, 250, 70);
number = new Integer(0);
textField = new JTextField(String.valueOf(number));
textField.setFont(new Font("Dialog", Font.BOLD + Font.ITALIC, 22));
getContentPane().add(textField);
setVisible(true);
}
public synchronized Integer getNumber() {
return number;
}
public synchronized void setNumber(Integer num) {
try {
number = num;
this.textField.setText(String.valueOf(number));
} catch (NumberFormatException nfe) {
number = 0;
this.textField.setText(String.valueOf(number));
}
}
}
I guess you have created a Static variable. Static variables share the value across all instances of a class. That might be one of the answer.
Hopes it answered your questions. Let me know if it's not the answer. Yippee!!

Simple JavaFX Browser Only Works The First Time Its Opened

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.

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

Pressing Enter to Continue

I have a JDialog which has two fields, username and password. I want to make the form like normal ones in which pressing enter will be like pressing continue.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
than you have to invoke code for this button with method
JButton#doClick();
but better would be use KeyBindings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
private JButton okButton = new JButton("OK");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
okButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
okButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
startTimer();
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}
JButton button = ...
JTextField password = ...
ActionListener buttonListener = ...
button.addActionListner(buttonListener);
password.addActionListener(buttonListener);
When enter is pressed in a JTextField, an action event is fired.
You can achieve this by adding an action listener to your textfield, like so.
JTextField field1 = new JTextField();
field1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//here is your method to continue
continue();
}
});

Categories