I have a JPanel where I have array of buttons. It's a kind of memory game, and I wont to show some few frames of animation, for example Double Point.
Here is a part of code:
This animation is that some text is slowly showing and disappearing (I used also Alpha channel in those images) , but I don't know why when id should slowly disapearing it didn't like if of this image stay there.
public void paintComponent(Graphics g)
{
//Image img = new ImageIcon("res\\double.png").getImage();
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
t.start();
Image img2 = new ImageIcon("res\\double\\double_0000"+i+".png").getImage();
g.drawImage(img2, 0, 0, this.getWidth(), this.getHeight(), null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
t.restart();
repaint();
}
}
public class ScoreWindow extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
final public JButton btnScoreReturnButton;
final public JLabel ScoreLabel;
//final public JScrollBar scrollScoreBar;
private String[] data;
Timer t;
String sth="";
int i=0;
int datapower=0;
public ScoreWindow() {
btnScoreReturnButton = new JButton("Powrót");
SpringLayout sl_ScoreWindow = new SpringLayout();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, btnScoreReturnButton, 27, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, btnScoreReturnButton, 11, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, btnScoreReturnButton, 100, SpringLayout.WEST, this);
this.setLayout(sl_ScoreWindow);
this.add(btnScoreReturnButton);
ScoreLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, ScoreLabel, 64, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, ScoreLabel, 111, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, ScoreLabel, -15, SpringLayout.SOUTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, ScoreLabel, -76, SpringLayout.EAST, this);
this.add(ScoreLabel);
JLabel SubtitleLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, SubtitleLabel, 20, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, SubtitleLabel, 80, SpringLayout.WEST,ScoreLabel);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, SubtitleLabel, 60, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, SubtitleLabel, -150, SpringLayout.EAST, this);
SubtitleLabel.setForeground(Color.BLACK);
SubtitleLabel.setHorizontalAlignment(JLabel.CENTER);
SubtitleLabel.setVerticalAlignment(JLabel.CENTER);
SubtitleLabel.setFont(ScoreLabel.getFont().deriveFont(32.0f));
SubtitleLabel.setText("Najlepsze Wyniki");
this.add(SubtitleLabel);
t=new Timer(100,this);
}
public void ReadData()
{
data = new String[20];
FileReader readFile=null;
BufferedReader reader =null;
String temp;
try
{
readFile=new FileReader("highscore.dat");
reader=new BufferedReader(readFile);
int i=0;
while((temp=reader.readLine())!=null)
{
data[i]=temp;
i++;
}
}
catch(Exception e)
{
data[0] ="Nobody:0";
}
finally
{
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void LoadData() {
String stream="<html>";
//System.out.print(data[0]+"\n");
for(int i=0;i<data.length;i++)
{
if(data[i]!=null)
{
if(i==0)
stream=stream+data[i];
//tream=stream+data[i];
else if(i>0)
stream=stream+"<br>"+data[i];
}
}
stream+="</html>";
System.out.print(stream+"\n");
ScoreLabel.setHorizontalAlignment(JLabel.CENTER);
ScoreLabel.setVerticalAlignment(JLabel.CENTER);
ScoreLabel.setForeground(Color.WHITE);
ScoreLabel.setFont(ScoreLabel.getFont().deriveFont(16.0f));
ScoreLabel.setText(stream);
ScoreLabel.setOpaque(false);
}
public int AmoutofData()
{
String amount[] = ScoreLabel.getText().split("<br>");
return amount.length;
}
public void paintComponent(Graphics g)
{
t.start();
if(i<10)
sth="0"+i;
else
sth=i+"";
Image img2 = new ImageIcon("res\\double\\double_000"+sth+".png").getImage();
g.drawImage(img2, i, i, 100, 100, null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
i=0;
repaint();
}
}
Related
I have a print preview made by JPanel, JDialog that run error free but doesn't show up after pack();.
I know it's a bit long, but you can just skip to PrintPreview method, others are just there to know more detail of how I control.
Pls help, I don't know why it doesn't show up on the screen. Anyone please help thanks so much. ^_^
private PageFormat pf;
private Book pg;
private int pageIndex;
private int totalPages;
private double scaler;
private String title;
private JTextField pageInput;
private JTextField zoomInput;
private PreviewPanel pp;
private JLabel statusBar;
Start Here
public void PrintPreview(String title, Book pg, int pageIndex) {
this.title = title;
setTitle(title + " - Print Preview");
scaler = .5;
this.pg = pg;
this.pageIndex = pageIndex;
this.totalPages = pg.getNumberOfPages();
pf = pg.getPageFormat(pageIndex);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
setLayout(new BorderLayout());
pp = new PreviewPanel();
add(new JScrollPane(pp), BorderLayout.CENTER);
JPanel topBar = new JPanel();
topBar.setLayout(new BorderLayout());
add(topBar, BorderLayout.NORTH);
JPanel leftTop = new JPanel();
JPanel rightTop = new JPanel();
topBar.add(leftTop, BorderLayout.WEST);
topBar.add(rightTop, BorderLayout.EAST);
leftTop.add(new JLabel("Page:"));
Insets pageButtonInsets = new Insets(0, 2, 0, 2);
JButton pageBack = new JButton("<");
pageBack.setMargin(pageButtonInsets);
pageBack.setActionCommand("back");
pageBack.addActionListener(this);
JButton pageForward = new JButton(">");
pageForward.setMargin(pageButtonInsets);
pageForward.setActionCommand("forward");
pageForward.addActionListener(this);
pageInput = new JTextField(Integer.toString(pageIndex+1));
pageInput.setPreferredSize(new Dimension(30, 20));
pageInput.setActionCommand("page");
pageInput.addActionListener(this);
leftTop.add(pageBack);
leftTop.add(pageInput);
leftTop.add(pageForward);
rightTop.add(new JLabel("Zoom:"));
zoomInput = new JTextField((int)(scaler*100)+"%");
zoomInput.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomInput);
JButton zoomSet = new JButton("Set");
zoomSet.setMargin(new Insets(0, 0, 0, 0));
zoomSet.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomSet);
zoomSet.setActionCommand("zoom");
zoomSet.addActionListener(this);
JPanel lowerBar = new JPanel();
lowerBar.setLayout(new BorderLayout());
lowerBar.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
statusBar = new JLabel("Ag"); // temporary label for setting size of status bar
lowerBar.add(statusBar, BorderLayout.CENTER);
add(lowerBar, BorderLayout.SOUTH);
JButton license = new JButton("<html>©</html>");
license.setActionCommand("license");
license.setMargin(new Insets(0, 0, 0, 0));
license.addActionListener(this);
lowerBar.add(license, BorderLayout.WEST);
JButton print = new JButton("Print...");
print.setActionCommand("print");
print.setMargin(new Insets(4, 0, 4, 0));
print.addActionListener(this);
lowerBar.add(print, BorderLayout.EAST);
pack();
//setVisible(true);
}
End here
private void updateStatusBar() {
updateStatusBar("Page " + (pageIndex+1) + " of " + totalPages);
}
private void updateStatusBar(String s) {
updateStatusBar(s, Color.black);
}
private void updateStatusBar(String s, Color c) {
statusBar.setText(s);
statusBar.setForeground(c);
}
private void print() {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPageable(pg);
pj.setJobName(title);
if (pj.printDialog()) {
try {
pj.print();
} catch (PrinterException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Could not print.\nSee the Java error console for details.", "error", JOptionPane.ERROR_MESSAGE);
}
}
}
private class PreviewPanel extends JPanel {
private static final long serialVersionUID = 1L;
public PreviewPanel() {
resetPreferredSize();
}
public void resetPreferredSize() {
setPreferredSize(new Dimension((int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler)));
}
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D)g1;
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.white);
g.fillRect(0, 0, (int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler));
g.setColor(Color.black);
try {
g.scale(scaler, scaler);
pg.getPrintable(pageIndex).print(g, pf, pageIndex);
updateStatusBar();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Page index out of range", 10, 30);
updateStatusBar("Page index out of range", Color.red);
} catch (PrinterException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Printer error", 10, 30);
updateStatusBar("Printer error", Color.red);
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getActionCommand().equals("page")) {
// change page
try {
pageIndex = Integer.parseInt(pageInput.getText())-1;
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("back")) {
if (pageIndex > 0) {
pageIndex--;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("forward")) {
if (pageIndex < totalPages - 1) {
pageIndex++;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("zoom")) {
// change zoom setting
try {
scaler = Double.parseDouble(zoomInput.getText().replaceAll("%", ""))// 100.0;
pp.resetPreferredSize();
pp.revalidate();
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("license")) {
JOptionPane.showMessageDialog(this, LICENSE);
} else if (arg0.getActionCommand().equals("print")) {
print();
}
}
Yeah, I figured it out. Hahahaha Actually it does pop out but behind other foreround application....hahahaa finally its done.
public class BelishaBeacon {
public class Design extends JPanel {
private boolean alternateColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(163, 180, 16, 45);
Rectangle box2 = new Rectangle(163, 225, 16, 45);
Rectangle box3 = new Rectangle(163, 270, 16, 45);
Rectangle box4 = new Rectangle(163, 315, 16, 45);
Rectangle box5 = new Rectangle(163, 360, 16, 45);
Rectangle box6 = new Rectangle(163, 405, 16, 45);
//drawing the shapes
Ellipse2D.Double ball = new Ellipse2D.Double(a, b, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.YELLOW);
g2.fill(ball);
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
}
public void alternateColors() {
alternateColors = true;
repaint();
}
}
public BelishaBeacon() {
//frame
JFrame frame = new JFrame();
frame.setSize(330, 550);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Design shapes = new Design();
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
private void swapColors() {
boolean swapColors;
Graphics g2;
if (swapColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
}
};
Thread t = new Thread(r);
t.start();
}});
JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.alternateColors();
}
});
I have created an action listener for my jbutton steady and flash, I am just trying to created a method for swapColors for it to be initialised in the jbutton flash. The swapcolos method initially should alternate between the colours orange and grey
You wrote that you want it to flash every 0.5 seconds.
To do so you need to start new thread for example
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
};
Thread t = new Thread(r);
t.start();
}});
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
Should be:
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
AND
public void alternateColors() {
alternateColors = true;
repaint();
}
Should be:
public void alternateColors() {
//Flip boolean alternateColors
alternateColors = !alternateColors;
repaint();
}
I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:
Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.
For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.
WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;
public class WheelBuilder extends JApplet{
public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;
public void init()
{
resize(540,600);
spin = new JButton("SPIN!");
spin.addActionListener(new spinListener());
Container cp = getContentPane();
cp.setVisible(true);
cp.setBackground((Color.GREEN).darker().darker());
Abet = new JButton("+BET+");
Abet.addActionListener(new aListener());
Sbet = new JButton("-BET-");
Sbet.addActionListener(new sListener());
cp.add(Sbet);
cp.add(spin);
cp.add(Abet);
cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
page.setColor((Color.GREEN).darker().darker());
page.fillRect(0, 0, 1000, 1000);
setBackground((Color.GREEN).darker().darker());
wheel.paintWheel(page, wheel.getStatus());
page.setColor(Color.BLACK);
page.drawString("TOTAL: "+total, 400, 50);
page.drawString("Current Bet: "+Tbet, 400, 25);
page.drawString("Last Spin:", 50, 25);
page.setColor(Color.WHITE);
page.fillOval(260, 75, 20, 20);
page.fillRect(50, 35, 60, 25);
page.setColor(color);
page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
int countEnd = randomSpin();
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
if (wheel.getStatus())
{
color = Color.RED;
last = (int)(Math.random()*7)*2+1;
}
else
{
color = Color.BLACK;
last = (int)(Math.random()*7)*2+2;
}
}
public void changeWheel()
{
int countEnd = randomSpin();
if (count <= countEnd)
{
wheel.setStatus(!(wheel.getStatus()));
repaint();
count++;
}
}
public int randomSpin()
{
return ((int)(Math.random()*2)+21);
}
}
public class aListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet <= total-50)
{
Tbet+=50;
}
last = 0;
repaint();
}
}
public class sListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet > 50)
{
Tbet-=50;
}
last = 0;
repaint();
}
}
}
RouletteWheel
import javax.swing.JApplet;
import java.awt.*;
public class RouletteWheel extends JApplet {
public boolean status;
public void paintWheel(Graphics page, boolean status)
{
if (status){
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.BLACK);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.setColor(Color.RED);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
if (!status)
{
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.RED);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
}
public boolean getStatus()
{
return status;
}
public void setStatus(boolean s)
{
status = s;
}
}
How can I create basic animation in Java?
Currently i am trying to implement a basic animation program using swing in Java.
But i am not getting whether my logic for program in correct or not.
My program implements Runnable, ActionListener interfaces and also extends JApplet.
I want to know that, is it necessary to differentiate start method of JApplet and Runnable?
And if yes then why..?
My program is basic balloon program, when I click on start button balloons start moving upward and comes to floor again. This will be continue till i press stop button.
Here is my code.
public class Balls extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
JPanel btnPanel=new JPanel();
static boolean flag1=true;
static boolean flag2=true;
static boolean flag3=false;
static int h;
static int temp=10;
Thread t=new Thread(this);
JButton start;
JButton stop;
public void init()
{
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't create GUI because of exception");
System.exit(0);
}
}
private void makeGUI() {
start=new JButton("start");
stop=new JButton("stop");
btnPanel.add(start);
btnPanel.add(stop);
add(btnPanel,BorderLayout.NORTH);
}
public void run()
{
while(true)
{
if(flag1)
{
repaint();
flag1=false;
}
else
{
try
{
wait();
flag3=true;
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Error ocuured !!\n Exiting..");
System.exit(0);
}
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h=Integer.parseInt(getParameter("height"));
if (flag1)
{
g.setColor(Color.RED);
g.fillOval(10,h,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,h,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h,60,40);
g.setColor(Color.pink);
g.fillOval(370,h,65,45);
flag1=false;
}
else
{
g.setColor(Color.RED);
g.fillOval(10,h-temp,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h-temp,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h-temp,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,355,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h-temp,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h-temp,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h-temp,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h-temp,60,40);
g.setColor(Color.pink);
g.fillOval(370,h-temp,65,45);
if(flag2 && temp<=400)
{
temp+=10;
if(temp==400)
{
flag2=false;
}
}
else if(!flag2)
{
temp-=10;
if(temp==10)
{
flag2=true;
}
}
else
{
}
}
}
public void start()
{
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.start();
if(flag3)
{
notify();
}
}
});
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag1=false;
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
repaint();
t=null;
}
}
});
}
}
1) Use SwingTimer as recommended instead of your Runnable implementation.
2) Read about custom painting , and here
3) draw at the JPanel instead of on JFrame
I have changed your code, examine it. I think, that it does what you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Balls extends JApplet {
private static final long serialVersionUID = 1L;
JPanel btnPanel = new JPanel();
static boolean flag1 = true;
static boolean flag2 = true;
static boolean flag3 = false;
static int h;
static int temp = 10;
JButton start;
JButton stop;
private Timer timer;
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
makeGUI();
}
});
}
private void makeGUI() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
});
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.stop();
}
});
btnPanel.add(start);
btnPanel.add(stop);
add(new MyPanel(), BorderLayout.CENTER);
add(btnPanel, BorderLayout.NORTH);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = Integer.parseInt(getParameter("height"));
if (flag1) {
g.setColor(Color.RED);
g.fillOval(10, h, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, h, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h, 65, 45);
flag1 = false;
} else {
g.setColor(Color.RED);
g.fillOval(10, h - temp, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h - temp, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h - temp, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, 355, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h - temp, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h - temp, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h - temp, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h - temp, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h - temp, 65, 45);
if (flag2 && temp <= 400) {
temp += 10;
if (temp == 400) {
flag2 = false;
}
} else if (!flag2) {
temp -= 10;
if (temp == 10) {
flag2 = true;
}
} else {
}
}
}
}
}
i want to add a image at 615,50 in my applet . image name is logo1.jpg . but the following code only prints d image.. when i compile and then run using applet viewer. only the image logo1 shows at d spot. the rest code doesnt work. however if i remove the image . then the code works fine. i think theres some problem with the paint() function . if i use ImageIcon and then add it into a label and set that label to the location,then it works fine in the appletviewer but as soon as i open it in a webbrowser, an IO Error appears
"access denied("java.io.FilePermission" "logo1.jpg" "read" ). pls help. image size is 126,126.
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
public class site extends Applet implements MouseListener, Runnable
{
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JLabel l21;
String str;
String s1;
String s2;
String s3;
Thread th;
int x;
int vt;
int hr;
int yx=75;
ImageIcon I;
Image image;
public void init()
{
setLayout(null);
addMouseListener(this);
loadImage();
//I=new ImageIcon("logo1.jpg");
l1 = new JLabel("2");
l1.setBounds(433, yx, 50, 50);
l1.setFont(new Font("Sketch Block", Font.PLAIN, 50));
l1.setForeground(Color.red);
add(l1);
l21=new JLabel(I);
l21.setBounds(630,50,126,126);;
add(l21);
l2 = new JLabel("0");
l2.setBounds(483, yx, 50, 50);
l2.setFont(new Font("Sketch Block", 0, 50));
l2.setForeground(Color.blue);
add(l2);
l3 = new JLabel("1");
l3.setBounds(543, yx, 50, 50);
l3.setFont(new Font("Sketch Block", 0, 50));
l3.setForeground(Color.magenta);
add(l3);
l4 = new JLabel("3");
l4.setBounds(583, yx, 50, 50);
l4.setFont(new Font("Sketch Block", 0, 50));
l4.setForeground(Color.cyan);
add(l4);
l5 = new JLabel("Impressions");
l5.setBounds(770, yx, 400, 50);
l5.setFont(new Font("Sketch Block", 0, 50));
l5.setForeground(Color.black);
add(l5);
l6 = new JLabel("March");
l6.setBounds(683, yx, 200, 50);
l6.setFont(new Font("Sketch Block", 0, 50));
l6.setForeground(Color.black);
th = new Thread(this);
}
public void loadImage()
{
URL url = getClass().getResource("logo1.jpg");
image = getToolkit().getImage(url);
}
public void paint(Graphics g)
{
g.drawImage(image, 615,50, this);
}
public void mouseClicked(MouseEvent me)
{
vt=me.getY();
hr=me.getX();
try
{
final URI uri = new URI("file:///E:/site/1.html");
final URI uri1 = new URI("file:///E:/site/2.html");
final URI uri2 = new URI("file:///E:/site/3.html");
if(hr<=468 && hr>=427)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri);
}
catch (Exception ex)
{
}
}
}
if(hr>=468 && hr<=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri1);
}
catch (Exception ex)
{
}
}
}
if(hr<=577 && hr>=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri2);
}
catch (Exception ex)
{
}
}
}
}
catch(Exception e)
{
}
}
public void mouseEntered(MouseEvent me)
{
th = new Thread(this);
th.start();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseExited(MouseEvent me) {
th.stop();
l1.setText(" ");
l2.setText(" ");
l3.setText(" ");
l4.setText(" ");
l5.setText(" ");
l6.setText(" ");
l1.setText("2");
l1.setBounds(433, yx, 40, 50);
l2.setText("0");
l2.setBounds(483, yx, 40, 50);
l3.setText("1");
l3.setBounds(533, yx, 40, 50);
l4.setText("3");
l4.setBounds(583, yx, 40, 50);
l5.setText("Impressions");
l5.setBounds(770, yx, 400, 50);
l21.setBounds(630,50,126,126);
}
public void run()
{
try
{
l2.setText(" ");
for (x = 0; x < 200; x += 1)
{
Thread.sleep(1L);
l3.setText("1");
l3.setBounds(533 - x / 2, yx, 40, 50);
l1.setText("2");
l1.setBounds(433 + x / 4, yx, 40, 50);
l4.setText("3");
l4.setBounds(583 - x / 4, yx, 40, 50);
l5.setBounds(770, yx-(6*x)/8, 400, 50);
l21.setBounds(630,50-x,126,126);
l6.setText("March");
l6.setBounds(650, 200 - (5 * x)/8, 200, 50);
add(l6);
}
l3.setText("<html>1<sup><font size=3>st</font></sup></html>");
l1.setText("<html>2<sup><font size=3>st</font></sup></html>");
l4.setText("<html>3<sup><font size=3>rd</font></sup></html>");
}
catch (Exception e)
{
}
}
}
everytime i use paint method, only the paint method works and the rest of the code doesnt work properly. even if i draw a line using the paint() method. then also the same happens.
Toolkit's image loading is sometimes not working. I don't know why but it is what I experienced. Use the ImageIcon class instead.
img = new ImageIcon(getClass().getResource("logo.png")).getImage();