How to Make a Splash Screen - java

I have a program which should has splash screen on JPanel, after button click should show another JPanel (object of the class) and draw shapes. I tried remove splash JPanel and after that add JPanel for drawing but it doeesn't work. How can I fix it? Two JLabel should be in the center of screen and it should be on 2 lines.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
*
* #author Taras
*/
public class MyComponent extends JComponent {
int i;
Color randColor;
public MyComponent()
{
this.i = i;
addMouseListener(new MouseHandler());
}
private ArrayList<Rectangle2D> arrOfRect=new ArrayList<>();
private ArrayList<Ellipse2D> arrOfEllipse=new ArrayList<>();
// private ArrayList<Color> randColor = new ArrayList<>();
Random rand = new Random();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle2D r : arrOfRect) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(r);
}
for (Ellipse2D e : arrOfEllipse) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(e);
}
}
public void add(Point2D p)
{
double x=p.getX();
double y=p.getY();
if (Pole.i == 1){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,100);
//randColor = new Color(randRed(), randGreen(), randBlue());
arrOfEllipse.add(ellipse);
}
if (Pole.i == 2){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 100, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 3){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 150, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 4){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,50);
arrOfEllipse.add(ellipse);
}
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event)
{
add(event.getPoint());
//Color rColor = new Color(randRed(), randGreen(), randBlue());
//randColor.add(rColor);
repaint();
}
}
private int randRed() {
int red;
Random randomNumber = new Random();
red = randomNumber.nextInt(255);
return red;
}
private int randGreen() {
int green;
Random randomNumber = new Random();
green = randomNumber.nextInt(255);
return green;
}
private int randBlue() {
int blue;
Random randomNumber = new Random();
blue = randomNumber.nextInt(255);
return blue;
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.omg.CosNaming.NameComponent;
public class Pole extends JFrame {
public static int i;
public static JPanel nameContainer = new JPanel(new GridLayout(2, 1));
public static JFrame frame= new JFrame("Shape Stamper!");
public static void main(String[] args) {
JPanel container;
JButton circle = new JButton("Circle");
JButton square = new JButton("Square");
JButton rectangle = new JButton("Rectangle");
JButton oval = new JButton("Oval");
JLabel programName = new JLabel("Shape Stamper!");
JLabel programmerName = new JLabel("Progrramed by: ");
Font font = new Font("Serif", Font.BOLD, 32);
programName.setFont(font);
font = new Font("Serif", Font.ITALIC, 16);
programmerName.setFont(font);
programName.setHorizontalAlignment(JLabel.CENTER);
programmerName.setHorizontalAlignment(JLabel.CENTER);
//programmerName.setVerticalAlignment(JLabel.CENTER);
// nameContainer.setLayout(new BorderLayout());
nameContainer.add(programName);
nameContainer.add(programmerName);
//nameContainer.setLayout(new BoxLayout(nameContainer, BoxLayout.X_AXIS));
container = new JPanel(new GridLayout(1, 4));
container.add(circle);
container.add(square);
container.add(rectangle);
container.add(oval);
circle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 1;
frame.remove(nameContainer);
frame.repaint();
System.out.println(i);
}
});
square.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 2;
}
});
rectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 3;
}
});
oval.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 4;
}
});
MyComponent shape = new MyComponent();
frame.setSize(500, 500);
frame.add(shape, BorderLayout.CENTER);
frame.add(container, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Here's an example of making a splash screen using an image.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CircleSplashScreen {
public CircleSplashScreen() {
JFrame frame = new JFrame();
frame.getContentPane().add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleSplashScreen();
}
});
}
#SuppressWarnings("serial")
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setOpaque(false);
setLayout(new GridBagLayout());
try {
img = ImageIO.read(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
} catch (IOException ex) {
Logger.getLogger(CircleSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}

Related

Make an JLabel move with Key Bidings

I have a short script made in swing, people keep telling me that I need to use Key bindings to get the Jlabel to move but I can't figure out how to do it. anyone have any idea on how to implement Key bindings in a way it works that does not use a Key Listener or that will be a problem if I add a button?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
public class Screen extends JFrame {
private JPanel contentPane;
int x,y;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen frame = new Screen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Screen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, "p1");
panel.setLayout(null);
JButton btnPlay = new JButton("Play");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout c =(CardLayout)(contentPane.getLayout());
c.show(contentPane, "p2");
}
});
btnPlay.setBounds(185, 164, 53, 23);
panel.add(btnPlay);
JLabel lblGame = new JLabel("Game");
lblGame.setHorizontalAlignment(SwingConstants.CENTER);
lblGame.setBounds(189, 28, 46, 14);
panel.add(lblGame);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, "p2");
panel_1.setLayout(null);
JLabel player = new JLabel("P");
player.setHorizontalAlignment(SwingConstants.CENTER);
player.setFont(new Font("Tahoma", Font.BOLD, 27));
player.setForeground(Color.BLACK);
player.setBackground(Color.BLACK);
player.setBounds(x, y, 51, 40);
panel_1.add(player);
}
}
As with most things, start having a look at the tutorials, How to Use Key Bindings, as pretty much any answer is simply going to be based on these
You could do something as simple as this...
import com.sun.glass.events.KeyEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Movable {
public void changeLocation(int xDelta, int yDelta);
}
public class TestPane extends JPanel implements Movable {
private JLabel player;
public TestPane() {
setLayout(null);
player = new JLabel("X");
player.setSize(player.getPreferredSize());
add(player);
setupKeyBindings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void setupKeyBindings() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
int xDelta = player.getWidth();
int yDelta = player.getHeight();
am.put("up", new MoveAction(this, 0, -yDelta));
am.put("down", new MoveAction(this, 0, yDelta));
am.put("left", new MoveAction(this, -xDelta, 0));
am.put("right", new MoveAction(this, xDelta, 0));
}
#Override
public void changeLocation(int xDelta, int yDelta) {
int xPos = player.getX() + xDelta;
int yPos = player.getY() + yDelta;
if (xPos + player.getWidth() > getWidth()) {
xPos = getWidth() - player.getWidth();
} else if (xPos < 0) {
xPos = 0;
}
if (yPos + player.getHeight() > getHeight()) {
yPos = getHeight() - player.getHeight();
} else if (xPos < 0) {
yPos = 0;
}
player.setLocation(xPos, yPos);
}
}
public class MoveAction extends AbstractAction{
private Movable movable;
private int xDelta;
private int yDelta;
public MoveAction(Movable movable, int xDelta, int yDelta) {
this.movable = movable;
this.xDelta = xDelta;
this.yDelta = yDelta;
}
#Override
public void actionPerformed(ActionEvent e) {
movable.changeLocation(xDelta, yDelta);
}
}
}
Disclaimer...
As I have, repeatedly, told either you or your fellow class mates, you shouldn't be using components this way. Instead, you should be following a custom painting route, which will provide you with greater flexibility and far less issues in the long run.
import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Movable {
public void changeLocation(int xDelta, int yDelta);
}
public class TestPane extends JPanel implements Movable {
private Rectangle player;
public TestPane() {
String text = "X";
FontMetrics fm = getFontMetrics(getFont());
int width = fm.stringWidth(text);
int height = fm.getHeight();
player = new Rectangle(0, 0, width, height);
setupKeyBindings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void setupKeyBindings() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
int xDelta = player.width;
int yDelta = player.height;
am.put("up", new MoveAction(this, 0, -yDelta));
am.put("down", new MoveAction(this, 0, yDelta));
am.put("left", new MoveAction(this, -xDelta, 0));
am.put("right", new MoveAction(this, xDelta, 0));
}
#Override
public void changeLocation(int xDelta, int yDelta) {
int xPos = player.x + xDelta;
int yPos = player.y + yDelta;
if (xPos + player.width > getWidth()) {
xPos = getWidth() - player.width;
} else if (xPos < 0) {
xPos = 0;
}
if (yPos + player.height > getHeight()) {
yPos = getHeight() - player.height;
} else if (xPos < 0) {
yPos = 0;
}
player.setLocation(xPos, yPos);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.draw(player);
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString("X", player.x, player.y + fm.getAscent());
g2d.dispose();
}
}
public class MoveAction extends AbstractAction {
private Movable movable;
private int xDelta;
private int yDelta;
public MoveAction(Movable movable, int xDelta, int yDelta) {
this.movable = movable;
this.xDelta = xDelta;
this.yDelta = yDelta;
}
#Override
public void actionPerformed(ActionEvent e) {
movable.changeLocation(xDelta, yDelta);
}
}
}
You should also be making appropriate use layout managers. These will safe you a lot of hair and time.
See Laying Out Components Within a Container for more details

In Java, how could I make a letter flash on the screen depending on a BPM value the user provides?

With Swing, I've created a window and want a letter to flash on the screen depending on the BPM (Beats per minute) the user inputs, and I was wondering how I would go about timing the flashing accurately. I tried using a Swing Timer but it is not very accurate and I see a lot of pauses or lag. I've heard something about using System.nanoTime() and System.currentTimeMillis() but have no clue how to implement them to create a timer. Any help would be appreciated!
Note.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.*;
public class Note extends JFrame implements ActionListener {
JPanel mainScreen = new JPanel();
JPanel south = new JPanel();
JPanel north = new JPanel();
//emptyNumberMain = how many empty panels you want to use
public int emptyNumberMain = 2;
JPanel[] emptyMain = new JPanel[emptyNumberMain];
JLabel title = new JLabel("Fretboard Trainer!");
JButton start = new JButton("Start!");
public static void main(String[] args) {
new Note();
}
public Note() {
super("Random Note!");
setSize(300,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//creates emptyNumberMain amount of empty panels
for (int i = 0; i < emptyNumberMain; i++) {
emptyMain[i] = new JPanel();
}
mainScreen.setLayout(new BorderLayout());
south.setLayout(new GridLayout(1,1));
south.add(emptyMain[0]);
south.add(start);
south.add(emptyMain[1]);
north.setLayout(new GridLayout(1,2));
north.add(title);
title.setHorizontalAlignment(JLabel.CENTER);
title.setFont(title.getFont().deriveFont(32f));
start.addActionListener(this);
mainScreen.add(north, BorderLayout.NORTH);
mainScreen.add(south, BorderLayout.SOUTH);
add(mainScreen);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
dispose();
new RandomNote();
}
}
}
RandomNote.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.util.Random;
import javax.swing.Timer;
import javax.swing.JSlider;
import java.awt.event.*;
import java.awt.*;
public class RandomNote extends JFrame {
JPanel noteScreen = new JPanel();
JPanel center = new JPanel();
JPanel southSlider = new JPanel();
JLabel bpm = new JLabel();
//emptyNumber = how many empty panels you want to use
int emptyNumber = 2;
JPanel[] empty = new JPanel[emptyNumber];
JLabel rndNote = new JLabel();
JSlider slider = new JSlider(0,200,100);
Timer timer2 = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bpm.setText(Integer.toString(slider.getValue()));
timer.setDelay((int) ((60.0/slider.getValue()) * 1000));
}
});
public RandomNote() {
super("Random Notes!");
timer.start();
timer2.start();
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//creates variable emptyNumber amount of empty panels
for (int i = 0; i < emptyNumber; i++) {
empty[i] = new JPanel();
}
noteScreen.setLayout(new BorderLayout());
center.setLayout(new GridLayout(1,1));
center.add(rndNote);
southSlider.setLayout(new GridLayout(3,1));
slider.setLabelTable(slider.createStandardLabels(20));
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
southSlider.add(slider);
southSlider.add(bpm);
rndNote.setHorizontalAlignment(JLabel.CENTER);
rndNote.setFont(rndNote.getFont().deriveFont(32f));
noteScreen.add(center, BorderLayout.CENTER);
noteScreen.add(southSlider, BorderLayout.SOUTH);
add(noteScreen);
setVisible(true);
}
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rndNote.setText(noteOutput());
}
});
public static String noteOutput() {
Random rand = new Random();
String[] note = {"A", "B", "C", "D", "E", "F", "G"};
int randNum = rand.nextInt(7);
return note[randNum];
}
}
The immediate thing that jumps out at me is this...
Timer timer2 = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bpm.setText(Integer.toString(slider.getValue()));
timer.setDelay((int) ((60.0/slider.getValue()) * 1000));
}
});
Why do you need to update the text and reset the timer every 100 milliseconds?
So, the simple answer would be to use a ChangeListener on the JSlider to determine when the slider's value changes. I'd recommend having a look at How to Use Sliders for more details
As a runnable concept...
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private AnimatableLabel label;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
label = new AnimatableLabel("BMP");
label.setHorizontalAlignment(JLabel.CENTER);
add(label, gbc);
label.start();
JSlider slider = new JSlider(10, 200);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
label.setBPM(slider.getValue());
}
});
slider.setValue(60);
add(slider, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class AnimatableLabel extends JLabel {
private Timer pulseTimer;
private Timer fadeTimer;
private double bpm = 60;
private double alpha = 0;
private Long pulsedAt;
public AnimatableLabel(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(String text) {
super(text);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(Icon image, int horizontalAlignment) {
super(image, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(Icon image) {
super(image);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel() {
setBackground(Color.RED);
initTimer();
}
public void start() {
updateTimer();
}
public void stop() {
pulseTimer.stop();
fadeTimer.stop();
}
protected void initTimer() {
pulseTimer = new Timer((int)(getDuration()), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pulsedAt = System.currentTimeMillis();
alpha = 1.0;
repaint();
}
});
pulseTimer.setInitialDelay(0);
pulseTimer.setCoalesce(true);
fadeTimer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pulsedAt == null) {
return;
}
long fadingDuration = System.currentTimeMillis() - pulsedAt;
alpha = 1.0 - (fadingDuration / getDuration());
if (alpha > 1.0) {
alpha = 1.0;
} else if (alpha < 0.0) {
alpha = 0.0;
}
repaint();
}
});
fadeTimer.setCoalesce(true);
}
protected double getDuration() {
return (60.0 / bpm) * 1000.0;
}
protected void updateTimer() {
fadeTimer.stop();
pulseTimer.stop();
pulseTimer.setDelay((int)getDuration());
pulseTimer.start();
fadeTimer.start();
}
public void setBPM(double bpm) {
this.bpm = bpm;
setText(Double.toString(bpm));
updateTimer();
}
public double getBPM() {
return bpm;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive((float)alpha));
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
}

Speed up/Mask Blur

I am using code from this website to blur my photos in a Java application.
The problem with it is that it is not fast enough to do the blurring effect in real-time. This means when the area it is blurring changes size, there is a large black box whilst it renders a new blur. Is there a way to mask this gap whilst it renders the new blur?
Example GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.LayoutManager;
import java.awt.MultipleGradientPaint.CycleMethod;
import java.awt.RadialGradientPaint;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import blur.GaussianFilter;
#SuppressWarnings("serial")
public class GUI extends JFrame {
private GUI() {
super("Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
Overlay layers = new Overlay();
add(layers);
pack();
setMinimumSize(getSize());
getContentPane().setBackground(Color.WHITE);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GUI());
}
private class Overlay extends JLayeredPane {
JPanel base;
JPanel overlay;
BufferedImage bi, blurredImage;
BufferedImageOp op = new GaussianFilter(4);
private Overlay() {
addComponentListener(new Resize());
setPreferredSize(new Dimension(800, 100));
createBase();
createOverlay();
add(base, new Integer(0));
bi = ComponentPainter.paintComponent(base);
blurredImage = op.filter(bi, null);
add(overlay, new Integer(1));
}
private void createBase() {
base = new JPanel();
base.setLocation(0, 0);
base.setPreferredSize(new Dimension(800, 100));
base.setSize(800, 100);
base.setBackground(Color.WHITE);
base.setVisible(false);
base.add(new JLabel("Hello"));
base.add(new JButton("Hello"));
}
private void createOverlay() {
overlay = new Over(new GridBagLayout());
overlay.setLocation(0, 0);
overlay.setPreferredSize(new Dimension(800, 100));
overlay.setSize(800, 100);
overlay.add(new JLabel("Hi"));
}
private class Resize extends ComponentAdapter {
#Override
public void componentResized(ComponentEvent e) {
base.setSize(new Dimension(getParent().getWidth(), getParent().getHeight()));
overlay.setSize(new Dimension(getParent().getWidth(), getParent().getHeight()));
bi = ComponentPainter.paintComponent(base);
blurredImage = op.filter(bi, null);
}
}
private class Over extends JPanel {
private Over() {
super();
}
private Over(LayoutManager layout) {
super(layout);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(blurredImage, 0, 0, this);
int alpha = 128;
Point2D center = new Point2D.Float(getWidth()/2f, getHeight()/2f);
float radius = (getWidth() / 16F) * 13;
float[] dist = {0f, 1f};
Color[] colors = {new Color(245, 251, 255, alpha), new Color(255, 255, 255, alpha)};
RadialGradientPaint p = new RadialGradientPaint(center, radius,
dist, colors,
CycleMethod.NO_CYCLE);
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
#Override
public boolean isOptimizedDrawingEnabled() {
return true;
}
}
private static class ComponentPainter {
public static BufferedImage paintComponent(Component c) {
layoutComponent(c);
BufferedImage img = new BufferedImage(c.getWidth(), c.getHeight(),
BufferedImage.TYPE_INT_RGB);
c.paint(img.createGraphics());
return img;
}
private static void layoutComponent(Component c) {
synchronized (c.getTreeLock()) {
c.doLayout();
if (c instanceof Container)
for (Component child : ((Container) c).getComponents())
layoutComponent(child);
}
}
}
}
Other code used in example GUI:
SO Answer
Blur Download

Drawing multiple graphic2d components into JPanel

I've read a lot of tutorials on drawing Graphics2D components and adding to JPanel/JFrame but I can't find how to add multiple these components into one JPanel simply. My code below adds only 1 component (line) and I can't find why it isn't possible to add more.
What am I doing wrong?
Desired behaviour: there should be 3 red lines.
My whole code:
package Examples;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example1 extends JFrame {
private final JPanel panel;
public Example1() {
// jpanel with graphics
panel = new JPanel();
panel.setPreferredSize(new Dimension(200, 200));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.setBackground(Color.WHITE);
add(panel);
// adding lines to jpanel
AddMyLine(); // 1st: this works well
AddMyLine(); // 2nd: this doesn't work
AddMyLine(); // 3rd: this doesn't work
setLayout(new FlowLayout(FlowLayout.LEFT));
setSize(250, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
// add new line to jpanel
private void AddMyLine() {
MyLine c = new MyLine();
System.out.println(c);
panel.add(c);
}
// line component
private class MyLine extends JComponent {
public MyLine() {
setPreferredSize(new Dimension(200, 200));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(1));
int x1 = (int)Math.round(Math.random()*200);
int y1 = (int)Math.round(Math.random()*200);
int x2 = (int)Math.round(Math.random()*200);
int y2 = (int)Math.round(Math.random()*200);
g2d.drawLine(x1,y1,x2,y2);
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example1();
}
});
}
}
Your MyLine class should not be a Swing component and thus should not extend JComponent. Rather it should be a logical entity, and in fact can be something that implements Shape such as a Line2D, or could be your own complete class, but should know how to draw itself, i.e., if it does not implement Shape, then it should have some type of draw(Graphics2D g) method that other classes can call. I think instead you should work on extending your panel's JPanel class, such that you override its paintComponent method, give it a collection to hold any MyLine items added to it, and draw the MyLine items within the paintComponent.
Other options include drawing directly on to a BufferedImage, and then displaying that BufferedImage in your JPanel's paintComponent method. This is great for static images, but not good for images that need to change or move.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class DrawChit extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private List<Shape> shapes = new ArrayList<>();
public DrawChit() {
setBackground(Color.white);
}
public void addShape(Shape shape) {
shapes.add(shape);
repaint();
}
#Override // make it bigger
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Shape shape : shapes) {
g2.draw(shape);
}
}
private static void createAndShowGui() {
DrawChit drawChit = new DrawChit();
drawChit.addShape(new Line2D.Double(10, 10, 100, 100));
drawChit.addShape(new Ellipse2D.Double(120, 120, 200, 200));
JFrame frame = new JFrame("DrawChit");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(drawChit);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Or an example using my own MyDrawable class, which produces a GUI that looks like this:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
#SuppressWarnings("serial")
public class DrawChit extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private List<MyDrawable> drawables = new ArrayList<>();
public DrawChit() {
setBackground(Color.white);
}
public void addMyDrawable(MyDrawable myDrawable) {
drawables.add(myDrawable);
repaint();
}
#Override
// make it bigger
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (MyDrawable myDrawable : drawables) {
myDrawable.draw(g2);
}
}
public void clearAll() {
drawables.clear();
repaint();
}
private static void createAndShowGui() {
final List<MyDrawable> myDrawables = new ArrayList<>();
myDrawables.add(new MyDrawable(new Line2D.Double(100, 40, 400, 400),
Color.red, new BasicStroke(40)));
myDrawables.add(new MyDrawable(new Ellipse2D.Double(50, 10, 400, 400),
Color.blue, new BasicStroke(18)));
myDrawables.add(new MyDrawable(new Rectangle2D.Double(40, 200, 300, 300),
Color.cyan, new BasicStroke(25)));
myDrawables.add(new MyDrawable(new RoundRectangle2D.Double(75, 75, 490, 450, 40, 40),
Color.green, new BasicStroke(12)));
final DrawChit drawChit = new DrawChit();
JFrame frame = new JFrame("DrawChit");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(drawChit);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int drawCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (drawCount >= myDrawables.size()) {
drawCount = 0;
drawChit.clearAll();
} else {
drawChit.addMyDrawable(myDrawables.get(drawCount));
drawCount++;
}
}
}).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyDrawable {
private Shape shape;
private Color color;
private Stroke stroke;
public MyDrawable(Shape shape, Color color, Stroke stroke) {
this.shape = shape;
this.color = color;
this.stroke = stroke;
}
public Shape getShape() {
return shape;
}
public Color getColor() {
return color;
}
public Stroke getStroke() {
return stroke;
}
public void draw(Graphics2D g2) {
Color oldColor = g2.getColor();
Stroke oldStroke = g2.getStroke();
g2.setColor(color);
g2.setStroke(stroke);
g2.draw(shape);
g2.setColor(oldColor);
g2.setStroke(oldStroke);
}
public void fill(Graphics2D g2) {
Color oldColor = g2.getColor();
Stroke oldStroke = g2.getStroke();
g2.setColor(color);
g2.setStroke(stroke);
g2.fill(shape);
g2.setColor(oldColor);
g2.setStroke(oldStroke);
}
}
You shouldn't be drawing lines by adding components. Components are things like panels, buttons etc.
See this tutorial on how to draw with Graphics2D: https://docs.oracle.com/javase/tutorial/2d/geometry/primitives.html
Your code adds three components but the panel is not big enough to show the other two components
panel.setPreferredSize(new Dimension(200, 600));
setSize(250, 800);

Deleting images from JFrame

I created one JFrame. and set layout shown in below code
this.setLayout(new GridLayout());
JPanel panel=new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new PicturePanel1());
JTabbedPane jtp=new JTabbedPane();
jtp.addTab("show Images", panel);
jtp.addTab("Compare Image", new JButton());
this.add(jtp);
I created another class that draws Images from particular location.
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
int k = 20,y=10;
for (int j = 0; j <= listOfFiles.length - 1; j++) {
g2.drawImage(b[j], k, y, 100, 100, null);
// add(new javax.swing.JCheckBox());
k = k + 120;
if(k>=960)
{
k=20;
y=y+120;
}
}
Its working fine. I want to delete Images when user clicks on particular Image.
This is my output window. I want to delete Image from list.
Here is an example I made (bored and tired of studying :)). It is by no means the best just a quick thing to show you an example, click the image you want to delete and then press the delete button or DEL to remove and image from the panel:
When app starts up (orange just shows focused label for hovering):
Image to delete is selected by clicking on the Label (Border becomes green highlighted and will remain this way until another label is clicked):
After delete button or key is pressed:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class JavaApplication5 {
public static void main(String[] args) {
createAndShowJFrame();
}
public static void createAndShowJFrame() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = createJFrame();
frame.setVisible(true);
}
});
}
private static JFrame createJFrame() {
JFrame frame = new JFrame();
//frame.setResizable(false);//make it un-resizeable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
ArrayList<BufferedImage> images = null;
try {
images = getImagesArrayList();
} catch (Exception ex) {
ex.printStackTrace();
}
final ImageViewPanel imageViewPanel = new ImageViewPanel(images);
JScrollPane jsp = new JScrollPane(imageViewPanel);
jsp.setPreferredSize(new Dimension(400, 400));
frame.add(jsp);
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
controlPanel.add(addLabelButton);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://icons.iconarchive.com/icons/deleket/sleek-xp-software/256/Yahoo-Messenger-icon.png")), 100, 100));
images.add(resize(ImageIO.read(new URL("https://upload.wikimedia.org/wikipedia/commons/6/64/Gnu_meditate_levitate.png")), 100, 100));
return images;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
class ImageViewPanel extends JPanel {
JLabel NO_IMAGES = new JLabel("No Images");
ArrayList<BufferedImage> images;
ArrayList<MyLabel> imageLabels;
public ImageViewPanel(ArrayList<BufferedImage> images) {
this.images = images;
imageLabels = new ArrayList<>();
for (BufferedImage bi : images) {
imageLabels.add(new MyLabel(new ImageIcon(bi), this));
}
layoutLabels();
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, true), "Delete pressed");
getActionMap().put("Delete pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
removeFocusedImageLabel();
}
});
}
void removeFocusedImageLabel() {
if (focusedLabel == null) {
return;
}
imageLabels.remove(focusedLabel);
remove(focusedLabel);
layoutLabels();
}
private void layoutLabels() {
if (imageLabels.isEmpty()) {
add(NO_IMAGES);
} else {
remove(NO_IMAGES);
for (JLabel il : imageLabels) {
add(il);
}
}
revalidate();
repaint();
}
private MyLabel focusedLabel;
void setFocusedLabel(MyLabel labelToFocus) {
if (focusedLabel != null) {
focusedLabel.setBorder(null);
focusedLabel.setClicked(false);
}
focusedLabel = labelToFocus;
focusedLabel.setBorder(new LineBorder(Color.GREEN));
}
}
class MyLabel extends JLabel {
private final ImageViewPanel imageViewPanel;
private boolean clicked = false;
public MyLabel(Icon image, ImageViewPanel imageViewPanel) {
super(image);
this.imageViewPanel = imageViewPanel;
initLabel();
}
public MyLabel(String text, ImageViewPanel imageViewPanel) {
super(text);
this.imageViewPanel = imageViewPanel;
initLabel();
}
private void initLabel() {
setFocusable(true);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
clicked = true;
imageViewPanel.setFocusedLabel(MyLabel.this);
}
#Override
public void mouseEntered(MouseEvent me) {
super.mouseEntered(me);
if (clicked) {
return;
}
setBorder(new LineBorder(Color.ORANGE));
//call for focus mouse is over this component
requestFocusInWindow();
}
});
addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
super.focusLost(e);
if (clicked) {
return;
}
setBorder(null);
}
});
}
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
public boolean isClicked() {
return clicked;
}
}
simply find the location (x, and y) and the size(width, and height) of image, then with the Graphics object (g2) fill a rectangle over the image drawn, like this
g2.setColor(this.getBackground());//set the color you want to clear the bound this point to JFrame/JPanel
g2.fillRect(x, y, width, height);
where x and y where is the location that images is located, and width and height are size of the picture

Categories

Resources