I'm trying to make a little animation on Java swing, which should move the drawString's string a little to left(to center), however, whenever I try to do it, the program just slowly opens and just jumps to the place where It should land eventually, so seemingly, there no animation occurs.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class IntroPanel extends JPanel {
private int x = 300;
private JButton exitButton, startButton;
private JPanel buttonsPanel;
public IntroPanel()
{
setPreferredSize( new Dimension( 300, 150));
setLayout( new BorderLayout());
buttonsPanel = new JPanel();
exitButton = new JButton( "Exit" );
startButton = new JButton( "Start" );
exitButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
startButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/**
* TODO GOES TO MAIN PANEL
*/
}
});
setBackground( new Color( 250, 250, 250) );
startButton.setPreferredSize( new Dimension(70, 40) );
exitButton.setPreferredSize( new Dimension(70, 40) );
Border padding = BorderFactory.createEmptyBorder(0, 0, 25, 0);
setBorder(padding);
buttonsPanel.setBackground( new Color( 250, 250, 250));
buttonsPanel.add(startButton);
buttonsPanel.add(exitButton);
add(buttonsPanel, BorderLayout.SOUTH);
animate();
}
public void animate()
{
for( int i = 1; i < 211; i++ )
{
x--;
repaint();
try
{
Thread.sleep(10);
}
catch(InterruptedException ex) { }
}
}
public void paintComponent( Graphics page )
{
Graphics2D gra = (Graphics2D) page;
gra.setFont( new Font( "Philosopher-BoldItalic", Font.ITALIC | Font.BOLD, 50 ) );
Color start = new Color( 50, 50, 50 );
Color end = new Color( 250, 250, 250 );
GradientPaint gradient =
new GradientPaint( 120, 100, start, 270, 270, end);
gra.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gra.setPaint( gradient );
gra.drawString("Geometrica", x, 100);
}
}
Main method:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame( "Geometrica" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 250);
frame.setBackground( new Color(250, 250, 250) );
frame.setLocationRelativeTo(null);
frame.getContentPane().add( new IntroPanel() );
frame.setVisible(true);
}
}
Thank you!
Call the animate method after the frame is made visible from outside the object.
Also you need to call super.paintComponent(page); inside your animate method like it says in the Javadoc then you'll get the desired result.
Main:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame( "Geometrica" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 250);
frame.setBackground( new Color(250, 250, 250) );
frame.setLocationRelativeTo(null);
IntroPanel p=new IntroPanel();
frame.getContentPane().add(p);
frame.setVisible(true);
p.animate();
}
}
IntroPanel:
public class IntroPanel extends JPanel {
private int x = 300;
private JButton exitButton, startButton;
private JPanel buttonsPanel;
public IntroPanel()
{
setPreferredSize( new Dimension( 300, 150));
setLayout( new BorderLayout());
buttonsPanel = new JPanel();
exitButton = new JButton( "Exit" );
startButton = new JButton( "Start" );
exitButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
startButton.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/**
* TODO GOES TO MAIN PANEL
*/
}
});
setBackground( new Color( 250, 250, 250) );
startButton.setPreferredSize( new Dimension(70, 40) );
exitButton.setPreferredSize( new Dimension(70, 40) );
Border padding = BorderFactory.createEmptyBorder(0, 0, 25, 0);
setBorder(padding);
buttonsPanel.setBackground( new Color( 250, 250, 250));
buttonsPanel.add(startButton);
buttonsPanel.add(exitButton);
add(buttonsPanel, BorderLayout.SOUTH);
}
public void animate()
{
super.paintComponent(page);
for( int i = 1; i < 211; i++ )
{
x--;
repaint();
try
{
Thread.sleep(10);
}
catch(InterruptedException ex) { }
}
}
public void paintComponent( Graphics page )
{
Graphics2D gra = (Graphics2D) page;
gra.setFont( new Font( "Philosopher-BoldItalic", Font.ITALIC | Font.BOLD, 50 ) );
Color start = new Color( 50, 50, 50 );
Color end = new Color( 250, 250, 250 );
GradientPaint gradient =
new GradientPaint( 120, 100, start, 270, 270, end);
gra.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gra.setPaint( gradient );
gra.drawString("Geometrica", x, 100);
}
}
Related
I have program that resizes a button.
I just want to keep the center point in the center.
Perhaps by moving it by the distance between the center and…the upper left corner
Like when I resize the box in JSwing.
I want the center point to remain in the same spot.
How can I change the x, y of the upper left coordinates as the box increases
while keeping the center point in the same spot?
What woulf be the steps to get this done?
I guess my using the distance between the center and the upper left corner but how would that help
https://pastebin.com/0r8Vhez7
here's the code for context.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Buttons
{
public static void main(String[] args)
{
//Buttons.JLabelExperiments JE = new Buttons().new JLabelExperiments();
//JE.ASY();
Buttons.JButtonExperiments JEB = new Buttons().new JButtonExperiments();
JEB.Print();
}
class JLabelExperiments
{
public static void ASY()
{
JFrame frame = new JFrame();
frame.setSize(1200, 1200);
JLabel lol = new JLabel(new Scanner(System.in).nextLine());
lol.setBounds(500, 400, 380, 200);
lol.setBorder(BorderFactory.createLineBorder(Color.BLACK));
frame.add(lol);
JSlider J = new JSlider(JSlider.VERTICAL, 0, 200, 0);
J.setMinorTickSpacing(2);
J.setMajorTickSpacing(10);
J.setPaintLabels(true);
J.setPaintTicks(true);
J.setPaintTrack(true);
J.addChangeListener(e ->
{
{
lol.setHorizontalAlignment(J.getValue());
JLabel LOL = new JLabel(String.valueOf(J.getValue()));
LOL.setBounds(700, 700, 100, 150);
frame.add(LOL);
}
});
frame.add(J);
JSlider j = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
j.setMajorTickSpacing(10);
j.setMinorTickSpacing(2);
j.setPaintTrack(true);
j.setPaintTicks(true);
j.setPaintLabels(true);
j.setBounds(200, 700, 400, 100);
j.addChangeListener(e ->
{
lol.setVerticalAlignment(j.getValue());
JLabel HUH = new JLabel(String.valueOf(j.getValue()));
HUH.setBounds(950, 700, 100, 150);
frame.add(HUH);
});
System.out.printf("%1$s, %2$s", J.getChangeListeners(), j.getChangeListeners());
frame.add(j);
frame.setVisible(true);
}
public static void asy()
{
}
}
class JButtonExperiments
{
public static void Print()
{
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(1200, 1200);
JButton B = new JButton("w");
B.setBounds(600, 600, 160, 160);
B.setText(new Scanner(System.in).nextLine());
frame.add(B);
JSlider width = new JSlider(SwingConstants.VERTICAL, 0, 0, 100);
JSlider height = new JSlider(JSlider.VERTICAL, 0, 0, 100);
width.setLocation(200, 600);
JLabel widthBox = new JLabel("Width");
widthBox.setBounds(20, 500, 120, 120);
height.setLocation(1000, 600);
JLabel heightBox = new JLabel("Height");
heightBox.setBounds(1180, 500, 120, 120);
width.setSize(100, 600);
height.setSize(100, 600);
frame.setVisible(true);
AtomicInteger counter = new AtomicInteger();
B.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
counter.getAndIncrement();
if(counter.get() == 1)
{
frame.add(width, height);
}
if(counter.get() == 3)
{
width.addChangeListener(E ->
{
B.setSize(B.getWidth()+width.getValue(), B.getHeight());
}
);
height.addChangeListener(E ->
{
B.setSize(B.getWidth(), B.getHeight()+height.getValue());
}
);
}
}
});
}
}
}
This was just a practice project but it seems this information may be more useful so please before forgive any lack of readability.
This code when run will make a button if you click it twice it will activate sliders that allow you to change the width and height of the button. By adding the value of the sliders to the value of the Button's width and height.
Use an appropriate layout manager, get it for free...
Now your button is always in the middle...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(new Insets(50, 50, 50, 50)));
setLayout(new GridBagLayout());
JButton btn = new JButton("Button in the middle");
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 100;
gbc.ipady = 100;
add(btn, gbc);
}
}
}
Change the text and see what happens ... for free
See Laying Out Components Within a Container
When I run my java program, two JFrames are showing, the JFrame that I created and another one that is blank that I cannot close. I think this error also has something to do with my JFrame that I created with components in it, not show when I run the program, instead the one showing is the blank JFrame. How do I fix this?
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import java.awt.Font;
public class trial extends Frame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
JButton newButton1, newButton2, newButton3,newButton4,newButton5,newButton6,newButton7,newButton8,newButton9;
Icon ic1=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png");
Icon ic2=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png");
Icon ic3=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png");
Icon ic4=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png");
Icon ic5=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png");
Icon ic6=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png");
Icon ic7=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png");
Icon ic8=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png");
Icon pink=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\c9.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trial window = new trial();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public trial() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 986, 677);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
newButton1 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png"));
newButton1.setBounds(43, 37, 150, 150);
newButton2 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png"));
newButton2.setBounds(191,37, 150, 150);
newButton3 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png"));
newButton3.setBounds(340,37, 150, 150);
newButton4 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png"));
newButton4.setBounds(43,186, 150, 150);
newButton5 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png"));
newButton5.setBounds(191,186, 150, 150);
newButton6 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png"));
newButton6.setBounds(340,186, 150, 150);
newButton7 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png"));
newButton7.setBounds(43,335, 150, 150);
newButton8 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png"));
newButton8.setBounds(191,335,150, 150);
newButton9 = new JButton(pink);
newButton9.setBounds(340,335,150, 150);
newButton1.addActionListener(this);
newButton2.addActionListener(this);
newButton3.addActionListener(this);
newButton4.addActionListener(this);
newButton5.addActionListener(this);
newButton6.addActionListener(this);
newButton7.addActionListener(this);
newButton8.addActionListener(this);
newButton9.addActionListener(this);
frame.getContentPane().add(newButton1);frame.getContentPane().add(newButton2);frame.getContentPane().add(newButton3);frame.getContentPane().add(newButton4);frame.getContentPane().add(newButton5);frame.getContentPane().add(newButton6);
frame.getContentPane().add(newButton7);frame.getContentPane().add(newButton8);frame.getContentPane().add(newButton9);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
DrumInfo a = new DrumInfo();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnNewButton.setIcon(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\drums.png"));
btnNewButton.setBounds(597, 37, 300, 277);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Click the picture to find out what's the picture about!");
lblNewLabel.setFont(new Font("Berlin Sans FB Demi", Font.PLAIN, 15));
lblNewLabel.setBounds(563, 315, 382, 45);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton_1 = new JButton("BACK");
btnNewButton_1.setBounds(412, 563, 156, 63);
frame.getContentPane().add(btnNewButton_1);
JButton btnCategories = new JButton("CATEGORIES");
btnCategories.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Puzzle2 a = new Puzzle2();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnCategories.setBounds(604, 563, 156, 63);
frame.getContentPane().add(btnCategories);
JButton btnNext = new JButton("NEXT");
btnNext.setBounds(789, 563, 156, 63);
frame.getContentPane().add(btnNext);
setSize(600,500);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==newButton1){
Icon s1 = newButton1.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton1.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton1.setIcon(pink);
}
}
if(e.getSource()==newButton2){
Icon s1 = newButton2.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton2.setIcon(pink);
}
}
if(e.getSource()==newButton3){
Icon s1 = newButton3.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton3.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton3.setIcon(pink);
}
}
if(e.getSource()==newButton4){
Icon s1 = newButton4.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton4.setIcon(pink);
}
}
if(e.getSource()==newButton5){
Icon s1 = newButton5.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton5.setIcon(pink);
}
}
if(e.getSource()==newButton6){
Icon s1 = newButton6.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton6.setIcon(pink);
}
}
if(e.getSource()==newButton7){
Icon s1 = newButton7.getIcon();
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton7.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton7.setIcon(pink);
}
}
if(e.getSource()==newButton8){
Icon s1 = newButton8.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton8.setIcon(pink);
}
}
if(e.getSource()==newButton9){
Icon s1 = newButton9.getIcon();
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton9.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton9.setIcon(pink);
}
}
if(newButton1.getIcon().equals(ic1)&&newButton2.getIcon().equals(ic2)&&newButton3.getIcon().equals(ic3)&&newButton4.getIcon().equals(ic4)&&newButton5.getIcon().equals(ic5)&&newButton6.getIcon().equals(ic6)&&newButton7.getIcon().equals(ic7)&&newButton8.getIcon().equals(ic8)&&newButton9.getIcon().equals(pink)) {
JOptionPane.showMessageDialog(this,"Congratulations! You won.");
}
}
}
for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.
First of all I am making a minigame with the Five Nights At Freddy's graphics and jump scares. I already know how to import and draw a picture (png and etc). The only one I don't know how to import, are gifs.
Here Is My Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Minigame extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
GameEvents gameEvents = new GameEvents();
Timer gameTimer = new Timer(1, gameEvents);
int i = 0;
int horizontalposition = 500;
int verticalposition = 500;
BufferedImage Picture;
BufferedImage Picture2;
BufferedImage Picture3;
BufferedImage Picture4;
BufferedImage Picture5;
BufferedImage Picture6;
//Don't forget to declare your variables!
Minigame()
{
gameTimer.start();
this.addKeyListener(gameEvents);
try
{
Picture = ImageIO.read(getClass().getResource("Child.gif"));
Picture2 = ImageIO.read(getClass().getResource("Freddycake_Gif.gif"));
Picture3 = ImageIO.read(getClass().getResource("Purple_man.png"));
Picture4 = ImageIO.read(getClass().getResource("Cake_Child_Idle.png"));
Picture5 = ImageIO.read(getClass().getResource("Cake_Child.gif"));
//The format for this is Picture = ImageIO.read(getClass().getResource("NameOfFile.typeoffile"));
}
catch (IOException e)
{
System.out.println("Pictures failed to load");
}
}
#Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0,0,this.getWidth(), this.getHeight());
///g.drawImage(Picture, horizontalposition, verticalposition, 100, 150, null);
g.drawImage(Picture, 200, 10, 70, 100, null);
g.drawImage(Picture, 200, 100, 70, 100, null);
g.drawImage(Picture, 200, 200, 70, 100, null);
g.drawImage(Picture, 200, 300, 70, 100, null);
g.drawImage(Picture, 200, 400, 70, 100, null);
g.drawImage(Picture, 200, 500, 70, 100, null);
g.drawImage(Picture2, horizontalposition, verticalposition, 100, 150, null);
g.drawImage(Picture3, 1100, 50, 100, 150, null);
g.drawImage(Picture4, 900, 50, 100, 150, null);
//g.drawImage(Picture5, 900, 50, 100, 150, null);
}
public class GameEvents implements ActionListener, KeyListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
#Override
public void keyPressed(KeyEvent key) //stuff inside here happens when a key is pressed
{
if(key.getKeyChar()=='d')
{
horizontalposition=horizontalposition+50;
}
if(key.getKeyChar()=='s')
{
verticalposition=verticalposition+50;
}
if(key.getKeyChar()=='w')
{
verticalposition=verticalposition-50;
}
if(key.getKeyChar()=='a')
{
horizontalposition=horizontalposition-50;
}
if(horizontalposition<0)
{
horizontalposition=0;
}
System.out.println(key.getKeyChar());
System.out.println('d');
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
public static void main(String[] args)
{
JFrame f = new JFrame("Java Graphics Example Project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Minigame p = new Minigame();
f.setSize(1500,700);
f.add(p);
f.setVisible(true);
p.requestFocusInWindow();
}
}
Any yes, I already know how to do g.drawImage();
Look up this answer response: Show animated GIF
If you don't feel like it, I'll just put the code of the person who replied here. However, they explain it there and really go in detail.
THIS IS THE CODE FROM STACKER WHO EXPLAINED IT ON THE LINK I GAVE YOU
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("<URL to your Animated GIF>");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
I am currently trying to draw a figure by clicking a button. My problems occurs when I click the button and it does not show up in the panel, but I know it's drawing because it runs through the loop.
The drawing will occur when I request the panel to draw it inside the constructor, but not inside the button, inside the constructor
If i put the code in the method "stuff()" inside the constructor it will draw everything just fine.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame{
public static void main(String[]args){
MainFrame f = new MainFrame();
}
public JFrame frame = new JFrame();
public JPanel panel = new JPanel(new BorderLayout());
public MainFrame(){
JButton button1 = new JButton("Shweet Button");
button1.setBounds(185, 10, 130, 20);
frame.setBounds(1680/4,1050/4,500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setBackground(Color.black);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
frame.add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stuff();
}
});
}
public void stuff(){
for(int i = 0;i<1000;i++){
panel.add(new paintComponent());
panel.setBackground(Color.black);
frame.repaint();
try {
Thread.sleep(80);
} catch (InterruptedException e1){e1.printStackTrace();}
}
}
static class paintComponent extends JComponent{
public int options;
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
if(options == 0){
options = 1;
g2.drawOval(50, (JFrame.HEIGHT/2)+100, 50, 50);
g2.drawOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawArc(65, (JFrame.HEIGHT/2)+130, 100, 0, 140, 30);
g2.drawLine(75, (JFrame.HEIGHT/2)+150, 75, (JFrame.HEIGHT/2)+220);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 100, (JFrame.HEIGHT/2)+160);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 65, (JFrame.HEIGHT/2)+210);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 50, (JFrame.HEIGHT/2)+260);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 100, (JFrame.HEIGHT/2)+260);
}else if(options == 1){
options = 0;
g2.drawOval(50, (JFrame.HEIGHT/2)+100, 50, 50);
g2.drawOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawArc(65, (JFrame.HEIGHT/2)+130, 100, 0, 140, 30);
g2.drawLine(75, (JFrame.HEIGHT/2)+150, 75, (JFrame.HEIGHT/2)+220);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 100, (JFrame.HEIGHT/2)+180);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 65, (JFrame.HEIGHT/2)+210);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 50, (JFrame.HEIGHT/2)+260);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 100, (JFrame.HEIGHT/2)+260);
}
}
}
}
You are blocking the Event Dispatching Thread, which is responsible for, amongst other things, processing paint requests.
You should never do anything like this...
for(int i = 0;i<1000;i++){
panel.add(new paintComponent());
panel.setBackground(Color.black);
frame.repaint();
try {
Thread.sleep(80);
} catch (InterruptedException e1){e1.printStackTrace();}
}
Within the EDT. Apart from the fact you are adding multiple new components to your UI every 80 milliseconds, you are also blocking the thread that is responsible for updating your screen...
Check out Concurrency in Swing for more details.
Animation of this type should be handled by a javax.swing.Timer.
Custom painting should be performed in the paintComponent method, as a general rule. You should also be calling super.paintXxx first as a matter of course. There's a lot of working going in the background that needs to be taken care of, especially if the component is transparent.
Check out Performing Custom Painting and Painting in AWT and Swing for more details.
Save your sanity and learn how to use layout managers, they will make your life easier in the long run.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
MainFrame f = new MainFrame();
}
});
}
public JFrame frame = new JFrame();
public JPanel panel = new JPanel(new BorderLayout());
private WavePane waver;
public MainFrame() {
waver = new WavePane();
JButton button1 = new JButton("Shweet Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setBackground(Color.black);
frame.add(button1, BorderLayout.SOUTH);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stuff();
}
});
panel.add(waver);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void stuff() {
// for (int i = 0; i < 1000; i++) {
// panel.add(new paintComponent());
// panel.setBackground(Color.black);
// frame.repaint();
// try {
// Thread.sleep(80);
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }
// }
waver.walk(!waver.isWaving());
}
public class WavePane extends JComponent {
private int options;
private Timer timer;
public WavePane() {
setOpaque(false);
timer = new Timer(80, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("tick");
options++;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void walk(boolean walk) {
if (walk) {
timer.start();
} else {
timer.stop();
}
}
public boolean isWaving() {
return timer.isRunning();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
int height = getHeight();
if (options % 2 == 0) {
g2.drawOval(50, 100, 50, 50);
g2.drawOval(60, 110, 8, 8);
g2.fillOval(60, 110, 8, 8);
g2.drawOval(80, 110, 8, 8);
g2.fillOval(80, 110, 8, 8);
g2.drawArc(65, 130, 100, 0, 140, 30);
g2.drawLine(75, 150, 75, 220);
g2.drawLine(75, 180, 100, 160);
g2.drawLine(75, 180, 65, 210);
g2.drawLine(75, 220, 50, 260);
g2.drawLine(75, 220, 100, 260);
} else {
g2.drawOval(50, 100, 50, 50);
g2.drawOval(60, 110, 8, 8);
g2.fillOval(60, 110, 8, 8);
g2.drawOval(80, 110, 8, 8);
g2.fillOval(80, 110, 8, 8);
g2.drawArc(65, 130, 100, 0, 140, 30);
g2.drawLine(75, 150, 75, 220);
g2.drawLine(75, 180, 100, 180);
g2.drawLine(75, 180, 65, 210);
g2.drawLine(75, 220, 50, 260);
g2.drawLine(75, 220, 100, 260);
}
}
}
}
You shouldn't be using JFrame.HEIGHT this actually has nothing to do with the frames height, but is part of the ImageObserver support... or any type of magic number for that matter