Can any one tell me how a JButton appears[Fade in], after a short delay.I am working with Netbeans - drag and drop concept for all components.
Personally I would look at making a class that extends your JButton and overriding the paint method. Use both the JTimer to change the values of "setComposite()" (found in the graphics2D class) method over time.
Example of changing the composite in java:
AlphaComposite newComposite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f)
g2d.setComposite(newComposite);
Here is the code that i found on which the above problem working.
import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
public class delay extends javax.swing.JFrame {
Timer timer;
public delay(int seconds) {
initComponents();
jButton1.setVisible(false);
getContentPane().setBackground(Color.red);
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask{
public void run() {
jButton1.setVisible(true);
timer.cancel();
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new delay(5).setVisible(true);
}
});
}
}
Related
I'm currently stuck on a project at the moment component("c") cannot be resolved, I know I'm getting this issue as I'm trying to grab "c" from outside the class from the repaint method but have no idea how to get around this. As far as I'm concerned if I am able to grab "c" then my whole program would. Any help will be massively appreciated. thanks!
package adp.cwr2122;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class SomApplication extends JFrame {
private static final long serialVersionUID = 1L;
private final JProgressBar bar = new JProgressBar();
private final SoM som = new SoM(800,600);
public SomApplication() {
final JPanel mainPanel = new JPanel(new BorderLayout());
final JPanel southPanel = new JPanel(new BorderLayout());
final JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(ev -> doCancel());
this.bar.setMaximum(5000);
southPanel.add(this.bar);
southPanel.add(cancelButton, BorderLayout.EAST);
final SomComponent c = new SomComponent(this.som);
mainPanel.add(c);
mainPanel.add(southPanel, BorderLayout.SOUTH);
add(mainPanel);
pack();
setVisible(true);
this.som.initialise();
c.repaint();
final long start = System.currentTimeMillis();
while(SomApplication.this.som.range() > 0) {
SomApplication.this.som.doOne();
SomApplication.this.bar.setValue((int)((5000 * (SomApplication.this.som.maxRange() - SomApplication.this.som.range())) / SomApplication.this.som.maxRange()));
c.repaint();
}
final long elapsed = System.currentTimeMillis() - start;
System.out.println("Done " + elapsed);
}
private void doCancel() {
System.out.println( "Cancel button pressed");
}
private static class SomComponent extends JComponent {
private static final long serialVersionUID = 1L;
private final SoM som;
public SomComponent( final SoM som) {
this.som = som;
new Thread(new Runnable() {
public void run(){
queuePaint();
System.out.println("Thread is working");
}
}).start();
}
public void repaint() {
if(SwingUtilities.isEventDispatchThread()) {
c.repaint();
}
else {
SwingUtilities.invokeLater(c.repaint);
}
}
public void queuePaint() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Queue Paint is being called");
setPaint(); }
});
}
public void setPaint() {
System.out.println("Paint is being called");
paintComponent(this.getGraphics());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(this.som.image().getWidth(), this.som.image().getHeight());
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(this.som.image(), 0, 0, this);
repaint();
}
}
public static void launch() {
new SomApplication();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SomApplication();
}
});
}
}
As you have recognized yourself your problem is access to c in the repaint() method. You only declare c in the scope of the constructor of SomApplication, so everything outside that scope (read: outside the curly braces of the SomApplicaton constructor) has no idea what c is supposed to be, because it is not declared.
One way to resolve this is declaring c as a member of SomApplication. However you will run into an additional problem there. Your nested class is static, so if you declare c as a member of SomApplication, then SomComponent cannot be static in order to "see" c.
Having said all that there is something fishy with your code there. Because c is an instance of SomComponent and presumably you intend to update itself I then don't see why c is in repaint() to begin with. Your repaint() does not override the JComponent#repaint and your c is presumably supposed to be this.
It's possible I misunderstand something about your architecture, but are you sure you need the c at all in there? Why don't you call repaint() rather than c.repaint() in SomComponent?
If you took the code piece in your SomComponent#repaint method from some online example, take a look at whether you need that code at all. JComponent already comes with repaint(), so maybe this is just the result of a bad copy+paste. Not sure.
I'm making a program that, for the time being, just prints Printing... every half second. Here is my code:
package mainPackage;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Ticker {
public static void tick() {
System.out.println("Printing...");
}
public static void main(String args[]) {
ActionListener timerListener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
tick();
}
};
Timer mainTimer = new Timer(500,timerListener);
mainTimer.start();
}
}
From my understanding the mainTimer object should be firing the event handled by timerListener every 500ms. When I execute this code nothing happens, am I missing something obvious?
Use swing timer under swing event dispatch thread:
public static void main(String args[]) {
ActionListener timerListener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
tick();
}
};
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Timer mainTimer = new Timer(500,timerListener);
mainTimer.start();
}
});
}
If you don't plan on changing the GUI from the timer, consider using java.util.Timer
I have problems with Java's Multi-Threading feature, so hopefully somebody can help me....
Here is my problem:
In the JPanel ExamplePanel which is located in the JFrame ExampleFrame I've added a ComponentListener which invokes the startPaint()-Method. This method should work in a new Thread. My Problem is that by resizing the window "former" Threads aren't closed, meanwhile new Threads are added....
So is there a way to resize the JPanel and to close at the same time the "old" threads, so that the number of threads is not growing, when I resize the JPanel?
I have tried something with a boolean exiter-variable, but it do not seemed to work...
here is the code:
package example;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Example2 {
public static void main(String[] args) throws InterruptedException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new ExampleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ExampleFrame extends JFrame {
private static final long serialVersionUID = 1L;
ExamplePanel examplePanel = new ExamplePanel();
private Thread t=null;
private class ExamplePanel extends JPanel implements ComponentListener {
private static final long serialVersionUID = 1L;
#Override
public void componentHidden(ComponentEvent e) {
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentResized(ComponentEvent e) {
startPaint();
}
#Override
public void componentShown(ComponentEvent e) {
}
private void startPaint() {
t=new Thread(new Runnable() {
#Override
public void run() {
//System.out.println(Thread.currentThread().getName());
while (true) {
//System.out.println(Thread.activeCount());
}
}
});
t.start();
}
}
public ExampleFrame() {
examplePanel.addComponentListener((ComponentListener) examplePanel);
getContentPane().add(examplePanel);
}
}
if the calculations don't take long don't use an extra Thread.
if you need this extra Thread make sure that it doesn't run forever (no while (true) without returning at some point)
you can always interrupt your running Thread bfore creating the new one
if (t != null && t.isAlive()) {
t.interrupt();
}
and check in the while(true) loop if the Thread is interrupted
if (t.isInterrupted()) {
System.out.println("Thread ended");
return;
}
hope this helps
I was reading the documentation on swing timers, when I came across some information about ActionListeners. When further researched, all I could find is how to create an ActionListener attached to a JButton, etc. How can you create a plain ActionListener, not attached to anything?
My timer is not working correctly, and I thought it may be because I was incorrectly using the ActionListener.
Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MyTimer {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("testing");
}
};
public MyTimer() {
Timer timer = new Timer(10, al);
timer.start();
}
public static void main(String[] args) {
MyTimer start = new MyTimer();
}
}
An ActionListener is just an interface
You can create an stand alone version by implementing it and then instanstanting it....
public class MyActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// do something...
}
}
And sometime in the future...
MyActionHandler handler = new MyActionHandler();
Or you could create an anonymous instance....
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// do something...
}
};
Take a look at Interfaces for more details
How can you create a plain actionlistner, not attached to anything?
Loot at this:
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World!");
}
};
// Using the listener with 2 seconds delay
java.swing.Timer timer = new java.swing.Timer(2000, listener);
timer.setRepeats(false);
// Start the timer
timer.start();
Try with this:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MyTimer {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("testing");
}
};
public MyTimer() {
Timer timer = new Timer(1000, al);
timer.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new MyTimer();
}
});
}
}
I am making a user interface which shows graphs and manipulates graphs. The class extends JFrame implements ActionListener. The ActionListener then calls different classes to manipulate graphs depending on the action. This worked while the class had few ActionListeners; however, now the class is becoming unmanageable.
I know that in the interest of encapsulation, it would be best to have the ActionListener within the user interface class because it needs to access non-static components of the interface. However, it seems like there is a conflict between encapsulation and readability.
What I am proposing is breaking the class into one class for the interface and a second for the ActionListener and accessing the interface components statically. What I want to know is does this follow basic design conventions? And, if this is an acceptable approach would you place the main class in the user-interface class or the ActionListener class?
Not a duplicate question... but my answer should help with your question.
Short summery, my preference would be to have the JFrame class not implement ActionListener and then have a number of named inner classes withing the JFrame that do implement the ActionListener.
I would place the main in a class unto itself... and call it Main.
Here is some sample code for the way I like to do it:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main
{
private Main()
{
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
final FooFrame frame;
frame = new FooFrame();
frame.setupGUI();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
and then the GUI:
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FooFrame
extends JFrame
{
private final JButton incrementBtn;
private final JButton decrementBtn;
private int value;
{
incrementBtn = new JButton("++");
decrementBtn = new JButton("--");
}
private class IncrementListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
increment();
}
}
private class DecrementListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
decrement();
}
}
public void setupGUI()
{
final LayoutManager layout;
layout = new FlowLayout();
setLayout(layout);
setupListeners();
addComponents();
}
private void setupListeners()
{
incrementBtn.addActionListener(new IncrementListener());
decrementBtn.addActionListener(new DecrementListener());
}
private void addComponents()
{
add(incrementBtn);
add(decrementBtn);
}
private void increment()
{
value++;
System.out.println("value = " + value);
}
private void decrement()
{
value--;
System.out.println("value = " + value);
}
}