I have a JFrame which contains a JPanel with the JButton "Press Me"
Pressing the "Press me" button will change to another JPanel(SecondPanel) within the same JFrame
I am facing a problem where there is a 10 second delay when i press the "Press Me" button before the SecondPanel appears.
This 10 second delay is caused the Timer event .
I wish for the SecondPanel to appear before the Timer event start.
What is happening now is that the Timer event starts , i am waiting at the "Press Me" button for 10 seconds , before the SecondPanel appears ,
can someone help me resolve this issue
Thanks
Main class used to run the project
package testing;
import java.io.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Testing extends JPanel
{
public static void main(String[] args)
{
frame = new JFrame();
LoginPanel lp = new LoginPanel();
frame.add(lp);
frame.pack();
frame.validate();
frame.setVisible(true);
}
static JFrame frame;
}
LoginPanel class
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginPanel extends JPanel
{
LoginPanel()
{
Loginbtn = new JButton("Press Me");
Loginbtn.addActionListener(new LoginButtonListener());
add(Loginbtn);
}
private class LoginButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
SecondPanel sp = new SecondPanel();
Utility.ChangePanel(sp);
sp.run();
}
}
JButton Loginbtn;
}
SecondPanel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SecondPanel extends JPanel
{
SecondPanel()
{
setLayout(new GridLayout(2,2));
//set deck image
File deckfile = new File("./src/testing/Ace_Club_1_1.png"); //deck image file location
try
{
Deckimg = ImageIO.read(deckfile); //read deck image
}
catch (IOException e)
{
}
Image scaledInstance = Deckimg.getScaledInstance(100, -1, Image.SCALE_SMOOTH);
DeckLabel = new JLabel(new ImageIcon(scaledInstance));
add(DeckLabel);
}
public void run()
{
Timer timer = new Timer(5000, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Code to be executed
System.out.println("HowareYou");
}
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!
try
{
Thread.sleep(7000);
}
catch(InterruptedException ie)
{
}
}
JLabel DeckLabel;
JPanel DeckPanel;
BufferedImage Deckimg;
}
Utility class used to switch JPanels within the JFrame
package testing;
import java.security.MessageDigest;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Utility
{
public static void ChangePanel(JPanel jp)
{
testing.Testing.frame.getContentPane().removeAll();
testing.Testing.frame.add(jp);
testing.Testing.frame.validate();
}
}
You're blocking the Swing event thread in SecondPanel.run() with Thread.sleep(7000). This will stop any GUI updates happening. If you remove the sleep you should see the second panel appear before the timer fires.
Related
I am trying to make a button that says hello world but it dose not work I tried multiple times but nothing i did made a difference
[![package com.company;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main implements ActionListener {
JButton b;
JFrame f;
public Main()
{
b=new JButton("hello");
b.addActionListener(this);
b.setBounds(100,100,95,30);
f.setTitle("first");
f.setSize(500,300);
f.add(b);
f.setVisible(true);
f.setLayout(null);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b)
{
System.out.print("hello world");
}
}
public static void main(String\[\] args) {
// write your code here
new Main();
}
}][1]][1]
and this is he result it displays
You need to instantiate your JFrame in the constructor with f = new JFrame();.
Ok so I will try to make this as understandable as possible. I have created a simple GUI with an "open" button and a textArea (along with other stuff but that's not important right now). Basically I am creating a method that when I click the Open button it displays the contents of the file in the textArea. I believe 99% of the method I have written is correct but I keep getting a NullPointerException and I don't quite understand why. Hopefully my code will clear up any confusion on what I am asking, I will comment on the line of code where I get the exception. Here is my code:
Application class (Basic setup of my GUI):
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class Application extends JFrame {
public OutputPanel outPanel = new OutputPanel();
public BarcodePanel barPanel = new BarcodePanel();
public ButtonPanel btnPanel = new ButtonPanel();
public ReferencePanel refPanel = new ReferencePanel();
public Application() {
super("Book Processor");
this.setLayout(new BorderLayout());
btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
outPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
refPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(btnPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.WEST);
add(refPanel,BorderLayout.SOUTH);
}//end constructor
public static void main(String[] args) {
Application frame = new Application();
frame.setSize(1000,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end main
}//end class
The next set of code is my ButtonPanel class(this is where I am having an issue) So I have an openFile method, that when I click the button it should display the contents of the file in the textArea. Again I receive a NullPointerException and I do not understand why. Here is the code for this class:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel{
JButton btnOpen = new JButton("Open");
OutputPanel outPanel = new OutputPanel();
Scanner input;
public ButtonPanel() {
ButtonHandler handler = new ButtonHandler();
add(btnOpen);
btnOpen.addActionListener(handler);
}//end constructor
/**
* Method for displaying the file onto the textArea.
*
*/
private void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
String fileName;
fileName = chooser.getSelectedFile().getAbsolutePath();
try {
Scanner input = new Scanner(Paths.get(fileName));
StringBuilder sb = new StringBuilder();
while(input.hasNextLine()) {
sb.append(input.nextLine()+ "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
finally {
input.close();
}
}//end readFile
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()== btnOpen) {
openFile();
}
}//end actionPerformed
}//end actionlistener
}//end class
Here is my last class, OutputPanel, this class contains the JTextArea:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputPanel extends JPanel{
public JTextArea txtOutput = new JTextArea(20,50);
public OutputPanel() {
add(txtOutput);
}//end constructor
}//end class
How do I get the textArea to display the contents of the file. More importantly why am I getting this exception and what can I do to fix it. Hopefully this makes as much sense as possible, and I really appreciate any and all input from you guys.
I used 'Thread' and 'TimeUnit' but not know how to use in the following program. I want when WIN+E execute then after some delay of 1 or 2 second next statement run. As, next statement is in for loop so it should run after 2 seconds infinite time (because of infinite for loop). You can see ActionListener line only.
package v;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class V extends JPanel{
private JButton V;
public V() throws AWTException{
Robot r = new Robot();
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
V = new JButton("PUSH");
add(V);
V.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
for (int i=0; i>0; i++) {r.keyPress(KeyEvent.VK_WINDOWS); r.keyPress(KeyEvent.VK_E); r.keyRelease(KeyEvent.VK_WINDOWS); r.keyRelease(KeyEvent.VK_E);}
}
});
}
public static void main(String[] args) throws AWTException {
V panel = new V();
JFrame frame = new JFrame ("V");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
i would go for something like this:
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class V extends JPanel{
private JButton V;
private boolean notstarted=true;
public V() throws AWTException{
Robot r = new Robot();
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
V = new JButton("PUSH");
add(V);
V.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
if(notstarted){
notstarted=false;
new Thread(new Runnable() {
#Override
public void run() {
while (true) {r.keyPress(KeyEvent.VK_WINDOWS);
r.keyPress(KeyEvent.VK_E);
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(StreamServer.class.getName()).log(Level.SEVERE, null, ex);
}
r.keyRelease(KeyEvent.VK_WINDOWS);
r.keyRelease(KeyEvent.VK_E);}
}
}).start();
}
}
});
}
public static void main(String[] args) throws AWTException {
V panel = new V();
JFrame frame = new JFrame ("V");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
As you can see i have added a boolean notstarted to control if the function have been accessed previously, so, this way you cant run that more than one and finally i have added a Thread to mitigate the impact the ActionListener could have on the thread that call it.
Anyway there should be beeter ways to achieve what you are looking for.
You can use javafx.animation.PauseTransition
PauseTransition happen = new PauseTransition(Duration.seconds(2));
happen.setOnFinished(e -> {
System.out.println("hello");
happen.playFromStart();
});
happen.play();
Like that. It will print hello every 2 seconds. That however requires you to extend javafx.application.Application and I see that you don't use javafx in your program.
You can use Thread.sleep as the other answer suggests - to sleep each 2000 miliseconds (in your loop).
There is also java.util.Timer and java.util.TimerTask. It allows you to do code every milisecond given in time. There is an excellent video of that here https://www.youtube.com/watch?v=36jbBSQd3eU
I am trying to create a piano program where you click the key and using an actionlistener is plays the note from the jfugue library. For some reason after about 18 clicks without changing anything the buttons stop working. I cut down the code to analyze why this might happen, thus only two notes.
Thanks in advance for any advice!
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.Color;
import javax.swing.JLayeredPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.*;
import org.jfugue.*;
public class ChordPlayer2 extends JComponent{
public ChordPlayer2(){
final Player player = new Player();
JFrame frame = new JFrame();
JButton cButton, csharpButton;
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(0, 0);
buttonPanel.setSize(1700, 1000);
csharpButton = new JButton("");
csharpButton.setLocation(100, 150);
csharpButton.setSize(100,520);
buttonPanel.add(csharpButton);
cButton = new JButton("");
cButton.setLocation(0, 150);
cButton.setSize(160, 800);
buttonPanel.add(cButton);
class cClicker implements ActionListener {
public void actionPerformed(ActionEvent event) {
player.play("C");
}
}
class csClicker implements ActionListener {
public void actionPerformed(ActionEvent event) {
player.play("C#");
}
}
ActionListener c = new cClicker();
cButton.addActionListener(c);
ActionListener cs = new csClicker();
csharpButton.addActionListener(cs);
buttonPanel.setOpaque(true);
//return buttonPanel;
frame.add(buttonPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1700, 1000);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
//JFrame.setDefaultLookAndFeelDecorated(true);
ChordPlayer2 demo = new ChordPlayer2();
}
}
This is a known bug in JFugue:
https://code.google.com/p/jfugue/issues/detail?id=49
The most recent version is claimed to fix this:
https://code.google.com/p/jfugue/downloads/detail?name=jfugue-4.1.0-20120125.jar&can=2&q=
I have created a simple VLCJ project that consists of a simple embedded player and a button to exit.
The code is as follows:
package test;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class Demo {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JPanel videoPane;
private JPanel buttonPane;
private Button exitButton;
private ActionListener a;
private static String vlc_location = "C:\\Program Files\\VideoLAN\\VLC";
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), vlc_location);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().run();
}
});
}
public Demo() {
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
a = new MyActionListener();
exitButton = new Button("Exit");
exitButton.setActionCommand("Exit app");
exitButton.addActionListener(a);
buttonPane = new JPanel();
buttonPane.setLayout(new BorderLayout());
buttonPane.setBackground(Color.black);
buttonPane.add(exitButton, BorderLayout.CENTER);
videoPane = new JPanel();
videoPane.setLayout(new BorderLayout());
videoPane.setBackground(Color.black);
videoPane.add(mediaPlayerComponent, BorderLayout.CENTER);
videoPane.add(buttonPane, BorderLayout.PAGE_END);
frame = new JFrame("vlcj demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setSize(1200, 800);
frame.setContentPane(videoPane);
frame.setVisible(true);
}
public void run() {
mediaPlayerComponent.getMediaPlayer().playMedia(video_file);
}
class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
String s = arg0.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}
}
}
}
The problem is that the button does show up but it cannot be clicked. When i removed the videoPane, it was back to clickable! Any ideas if I'm missing something?
I am using the version 2.1.0 for vlcj.
Thanks!
Thanks MadProgrammer for your advise. I went on to think about it and tried commenting away the line of code in run(). The JButton came back!
However, when i un-commented the code in run(), the JButton disappeared. I was thinking maybe the Swing runnable was causing issue with the creation of the JButton.
Hence, what i did was to comment away the whole Swing runnable and just use:
final Demo demo = new Demo();
demo.run();
The demo can now play video and display the Exit button, thanks!