从正在运行的线程实例中的 jFrame 访问元素



我正在尝试制作一个应用程序,用于在线程的不同运行实例之间进行通信。我有一个jFrame,它有一个jTextField和一个jButton。在jTextField中,我键入要运行的线程数,按下jButton后,线程将运行。每个线程都包含一个带有 jButton 的 jFrame。因此,如果我在jTextField中键入3,然后按OK,则会弹出三个不同的jFrames,它们都有自己的jButton。如果我在线程的一个 jFrame 中按下 jButton,则 jButton 设置为禁用 ( setEnabled(false) )。当按下时,这应该发生在线程内的jFrame的每个jButton上,但最后一个jFrame中仍未按下的jButton。

这是线程的窗口类:

public class Window extends JFrame implements Runnable {
    JFrame jr;
    JButton bt;
    public void run() {
        jr=new JFrame();
        bt=new jButton();
        bt.setTitle("Press Me");
        jr.setLayout(new FlowLayout());
        jr.add(bt);
        bt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                bt.setEnabled(false);
            }
        });
        jr.setVisible(true);
    }
}

现在这就是我运行此线程的多个实例的方式。 i是从 jTextField 中获取的线程实例的数量:

(    int i=Integer.parseInt(jTextField1.gettext())  )
for (int a=0;a<i;a++) {
    Runnable thr=new Window(a);
    executor.execute(thr);
}

这就是我想做的:在线程实例中的每个 jFrame 上按下 jButton 并将其设置为setEnabled(false)后,我到达弹出的最后一个 jFrame,其 jButton 仍未按下。当我按下最后一个 JButton 时,我希望每个 jFrame 上的所有 JButton 都设置为setEnabled(true)。我该怎么做?

这是它现在 100% 工作的主要类!

        import java.awt.Color;
    import java.awt.Image;
    import java.io.IOException;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    /**
     *
     * @author oliver
     */
    public class Hauptklasse extends javax.swing.JFrame {
    static int i = 0;
    static Random r;
    static boolean OkApasat=false;
    static int c;
    public static Fereastra[] thread;

    public Hauptklasse() throws IOException {
        initComponents();
        Image logo;
        logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
        jLabel4.setIcon(new ImageIcon(logo));
        jLabel4.setVisible(true);
        setLocation(200,100);
        jPanel1.setBackground(Color.cyan);
        jTextField1.setEditable(false);
        jButton2.setEnabled(false);
        r=new Random();


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton1.setText("Pornire");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
        jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Numar maxim de ferestre");
        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton2.setText("OK");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(1, 1, 1)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2))
                        .addGap(22, 22, 22)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
                .addContainerGap())
        );
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>                        
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         jTextField1.setEditable(true);
         jButton1.setEnabled(false);
         jButton2.setEnabled(true);
         jTextArea1.append("n Welcome! :)");
         jTextArea1.append("n The following app tests the communication between threads");
         jTextArea1.append("n Please enter maximum number of windows to be opened");

    }                                        
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       OkApasat=true;

    }                                        
    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String args[]) throws IOException {

        final Hauptklasse main1 = new Hauptklasse();

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                main1.setVisible(true);
            }
        });
        while (true){
            if (OkApasat==true){
                if (Integer.parseInt(jTextField1.getText())>=3){
                   i= (Integer.parseInt(jTextField1.getText()));
                   main1.jTextArea1.append("n"+i+" windows opened");
                   Fereastra[] thr=new Fereastra[i];
                    for (c = 0; c < i; c++) {
                        thr[c]=new Fereastra(thr);
                        thr[c].run();
                    }
                  OkApasat=false;
                   main1.jButton2.setEnabled(false);
                   main1.jTextField1.setEditable(false);

            }
                else jTextArea1.append("n Wrong maximum number of windows-must be at least 3");
                OkApasat=false;
        }
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
            }

    }
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTextArea jTextArea1;
    public static javax.swing.JTextField jTextField1;
    // End of variables declaration                   
    }

这是窗口类,工作 100 %:

    import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 *
 * @author oliver
 */
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
    this.thread = thread;
    jr = new JFrame();
    jr.setSize(250, 250);
    jr.setLayout(new FlowLayout());
    bt = new JButton();
    jr.add(bt);
    bt.setText("OK");
    bt.setBackground(Color.cyan);
    l2 = new JLabel();
    l2.setText("Buton activ");
    jr.add(l2);
    jr.setVisible(true);
}
public void run() {
    bt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            bt.setEnabled(false);
            deblocat = true;
            for (int c = 0; c < Hauptklasse.i; c++) {
                if (thread[c] != null && thread[c].bt.isEnabled()) {
                    deblocat = false;
                    break;
                }
            }
            if (deblocat == true) {
                for (int c = 0; c < Hauptklasse.i; c++) {
                    if (thread[c] != null) {
                        thread[c].bt.setEnabled(true);
                    }
                }
            }
        }
    });
}
}

我的类:

1)窗口类(Fereastra表示窗口,deblocat表示解锁,但是on激活表示按钮已启用)

package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 *
 * @author oliver
 */
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
    this.thread = thread;
    jr = new JFrame();
    jr.setSize(250, 250);
    jr.setLayout(new FlowLayout());
    bt = new JButton();
    jr.add(bt);
    bt.setText("OK");
    bt.setBackground(Color.cyan);
    l2 = new JLabel();
    l2.setText("Buton activ");
    jr.add(l2);
    jr.setVisible(true);
}
public void run() {
    bt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            bt.setEnabled(false);
            deblocat = true;
            for (int c = 0; c < Hauptklasse.i; c++) {
                if (thread[c] != null && thread[c].bt.isEnabled()) {
                    deblocat = false;
                    break;
                }
            }
            if (deblocat == true) {
                for (int c = 0; c < Hauptklasse.i; c++) {
                    if (thread[c] != null) {
                        thread[c].bt.setEnabled(true);
                    }
                }
            }
        }
    });
}

}

2)主类(又名Hauptklasse,okApasat表示ok被按下):

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
 *
 * @author oliver
 */
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;

public Hauptklasse() throws IOException {
    initComponents();
    Image logo;
    logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
    jLabel4.setIcon(new ImageIcon(logo));
    jLabel4.setVisible(true);
    setLocation(200,100);
    jPanel1.setBackground(Color.cyan);
    jTextField1.setEditable(false);
    jButton2.setEnabled(false);
    r=new Random();


}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
    jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jButton1.setText("Pornire");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
    jTextArea1.setColumns(20);
    jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
    jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    jLabel1.setText("Numar maxim de ferestre");
    jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jButton2.setText("OK");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(28, 28, 28)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(44, 44, 44)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2)))
            .addContainerGap(31, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addGap(0, 0, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(1, 1, 1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2))
                    .addGap(22, 22, 22)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
            .addContainerGap())
    );
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
    );
    pack();
}// </editor-fold>                        
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     jTextField1.setEditable(true);
     jButton1.setEnabled(false);
     jButton2.setEnabled(true);
     jTextArea1.append("n Welcome! :)");
     jTextArea1.append("n The following app tests the communication between threads");
     jTextArea1.append("n Please enter maximum number of windows to be opened");

}                                        
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
   OkApasat=true;

}                                        
/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String args[]) throws IOException {

    final Hauptklasse main1 = new Hauptklasse();

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            main1.setVisible(true);
        }
    });
    while (true){
        if (OkApasat==true){
            if (Integer.parseInt(jTextField1.getText())>=3){
               i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3; 
               main1.jTextArea1.append("n"+i+" windows opened");
               Fereastra[] thr=new Fereastra[i];
                for (c = 0; c < i; c++) {
                    thr[c]=new Fereastra(thr);
                    thr[c].run();
                }
              OkApasat=false;
               main1.jButton2.setEnabled(false);
               main1.jTextField1.setEditable(false);

        }
            else jTextArea1.append("n Wrong maximum number of windows-must be at least 3");
            OkApasat=false;
    }
        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
        }

}
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration                   

}

最新更新