I have the following code in which I have created a JTextArea and Menubar in which I have added menuItem Inc.
I have coded the value of "val" = 0 , so that when the code runs and frame appears, the first thing that is seen is zero. But i want to increment this "0" to + 1 when Inc button is pressed. Right know it keeps on displaying "0" when I press Inc My code is as follows:
public class Menu
{
public static void main(String[] args)
{
myFrame frame = new myFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(300, 500);
frame.setLocation(600,300);
frame.setTitle("My Menu");
}
}
class myFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JTextArea area;
JMenuItem inc;
int val = 0;
public myFrame()
{
JTextArea area = new JTextArea(20,15);
add(new JScrollPane(area), BorderLayout.CENTER);
String aString = Integer.toString(val);
area.setText(String.valueOf(aString));
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Count");
menuBar.add(menu);
setJMenuBar(menuBar);
JMenuItem inc = new JMenuItem("Inc");
menu.add(inc);
inc.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Inc"))
{
int result = val+1;
String aString = Integer.toString(result);
area.setText(String.valueOf(aString));
}
}
}
In myFrame
s constructor, replace JTextArea area = new JTextArea(20,15);
with area = new JTextArea(20,15);