how to call this code from gui(jframe) - java

i wanna to call youtubeviewer from a window by actionlistener
public class YouTubeViewer {
public YouTubeViewer(){
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("YouTube Viewer");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(getBrowserPanel(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
NativeInterface.runEventPump();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
NativeInterface.close();
}
}));
}
public JPanel getBrowserPanel() {
JPanel webBrowserPanel = new JPanel(new BorderLayout());
JWebBrowser webBrowser = new JWebBrowser();
webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
webBrowser.setBarsVisible(false);
webBrowser.navigate("www.youtube.com/embed/sKeCX98U29M");
return webBrowserPanel;
}
}
jframe example(for testing)
public class trailerPlayer extends JPanel implements ActionListener
{
private JButton press;
public trailerPlayer ()
{
setLayout(new BorderLayout());
press = new JButton("press");
press.addActionListener(this);
add(press);
}
public void actionPerformed(ActionEvent actionEvent)
{
YouTubeViewer a = new YouTubeViewer();
}
public static void main(String args[ ])
{
trailerPlayer p = new trailerPlayer();
JFrame test = new JFrame();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.add(p);
test.setSize(500,500);
test.setVisible(true);
}
}
YouTubeViewer include class of DJ Native Swing api library.
if i call directly by main function,it will work.but if i call from actionlistener it will stop responding at the time i press it~ i guess it is the problem of running issue~ how to solve ? any idea? thanks
any idea??

Your code blocks the EDT (NativeInterface.runEventPump();). So you should do it in a different thread.
public void actionPerformed(ActionEvent actionEvent)
{
Thread t = new Thread(new Runnable() {
public void run() {
YouTubeViewer a = new YouTubeViewer();
}
});
t.start();
}

Related

java GUI Form open other form onclick button

I am trying to do when clicked button from form1 open form2. Its sounds very simple but i coudnt find any way to do this.I am using java intellij.
When i use netbeans and swing i was doing this with :
"Form2 form2=new Form2();
form2.setVisible(true);
dispose(); "
Form1(Main):
public class Main {
private JButton b_show;
private JButton b_Add;
private JPanel jp_main;
public Main() {
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
form2(Show):
public class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
Show show=new Show();
geriButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Show().jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
is any one can help me ?
when click b_show open form2(Show).
Here is an mcve demonstrating it
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
private final JButton b_show;
private final JPanel jp_main;
public Main() {
jp_main = new JPanel();
b_show = new JButton("Show");
b_show.addActionListener(actionEvent -> {
new Show();
});
jp_main.add(b_show);
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
createAndShowGui();
}
void createAndShowGui(){
JFrame frame=new JFrame();
frame.setLocationRelativeTo(null);
jpanelmain = new JPanel();
b_back = new JButton("Back");
jpanelmain.add(b_back);
frame.setContentPane(jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
However, please read The Use of Multiple JFrames: Good or Bad Practice?
The best way to do this would be using JDialogs. When actionPerformed() at 'Form1' is called, you would instantiate a new JDialog and set him visible. Here is an example:
public class Show extends JDialog {
private JButton b_back;
public JPanel jpanelmain;
public Show(Frame owner, boolean modal) {
super(owner, modal);
}
//method that creates the GUI
}
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
Show show = new Show(JOptionPane.getFrameForComponent(this), true);
show.setVisible(true);
}
});
Finally, when you want to close the dialog, implement an actionPerformed() in it, and call the dispose() method

Closing JFrame with Button

I am currently using Eclipse's drag and Drop feature, I have one application window which comes with JFrame by default and is able to setVisible(false); but my other frames/panel/window I have created with JPanel and with extending JFrame.
Because of extend I am unable to setVisible(false or true); it has no effect at all on the window it still remains true.
My code :
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
.
.
. so on
Here I am trying to execute my button:
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(false);
}
});
Any solutions for it?
Because you're creating the frame inside the Runnable, its scope is limited to that of the runnable. Try declaring the variable outside of the runnable, then initializing it within the runnable, like so:
private JPanel contentPane;
private LibrarianMenu frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Then setvisible to false without declaring a new instance of LibrarianMenu:
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
This is happening because every time you press the button you create a new instance of that frame. Here is your code updated :
static LibrarianMenu frame ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the logout button event should be like this :
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});

Running JUnit Tests in a Swing GUI using Swing Worker

I'm writing a GUI that is able to perform some JUnit Tests and to handle this I have used a SwingWorker.
When I start the program the GUI comes up and I click through some selections and the SwingWorker initiates and does it's part and finally outputs either a console output or file output. Then I would click through the GUI again and start another test. At this point when the program finishes it would generate the final output twice, e.g. the console output would be followed directly by an identical console output.
I am assuming this is due to the SwingWorker not terminating and "dying".
Also I am creating the SwingWorker when I click a "start" button in the GUI. Is this a bad idea and what would the proper way to do it be instead?
EDIT Added code sample
public class TestMainFrame {
private static JFrame frame;
private static JTextArea textArea;
public TestMainFrame(){
createAndShowGUI();
}
private void createAndShowGUI() {
frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
JButton btn = new JButton("Test Me");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(btn.getText().equals("Test Me")){
testMe();
}
}
});
textArea = new JTextArea("This is a test pane! \n");
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
frame.add(scroller, BorderLayout.CENTER);
frame.add(btn, BorderLayout.PAGE_END);
frame.setSize(new Dimension(300, 400));
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static void testMe(){
writeToTextArea("Button Pressed");
writeToTextArea("Starting tests");
SwingWorker<Result, Void> worker = new SwingWorker<Result, Void>() {
#Override
public Result doInBackground() {
writeToTextArea("Inside the doInBackground method of SwingWorker");
return null;
}
#Override
public void done() {
writeToTextArea("The SwingWorker has finished");
}
};
worker.execute();
}
private static void writeToTextArea(String text){
textArea.append(text + "\n");
}
(Not an answer)
This is how I ran your code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestMainFrame {
private static JFrame frame;
private static JTextArea textArea;
public TestMainFrame() {
createAndShowGUI();
}
private void createAndShowGUI() {
frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
final JButton btn = new JButton("Test Me");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (btn.getText().equals("Test Me")) {
testMe();
}
}
});
textArea = new JTextArea("This is a test pane! \n");
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
frame.add(scroller, BorderLayout.CENTER);
frame.add(btn, BorderLayout.PAGE_END);
frame.setSize(new Dimension(300, 400));
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static void testMe() {
writeToTextArea("Button Pressed");
writeToTextArea("Starting tests");
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
public Void doInBackground() {
writeToTextArea("Inside the doInBackground method of SwingWorker");
return null;
}
#Override
public void done() {
writeToTextArea("The SwingWorker has finished");
}
};
worker.execute();
}
// *** note change ***
private static void writeToTextArea(final String text) {
if (SwingUtilities.isEventDispatchThread()) {
textArea.append(text + "\n");
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text + "\n");
}
});
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestMainFrame testMainFrame = new TestMainFrame();
testMainFrame.createAndShowGUI();
}
});
}
}

Closing and reopeing of frame happens with increasing frequency each a button is pressed a single time

I am using a self made toolbar to navigate through my application and the toolbar is present on all pages. Each time a new page is displayed I am closing the current frame and opening a new one, using the following code:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
I am doing it this way as the ActionListeners are declared in the toolbar class, whilst the frames for each page are declared at runtime and are not static.
This all works fine except for one particular case-the "cancel" button, where the first time the frame is accessed it will close once. The second time it will close and re open 2 times, the third 3 and so on. I have tracked this using the "counter" in the code.
I have minimised the code to recreate the same behaviour, as below:
Toolbar Class
public class Toolbar {
static JButton buttonCancel = new JButton("Cancel");
static int counter;
public static JPanel Toolbar(String panelname){
FlowLayout layout = new FlowLayout();
JPanel Toolbar = new JPanel(new BorderLayout());
Toolbar.setLayout(layout);
GridLayout GLayout = new GridLayout(2,1);
GLayout.setVgap(0);
JPanel container2 = new JPanel();
if(panelname.matches("Customers")){
container2.setLayout(GLayout);
JButton buttonAddCust = new JButton("Add Cust");
container2.add(buttonAddCust, BorderLayout.PAGE_START);
buttonAddCust.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
Customers.AddCustomersGui();
}
});
}
JPanel container21 = new JPanel();
if(panelname.matches("Add Customers")){
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter ++;
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
}
Toolbar.add(container2);
Toolbar.add(container21);
return Toolbar;
}
}
GUI class
public class Customers extends Toolbar{
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(Toolbar.Toolbar(frame.getTitle()));
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void AddCustomersGui(){
final JFrame frame1 = new JFrame("Add Customers");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Addcustomers = new JPanel();
Addcustomers.add(Toolbar.Toolbar(frame1.getTitle()));
frame1.setContentPane(Addcustomers);
frame1.setSize(1200,500);
frame1.setVisible(true);
}
}
main class
public static void main(String[] args) {
Customers.CustomersGui();
}
You are adding a new ActionListener to the buttonCancel, with each iteration of your code and this is the reason for your program's behavior.
Also, as per my comment, you state,
Each time a new page is displayed I am closing the current frame and opening a new one.
A better design is probably not to swap windows which can be annoying, but rather to swap JPanel views using a CardLayout. Please read The Use of Multiple JFrames, Good/Bad Practice?.
For example, add this line of code to your program:
if (panelname.matches("Add Customers")) {
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
java.awt.Window win[] = java.awt.Window.getWindows();
for (int i = 0; i < win.length; i++) {
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
// ***** add this here **********
System.out.println("buttonCancel ActionListener count: "
+ buttonCancel.getListeners(ActionListener.class).length);
}
and you'll see that the ActionListeners get added multiple times to this button.
An example of swapping views:
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwapPanels extends JPanel {
public static final String CUSTOMER = "customer";
public static final String ADD_CUSTOMER = "Add Customer";
protected static final int PREF_W = 800;
protected static final int PREF_H = 600;
public static final String CANCEL = "Cancel";
private CardLayout cardLayout = new CardLayout();
public SwapPanels() {
setLayout(cardLayout);
add(createCustomerPanel(CUSTOMER), CUSTOMER);
add(createAddCustomerPanel(ADD_CUSTOMER), ADD_CUSTOMER);
}
public void showCard(String key) {
cardLayout.show(this, key);
}
public JPanel createAddCustomerPanel(String name) {
JPanel addCustPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
addCustPanel.setName(name);
addCustPanel.setBorder(BorderFactory.createTitledBorder(name));
addCustPanel.add(new JButton(new AbstractAction(CANCEL) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (CANCEL.equals(e.getActionCommand())) {
SwapPanels.this.showCard(CUSTOMER);
}
}
}));
return addCustPanel;
}
private JPanel createCustomerPanel(String name) {
JPanel custPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
custPanel.setName(name);
custPanel.setBorder(BorderFactory.createTitledBorder(name));
custPanel.add(new JButton(new AbstractAction(ADD_CUSTOMER) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (ADD_CUSTOMER.equals(e.getActionCommand())) {
SwapPanels.this.showCard(ADD_CUSTOMER);
}
}
}));
return custPanel;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SwapPanels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SwapPanels());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

JavaFX 2.2 : How to forward mouse event to a Swing component under a JFXPanel in a JLayeredPane?

In my application, I want to have a Swing panel with JavaFX control over it. For that, I use a JLayeredPane in which I insert a JPanel and a JFXPanel with a Scene that is not filled (aka setFill(null)). But no event passes through transparent areas of the JFXPanel to the Swing panel.
Is there any solution to this problem ?
Thanks
Here an example :
public class TestJavaFX
{
private static JButton button;
private static JFXPanel javafxPanel;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
initAndShowGUI();
}
});
}
public static void initAndShowGUI()
{
JFrame frame = new JFrame("Swing application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
javafxPanel = new JFXPanel();
button = new JButton("Swing - Push me");
JLayeredPane pane = new JLayeredPane();
pane.add(button, JLayeredPane.DEFAULT_LAYER);
pane.add(javafxPanel, JLayeredPane.PALETTE_LAYER);
pane.addComponentListener(new ComponentListener()
{
#Override
public void componentShown(ComponentEvent e)
{
}
#Override
public void componentResized(ComponentEvent e)
{
button.setBounds(20, 50, 150, 30);
javafxPanel.setBounds(0, 0, e.getComponent().getWidth(), e.getComponent().getHeight());
}
#Override
public void componentMoved(ComponentEvent e)
{
}
#Override
public void componentHidden(ComponentEvent e)
{
}
});
frame.getContentPane().add(pane, BorderLayout.CENTER);
Platform.runLater(new Runnable()
{
public void run()
{
createScene();
}
});
// Show frame.
frame.setSize(600, 400);
frame.setVisible(true);
}
private static void createScene()
{
Button btn = new Button();
btn.setText("JavaFX - Push me");
VBox pane = new VBox();
pane.getChildren().add(btn);
Scene scene = new Scene(pane);
scene.setFill(null);
javafxPanel.setScene(scene);
}
}

Categories

Resources