繁体   English   中英

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

[英]Accessing elements from a jFrame that is within a running instance of a thread

我正在尝试制作一个用于在线程的不同运行实例之间进行通信的应用程序。 我有一个jFrame,其中有一个jTextField和一个jButton。 在jTextField中,键入要运行的线程数,然后按jButton后,线程将运行。 每个线程包含一个带有jButton的jFrame。 因此,如果我在jTextField中键入3,然后按OK,则会弹出具有自己的jButton的三个不同的jFrame。 如果我在线程的一个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)Window类(Fereastra表示窗口,deblocat表示已解锁,buton activ表示已启用按钮)

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                   

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM