Reputation: 99
Here is my main class:
import javax.swing.*;
public class WordProcessor {
public static void main(String[] args) {
MainFrame frame = new MainFrame("Word Processor", 10000, 10000);
}
}
and i have two other classes
import javax.swing.*;
public class MainFrame extends JFrame {
JMenuBar menubar = new JMenuBar();
public MainFrame(String name, int x, int y) {
setTitle(name);
setSize(x, y);
setVisible(true);
setJMenuBar(menubar);
//creates file menu and adds to menubar
//TODO populate with JMenuItems
JMenu filemenu = new JMenu("file");
filemenu.setVisible(true);
menubar.add(filemenu);
buttonnew buttonnew = new buttonnew("new");
buttonnew.setVisible(true);
filemenu.add(buttonnew);
buttonnew.addMouseListener(buttonnew);
}
}
and lastly
import javax.swing.*;
import java.awt.event.*;
public class buttonnew extends JMenuItem implements MouseListener{
buttonnew(String s) {
super();
super.setText(s);
}
public void mouseClicked(MouseEvent e){
System.out.println("hey-o");
}
@Override
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
}
Nothing happens when i click on buttonneẅ. I'm so lost!
Upvotes: 2
Views: 1852
Reputation: 324128
Read the Swing tutorial on How to Use Menu Items. You should not be using a MouseListener. You should be adding an ActionListener to the menu item.
The tutorial also has section on How to Write an Action Listener
and How to Write a Mouse Listener
.
public class buttonnew extends JMenuItem implements MouseListener{
Also class name should start with an upper case character, not a lower case character.
buttonnew.setVisible(true);
Swing components (except top level windows) are visible by default to the above code is unnecessary.
MainFrame frame = new MainFrame("Word Processor", 10000, 10000);
Don't hardcode a size for a frame. My screen is only 1376 x 768. You should either use:
frame.pack();
or for full screen you can use:
frame.setExtendedState(...);
Don't make the frame visible until you have added all the compnents to the frame.
setTitle(name);
setSize(x, y);
setVisible(true);
setJMenuBar(menubar);
Upvotes: 8
Reputation: 285405
Solutions:
Upvotes: 9