I’m taking a java class and have to make a Black Jack game for the final and I wanted to implement a GUI for it. Only problem is I don’t really know how to use the Mouse Listener. Or rather, I don’t know how to get it to do what I want it to do. For now all I want to do is draw a string when I button is clicked or pressed. I can get it to print in the command line but it won’t draw the string. I’m also going off of the experience I got from making a pong game for my midterm so I don’t know if some of this stuff is needed for a game like Black Jack. Here’s what I got to start off with if it helps you at all, any help is appreciated.
public class BlackJack extends JPanel implements Runnable, KeyListener, MouseListener {
private JButton button = new JButton("This is a JButton");
boolean buttonClicked;
public BlackJack() {
JFrame frame = new JFrame("BlackJack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.setSize(500,500);
button.addMouseListener(this);
frame.add(button);
frame.setVisible(true);
button.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(buttonClicked)
{
g.setColor(Color.BLACK);
g.drawString("The button was clicked", 50,50);
}
}
public void mouseClicked(MouseEvent e) {
if(e.getSource().equals(button))
{
if(!buttonClicked)
buttonClicked = true;
else
buttonClicked = false;
}
}
public void start(){
Thread th = new Thread (this);
th.start ();
}
public void run(){
while(true)
{
try
{
Thread.sleep (25);
}
catch (InterruptedException ex){}
}
}
I think that’s all I need to put up for this. Anything else I have so far is just empty key and mouse listener methods.