2013-08-07 5 views
1

Я пытаюсь проверить кнопки, но я не могу получить Action Listener работатьКак добавить ActionListener к кнопке в рамке в Java

public class ButtonTester implements ActionListener { 

static JLabel Label = new JLabel("Hello Buttons! Will You Work?!"); 
public static void main(String[] args) { 
    //Creating a Label for step 3 
    // now for buttons 
    JButton Button1 = new JButton("Test if Button Worked"); 
    // step 1: create the frame 
    JFrame frame = new JFrame ("FrameDemo"); 
    //step 2: set frame behaviors (close buttons and stuff) 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //step 3: create labels to put in the frame 
    frame.getContentPane().add(Label, BorderLayout.NORTH); 
    frame.getContentPane().add(Button1, BorderLayout.AFTER_LAST_LINE); 
    //step 4: Size the frame 
    frame.pack(); 
    //step 5: show the frame 
    frame.setVisible(true); 
    Button1.setActionCommand("Test"); 
    Button1.setEnabled(true); 
    Button1.addActionListener(this); //this line here won't work 
} 
@Override 
public void actionPerformed(ActionEvent e) { 
    // TODO Auto-generated method stub 
    if("Test".equals(e.getActionCommand())) 
    { 
     Label.setText("It Worked!!!"); 
    } 
    } 

} 
+1

Вы должны создать свои компоненты Swing в потоке событий Swing, используя SwingUtilities.invokeLater() в main(). Если ButtonTester реализует Runnable, перемещая код из main() в run(), то выполнение SwingUtilities.invokeLater (new ButtonTester()) из main() решит сразу несколько проблем. –

+0

Пожалуйста, изучите соглашения об именах java и придерживайтесь их. – kleopatra

ответ

3

this не имеет контекста в методе static

Вместо этого попробуйте использовать что-то вроде Button1.addActionListener(new ButtonTester()); вместо ...

Обновлено

Вы также можете взглянуть на Initial Threads, так как у Swing есть особые требования ...

+0

Также хорошее решение. –

3

Статические методы не связаны с экземпляром класса, поэтому не может быть использован.

Вы можете переместить весь код из основных для нестатической методы ButtonTester (скажем, run(), например), и сделать что-то вроде этого от основных:

new ButtonTester().run(); 

Вы также можете использовать анонимный внутренний класс для ActionListener:

Button1.addActionLister(new ActionListener() { 
    @Override public void actionPerformed (ActionEvent e) { 
     // ... 
    } 
}); 
+1

Согласитесь, не любите задерживаться в методе 'main'. Также забыл упомянуть об начальных потоках – MadProgrammer

+1

Даже обычный внутренний класс может быть хорошим, если вы хотите изменить или получить доступ к свойствам кнопки и хотите получить дополнительную доступность. – snickers10m

1

Java говорит, что вы не можете получить доступ к нестатическому объекту из статического контекста (это относится к объекту, который не является статическим и основным() является статическим), поэтому мы используем конструктор для инициализации:

public class ButtonTester implements ActionListener { 
static JLabel Label = new JLabel("Hello Buttons! Will You Work?!"); 
ButtonTester() //constructor 
{ 
//Creating a Label for step 3 
    // now for buttons 
    JButton Button1 = new JButton("Test if Button Worked"); 
    // step 1: create the frame 
    JFrame frame = new JFrame ("FrameDemo"); 
    //step 2: set frame behaviors (close buttons and stuff) 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //step 3: create labels to put in the frame 
    frame.getContentPane().add(Label, BorderLayout.NORTH); 
    frame.getContentPane().add(Button1, BorderLayout.AFTER_LAST_LINE); 
    //step 4: Size the frame 
    frame.pack(); 
    //step 5: show the frame 
    frame.setVisible(true); 
    Button1.setActionCommand("Test"); 
    Button1.setEnabled(true); 
    Button1.addActionListener(this); //this line here won't work 
} 


public static void main(String[] args) { 
ButtonTester test1=new ButtonTester();// constructor will be invoked and new object created 


} 
@Override 
public void actionPerformed(ActionEvent e) { 
    // TODO Auto-generated method stub 
    if("Test".equals(e.getActionCommand())) 
    { 
     Label.setText("It Worked!!!"); 
    } 
    } 
} 
Смежные вопросы