why repeated call to repaint() method did not work - java

My objective is to put a button and a circle on the JFrame. When i click the button the circle should move randomly on the panel/frame.
But when i click the button the circle just move once only and after putting SOP statements i found that "frame.repaint()" is getting called multiple times but this call is triggering the "paintComponent" method only once, the very first time (defined in class Panel1). Its very strange!
I have also provided another code which works as expected but has no buttons to trigger the animation. I have read that repaint() requests are coalesced together and executed once, then how come the second program works?
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.awt.*;
public class SimpleGui3c_4 {
public static void main(String args[]) {
Frame1 frame = new Frame1();
frame.go();
}
}
class Frame1 {
JFrame frame;
Panel1 p;
void go() {
frame = new JFrame();
JButton button1 = new JButton("Color Change");
p = new Panel1();
frame.setSize(500,500);
frame.setVisible(true);
frame.getContentPane().add(BorderLayout.SOUTH, button1);
frame.getContentPane().add(BorderLayout.CENTER, p);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
button1.addActionListener(new ColorActionListener());
}
class ColorActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
for(int i=0;i<130;i++) {
System.out.println("Frame repaint started");
frame.repaint();
try {
Thread.sleep(5000);
}catch(Exception ex) {}
System.out.println("Frame repaint ended");
}
}
}
class Panel1 extends JPanel {
public void paintComponent(Graphics g) {
System.out.println("Inside the paint Component method");
int x = (int)(Math.random()*100);
int y = (int)(Math.random()*100);
g.setColor(Color.BLUE);
g.fillOval(x,y,100,100);
System.out.println("Exiting the paint component method");
}
}
}
Code which works but has no button to trigger the animation, it works as soon as i run the code. I am not sure why the below program works and the above program fails!
import javax.swing.*;
import java.awt.*;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String args[]) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
for(int i = 0;i<130;i++) {
//x++;
//y++;
drawPanel.repaint();
try {
Thread.sleep(50);
}catch(Exception ex) {}
}
}//close go
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0,0,this.getWidth(), this.getHeight());
int x = (int)(Math.random()*70);
int y = (int)(Math.random()*70);
g.setColor(Color.green);
g.fillOval(x,y,40,40);
}
}
}

I have also provided another code which works as expected but has no buttons to trigger the animation.
The difference between the two pieces of code is context within which they are been called.
The code that "works" is actually been updated out side the context of the Even Dispatching Thread, in the "main" thread, which means that doing something like Thread.sleep won't prevent the UI from been updated.
The code which does not work is been updated from with the content of the Event Dispatching Thread (from within the ActionListener), which is prevent the EDT from processing new paint requests until after the actionPerformed method returns
Another issue you will face relates to when you decide to update the position of the circle.
paintComponent can be called for all a number of different reasons, many which you don't control. Painting should focus on painting the current state and should never modify it (directly or indirectly). Instead, you should use some kind of update method, whose job it is, is to update the x/y position of the circle and trigger a new paint cycle.
I would highly recommend that you stop and take the time to read through:
Concurrency in Swing for a more detail explanation
How to use Swing Timers for a possible solution
Performing Custom Painting and Painting in AWT and Swing for a better understanding into how painting actually works in Swing.
Your problem is rookie mistake which comes about from not understanding how the API actually works and not understanding the tools available to solve it
There are a number of other "issues" which would result in undesirable behaviour, like not calling setVisible last, so the UI doesn't need be updated again to ensure that the components been added are visible.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimpleGui3c_4 {
public static void main(String args[]) {
new SimpleGui3c_4();
}
public SimpleGui3c_4() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Frame1 frame = new Frame1();
frame.go();
}
});
}
public interface Animatable {
public void update();
}
public class Frame1 {
JFrame frame;
Panel1 p;
void go() {
frame = new JFrame();
JButton button1 = new JButton("Color Change");
p = new Panel1();
frame.getContentPane().add(BorderLayout.SOUTH, button1);
frame.getContentPane().add(BorderLayout.CENTER, p);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
button1.addActionListener(new ColorActionListener(p));
frame.pack();
frame.setVisible(true);
}
class ColorActionListener implements ActionListener {
private Animatable parent;
public ColorActionListener(Animatable parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
btn.setEnabled(false);
Timer timer = new Timer(5000, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Frame repaint started");
parent.update();
counter++;
if (counter >= 130) {
((Timer)e.getSource()).stop();
btn.setEnabled(true);
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
class Panel1 extends JPanel implements Animatable {
private int xPos, yPos;
public Panel1() {
update();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Inside the paint component method");
g.setColor(Color.BLUE);
g.fillOval(xPos, yPos, 100, 100);
System.out.println("Exiting the paint component method");
}
#Override
public void update() {
System.out.println("Inside the update method");
xPos = (int) (Math.random() * 100);
yPos = (int) (Math.random() * 100);
repaint();
}
}
}
}

Related

Why this circle didn't get smeared

import javax.swing.*;
import java.awt.*;
public class Test1 {
int x = 70;
int y = 70;
public static void main (String[] args) {
Test1 gui = new Test1 ();
gui.go();
}
public void go() {
JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
x++; y++;
drawPanel.repaint();
try { Thread.sleep(50);
} catch(Exception ex) { } }
}// close go() method
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(x,y,40,40);
}
} // close inner class
} // close outer class
page1page2
According to the page 2, the circle should be smeared in the frame... but actually, when I ran it, it just moved without smearing. Why was that?
btw, if these codes were not able to make a smearing circle, how could I make a smearing one?
cheers
As shown here, "If you do not honor the opaque property you will likely† see visual artifacts." Indeed, running your example on Mac OS X with Java 6 produces a series of circles that appear "smeared."
How could I make a smearing one?
Do not rely on painting artifacts to get the desired result; instead, render a List<Shape> as shown below.
Use javax.swing.Timer to pace animation.
Construct and manipulate Swing GUI objects only on the event dispatch thread.
Override getPreferredSize() to establish a drawing panel's initial geometry.
Code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test2 {
public static void main(String[] args) {
EventQueue.invokeLater(new Test2()::display);
}
public void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final MyDrawPanel drawPanel = new MyDrawPanel();
frame.add(drawPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyDrawPanel extends JPanel {
private int x = 30;
private int y = 30;
private final List<Shape> list = new ArrayList<>();
public MyDrawPanel() {
new Timer(50, (new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x++;
y++;
list.add(new Ellipse2D.Double(x, y, 40, 40));
repaint();
}
})).start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.green);
for (Shape s : list) {
g2d.fill(s);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
}
†Emphasis mine.

Painting inside Swing Timer not working

I never worked with Timers before so my problem is probably stupid one really. My program draws a circle which is red and after random seconds the circle should change its color to green. I just made a swing timer as you can see below in the code. And it enters actionPerformed() method but it doesn't change color. Could you help me somehow fix my problem with changing colors?
My code:
package igrica;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ChangingCircle implements ActionListener{
JFrame frame;
Timer timer;
Random r;
public static void main(String[] args) {
ChangingCircle gui = new ChangingCircle();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillOval(100, 100, 100, 100);
Random r = new Random();
Timer timer = new Timer(r.nextInt(5000) + 1000, new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.println("Timer out");
g.setColor(Color.green);
g.fillOval(100, 100, 100, 100);
}
});
timer.start();
}
}
}
There's quite the mess in your code. Try this:
public class ChangingCircle {
Color color = Color.RED;
MyPanel panel = new MyPanel();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ChangingCircle gui = new ChangingCircle();
gui.go();
});
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Random r = new Random();
Timer timer = new Timer(r.nextInt(5000) + 1000, new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.println("Timer");
color = Color.GREEN;
panel.repaint();
}
});
timer.setRepeats(false);
timer.start();
}
class MyPanel extends JPanel {
private int size = 100, loc = 100;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(loc, loc, size, size);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(size + loc, size + loc);
}
}
}
The idea is that the timer only changes the property of the shape to be drawn and then calls repaint() to reflect the change. The paintComponent is called whenever it is needed, even in quick succession and should return quickly.
Specific Notes:
Start Swing from the EDT.
Create and start the timer from outside of paintComponent since it is called many times and that will create and start many timers.
You should probably set the timer not to repeat.
Call super.paintComponent(g); as the first thing inside paintComponent.
You seem to have an ActionListener that does nothing.
General tips:
Use the #Override annotation when applicable.
Call pack() on the frame instead of setting its size manually and #Override the getPreferredSize method of the component you paint on. Return a meaningful size based on what you draw.
Use add(component, location) and not the other way around (deprecated).
Don't use fields when local variables will do (Random r for example).
Use uppercase constant names (Color.RED instead of Color.red).
Don't initiate a Timer from within a paintComponent method. This method should be for painting and painting only. Instead start the Timer in your constructor and within your Timer's actionPerromed and call repaint(), change the state of a field of the class, and use that information within the paintComponent use that field to draw any new information.
e.g.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ChangingCircle {
JFrame frame;
public static void main(String[] args) {
ChangingCircle gui = new ChangingCircle();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
class MyPanel extends JPanel {
private Random r = new Random();
private boolean draw = false;
public MyPanel() {
Timer timer = new Timer(r.nextInt(5000) + 1000, new ActionListener() {
public void actionPerformed(ActionEvent ev) {
draw = true;
repaint();
}
});
timer.setRepeats(false);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw) {
g.setColor(Color.red);
g.fillOval(100, 100, 100, 100);
}
}
}
}
Also, don't forget to call the super's paintComponent method from within your override.
If you need to change colors, give the JPanel a Color field, say called color and change it's value from within the Timer, and then call repaint(). Again within paintComponent, use the value of that field to draw the oval with. Also in this situation, the Timer should repeat, so get rid of timer.setRepeats(false) in that situation.
The timer works asynchronously and paintComponent finishes before finishing the work of timer.

I'm trying to draw a string in JFrame, but it won't work.. Help please

I'm trying to display a string when a button is pressed, but it does not work. I do not know what the problem is. I get no error, but that does not bother me. I'm missing something fundamental, I suppose. Please help!!
//I'm trying to draw a string in the frame when a button is pressed, but it won't work..
//Can't figure out what the problem is.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class AppletTwo extends JFrame implements ActionListener
{
JFrame frameOne;
JButton btnOne;
AppletTwo()
{
frameOne = new JFrame("frameOne");
frameOne.setSize(320,240);
frameOne.setLayout(new FlowLayout(FlowLayout.LEFT));
frameOne.setVisible(true);
frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnOne = new JButton("Print");
btnOne.addActionListener(this);
frameOne.add(btnOne);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == btnOne)
{
repaint();
}
}
public void paint(Graphics g)
{
g.drawString("Never Works",150,150);
}
public static void main(String[] args)
{
AppletTwo frame1 = new AppletTwo();
}
}
" I'm missing something fundamental, I suppose. "
Yes, you are:
Main problem:
Your class is JFrame which is the component for which you are overriding the paint method. But you create another instance of a JFrame, which is the one you setVisible to. Keep in mind, you haven't drawn anything to this frame. So you are seeing the new instance of frame, not the class frame for which you are painting (and for which you never set visible).
Other problems:
You should always call super.paint[Component] after a paint[Component] override
#Override
public void paint(Graphics g) {
super.paint(g);
}
Don't paint on top level container like JFrame. Instead paint on a JPanel or JComponent and override is paintComponent method and call super.paintComponent, then add that component to the frame. See Performing Custom Painting
Swing apps should be run on the event dispatch thread (EDT). You can do so by wrapping your main code in a SwingUtilities.invokeLater(...). See Initial Threads
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
AppletTwo frame1 = new AppletTwo();
}
});
}
Generally, you always want to set the frame visible after adding your components.
Other notes:
See Extends JFrame vs. creating it inside the the program
UPDATE
Example with all the above mentioned points.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class SimpleDrawing {
public SimpleDrawing() {
final DrawingPanel panel = new DrawingPanel();
final JTextField field = new JTextField(15);
JButton button = new JButton("Change name");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String someString = field.getText();
if (!someString.isEmpty()) {
panel.setString(someString);
}
}
});
JPanel bottomPanel = new JPanel();
bottomPanel.add(field);
bottomPanel.add(button);
JFrame frame = new JFrame();
frame.add(panel);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class DrawingPanel extends JPanel {
private String someString = "Stackoverflow";
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(someString, 75, 75);
}
#Override
public Dimension getPreferredSize() {
return new Dimension (300, 100);
}
public void setString(String someString) {
this.someString = someString;
repaint();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new SimpleDrawing();
}
});
}
}

JFrame repaint(); error

So, I'm currently working on making a ball that moves on keyboard command. My problem is that when I call repaint();, it gives me an error saying that it "Cannot make a static reference to the non-static method repaint() from the type Component." What am I doing wrong?
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class App extends JFrame{
JFrame f = new JFrame();
public static int keyVal = 0, x = 10, y = 10;
public static void main(String[] args) {
new App();
Ball();
while(true){
System.out.println(keyVal);
try{
Thread.sleep(50);
}
catch(Exception e){}
}
}
public static void Ball(){
while(true){
if(keyVal == 65){
x = x -1;
}
else if(keyVal == 68){
x = x + 1;
}
repaint();
//repaint(x, y, 10, 20);
}
}
public App(){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pong");
f.setSize(30,40);
f.setLocationRelativeTo(null);
f.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e){
keyVal = e.getKeyCode();
}
public void keyReleased(KeyEvent e){
keyVal = 0;
}
public void keyTyped(KeyEvent e){}
});
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(500,200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("test");
g.setColor(Color.orange);
g.fillRect(x, y, 10, 20);
}
}
}
Your class is already a JFrame subclass. There's no need to create another JFrame. Take out the JFrame f = new JFrame() and all the f.method(..) just use method(..)
Don't use while(true) or Thread.sleep(). You will run into problem. Instead look into How to use a Swing Timer. Here is a simple example. You could also find many other examples just doing a simple google search on how to use Swing Timer
No need to setSize() to the frame, you already pack() it.
You should look into How to use Key Bindings. If not now, you will come to find that there are focus issues, among other things, with using a KeyListener.
Run your program from the Event Dispatch Thead, like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new App();
}
});
}
Freebie
A simple implementation of a javax.swing.Timer would be something like this
public App() {
...
Timer timer = new Timer(50, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
}
Here is the basic construct of the Timer
Timer( int dalay, ActionListener listener )
The delay it the amount of milliseconds delayed for each time the event is fired. So in the above code, for every 50 milliseconds, something will happen. This will achieve what you are trying to do with the Thread.sleep. You can call the repaint() from inside the actionPerformed
Here's a simple refactor of your code, that you can test out
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class App extends JFrame {
private MyPanel panel = new MyPanel();
public static int keyVal = 0, x = 10, y = 10;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new App();
}
});
}
public App() {
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x = x + 5;
panel.repaint();
}
});
timer.start();
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Pong");
pack();
setLocationRelativeTo(null);
setVisible(true);
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(500, 200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("test");
g.setColor(Color.orange);
g.fillRect(x, y, 10, 20);
}
}
}

Background image in java swing issue

I've made a Jpanel with a background image and a Jbutton also with its background. The problem is that background sometimes is loaded sometimes no.
public class Window extends JFrame {
public static JFrame createwindow() {//fare singleton
JFrame frame = new JFrame("Battaglia navale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(740, 740);
frame.setVisible(true);
frame.setResizable( false );
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(((int)dim.getWidth()-(int)frame.getWidth())/2, ((int)dim.getHeight()-(int)frame.getHeight())/2);
return frame;
}
}
public class StartWindow {
JFrame frame;
private JButton button;
private JButton button2;
final String button_start = "img/start.png";
ImageIcon start = new ImageIcon(button_start);
public void CreateStartWindow() {
frame = Window.createwindow();
Container container = frame.getContentPane();
JpanelStart panel = new JpanelStart();
container.add(panel);
this.button = new JButton(start);
button.setActionCommand("start");
button.setHideActionText(true);
button.setOpaque(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
this.button2 = new JButton("Classifica");
panel.add(button);
panel.add(button2);
frame.setVisible(true);
}
public void addActionListener(ActionListener al) {
this.button.addActionListener(al);
this.button2.addActionListener(al);
}
public void chiudi() {
frame.dispose();
}
}
class JpanelStart extends JPanel {
private Image img;
private String path_img = "img/sfondo.jpg";
public JpanelStart() {
img = Toolkit.getDefaultToolkit().createImage(path_img);
loadImage(img);
}
private void loadImage(Image img) {
try {
MediaTracker track = new MediaTracker(this);
track.addImage(img, 0);
track.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
setOpaque(false);
g.drawImage(img, 0, 0, this);
super.paintComponent(g);
}
}
super.paintComponet should go right after the method signature.
you set the button opacity to false, so it won't be seen.
Run your program from the Event Dispatch Thread.
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new StartWindow().CreateStartWindow();
}
});
}
In your method, you're making the frame visible before adding anything. Leave that out in the method
Don't set the size of the frame. Instead override the getPrefereedSize() of the JPanel and call pack() on the frame.
IMO, I see no use at all for this so-called helper method. I would toss it out the window
You should load your image as an embedded resource, and not from the file system.
img = ImageIO.read(StartWindow.class.getResource(path_img));
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartWindow {
JFrame frame;
private JButton button;
private JButton button2;
final String button_start = "img/start.png";
ImageIcon start = new ImageIcon(button_start);
public void CreateStartWindow() throws IOException {
frame = Window.createwindow();
Container container = frame.getContentPane();
JpanelStart panel = new JpanelStart();
container.add(panel);
this.button = new JButton(start);
button.setActionCommand("start");
button.setHideActionText(true);
button.setOpaque(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
this.button2 = new JButton("Classifica");
panel.add(button);
panel.add(button2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
new StartWindow().CreateStartWindow();
} catch (IOException ex) {
Logger.getLogger(StartWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void addActionListener(ActionListener al) {
this.button.addActionListener(al);
this.button2.addActionListener(al);
}
public void chiudi() {
frame.dispose();
}
}
class Window {
public static JFrame createwindow() {//fare singleton
JFrame frame = new JFrame("Battaglia navale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
return frame;
}
}
class JpanelStart extends JPanel {
private static final int D_W = 700;
private static final int D_H = 700;
private Image img;
private String path_img = "/images/logo.gif";
public JpanelStart() throws IOException {
img = ImageIO.read(StartWindow.class.getResource(path_img));
loadImage(img);
}
private void loadImage(Image img) {
try {
MediaTracker track = new MediaTracker(this);
track.addImage(img, 0);
track.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, D_W, D_W, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
}
**Shows Up Every time **
draw the image after super.paintComponent(g) (which draws the component that you want to draw on top of)
call repaint() in loadImage() after the image is set (so that it redraws it)
loadImage() doesn't seem to be setting the img variable does it need to?
(not essential but recommended) you should also move UI changes into the EDT (Event Dispatch Thread).
Example of running a UI task on EDT
This puts UI operations on a queue so that all UI changes are made from the same thread and avoid interference.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
//UI Operations
}
} );

Categories