Question

We are making a Bananagrams game. We want to use a mouseListener (which we can't figure out how to write) to click on a JButton, which will in turn open a new window in GUI. How can we do this?

Code: This is my code for Bananagramz!!!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
public class Gui extends JFrame implements ActionListener {
   //private JPanel pane;
    private Container  pane; 
    private JButton start;
    private JRadioButton five, fifteen, ten;
    private JLabel welcome,instructions, ins, inst, instr;
    private int i;
    public Gui() {
        this.setTitle("BANANAGRAMZ");
        this.setSize(500,500);
        this.setLocation(100,100);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    pane = this.getContentPane();
    pane.setLayout(new FlowLayout());
    five = new JRadioButton("Check here if you want 5 minutes to play!");
    ten = new JRadioButton("Check here if you want 10  minutes to play!");  
    fifteen = new JRadioButton("Check here if you want 15 minutes to play!");

    welcome = new JLabel("Welcome to Bananagramz!");
    instructions = new JLabel("You will be given 50 tiles randomly chosen from a pot of 144.");
    ins = new JLabel ("Your goal is to make a grid of (real) English words,");
    inst = new JLabel ("which will be checked (for realness) at the end, within a time limit.");
    instr = new JLabel("Think hard, and beat the clock!");
    JButton start = new JButton("Go!");

     pane.setForeground(Color.YELLOW);
     pane.setBackground(Color.YELLOW);

    pane.add(welcome);
    pane.add(five);
    pane.add(ten);
    pane.add(fifteen);


    pane.add(instructions);
    pane.add(ins);
    pane.add(inst);
    pane.add(instr);

    pane.add(start);
    }
    public void actionPerformed( ActionEvent e){
    i++;
    System.out.println(i);
    }
    public void mouseClicked(MouseEvent e){
    System.out.println("mouse cliekd");
    }


    public static void main(String[] args) {
        Gui g = new Gui();
        g.setVisible(true);
    }
}
Was it helpful?

Solution

The problems as I saw is you declared

private JButton start;

but in your constructor you did

JButton start = new JButton("Go!");

it should be

start = new JButton("Go!");

and register a listener to the button like below

start.addActionListener(this); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top