View Single Post
  #1 (permalink)  
Old 11-19-2007, 12:39 AM
adlb1300 adlb1300 is offline
Member
 
Join Date: Jul 2007
Posts: 46
adlb1300 is on a distinguished road
Need help with JButton event
I'm trying to code an JButton and cannot get the code to compile correctly. When I add the action listener to the button I get an error that non-static variable this cannot be referenced from a static context. I'm also having problems with the method that is setup to handle the event. Here is my code:

Code:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.*; import java.awt.*; public class GuessNumber implements ActionListener{ public static void main(String[] args) { JButton okButton; JLabel msgLabel; final JTextField answerTextField; JPanel panel; String askForNum = "Please enter what you think the random number is below."; // generates randomNumber between 1 and 100 int randomNumber; int max = 100; Random random = new Random(); randomNumber = random.nextInt(max +1); // output of random number for testing purposes remove prior to submission System.out.println(randomNumber); // creates JLabel that asks user to guess what the random number is and enter it below msgLabel = new JLabel(askForNum, JLabel.CENTER); msgLabel.setSize(400, 150); msgLabel.setFont(new Font("Times New Roman", Font.BOLD, 14)); answerTextField = new JTextField(); answerTextField.setFont(new Font("Times New Roman", Font.PLAIN, 14)); answerTextField.setSize(75, 30); answerTextField.setVisible(true); okButton = new JButton("Ok"); okButton.setSize(30, 30); okButton.setFont(new Font("Times New Roman", Font.PLAIN, 14)); okButton.addActionListener(this); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(msgLabel); panel.add(answerTextField); panel.add(okButton); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(panel); f.setSize(400, 200); f.setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource() == okButton){ } } }
Thanks
Reply With Quote
Sponsored Links