سؤال

لقد أنشأت في تطبيق Java Swing الخاص بي نافذة رئيسية مع Jbutton. لقد أضفت إلى هذا الزر فئة مستمع الحدث (تنفيذ واجهة ActionListener) والتي ، في كل مرة يتم فيها النقر فوق الزر ، يقوم بإطلاق نافذة "منبثقة". تعمل الطريقة بشكل جيد عند النقر فوق الزر ، إلا عند النقر فوق الزر لأول مرة ، لأنه لا يفعل شيئًا. لا أحد يعرف السبب وراء هذا السلوك؟

هل كانت مفيدة؟

المحلول

طريقة أبسط ربما هي توفير AbstractAction. يمكنك تجربة النهج المبين أدناه. (يظهر نافذة منبثقة عند النقر فوق الزر.)

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(new JButton(new AbstractAction("Button Text") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hello World");
            }
        }));
        jf.setSize(200, 200);
        jf.setVisible(true);
    }
}

نصائح أخرى

Posting the code of the event handler as well as how you are attaching it to the button might help. You might want to take a quick look at this Sun Tutorial

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top