Hello everyone.
I just started on 'converting' my multiplayer text RPG
into a graphical form.
What I am trying to do is this:
Create a title window, basicly just a JPanel with one image filling the space.
To this JPanel I add a MouseListener.
When a user clicks the window and thus the panel, I change the Image to draw
to just the background image, ie no text, and then call repaint();
However what happens, is that I have to click the panel twice for the background Image to appear. After the first click I just get the JPanel's background color.
My code looks like this:
The JFrame
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.*;
public class MainWindow extends JFrame {
private static final long serialVersionUID = 1L;
public MainWindow(String title){
setSize(640,400);
setTitle(title);
setResizable(false);
Image titleScreen = Toolkit.getDefaultToolkit().getImage("starting screen_2.jpg");
MainWindowCanvas board = new MainWindowCanvas(titleScreen);
getContentPane().add(board,BorderLayout.CENTER);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new MainWindow("Celegoth");
}
}
The JPanel
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainWindowCanvas extends JPanel implements MouseListener{
/**
*
*/
private static final long serialVersionUID = 9111698527897284505L;
private Image mainTitleScreen,mainMenuScreen;
public MainWindowCanvas(Image im){
setLayout(null);
addMouseListener(this);
setBackground(Color.black);
mainTitleScreen = im;
mainMenuScreen = Toolkit.getDefaultToolkit().getImage("Starting screen background.jpg");
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(mainTitleScreen, 0, 0, null);
}
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
mainTitleScreen = mainMenuScreen;
repaint();
}
public void mouseReleased(MouseEvent arg0) {
}
}
If I put a JOptionPane.showMessageDialog of some sort in between there, for example in the mousePressed method, so that the paintComponent gets called twice, there's no problem.
But I want to understand what's happening, so I can avoid mistakes in the future.
Thanks for reading, and hopefully until soon.
Aviras