Java刷新第二种形式 [英] Java refreshing second form

查看:63
本文介绍了Java刷新第二种形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式.第一个是通过使用jslider来确定按钮的数量.第二种形式是根据jslider值显示jbutton.当我单击jbutton2时,第二种形式显示并显示按钮.运行良好.但是,我想在第二个窗体上创建jbutton而不单击第一个窗体中的jbutton2. 相反,当我更改jslider时,它应该在运行时在第二个表单上创建jbutton,并且一旦我更改jslider,就应该在第二个表单上再次创建该按钮数量,并根据jslider值刷新第二个表单的按钮编号. 我已经尝试过revalidate();、 repaint();但它们不起作用,它们不会刷新第二种形式.

I have two forms. First one is to decide numbers of button by using jslider. Second form is to display jbuttons according to jslider value. When i click jbutton2, the second form shows and display buttons. It is working perfectly. However, I want to create jbutton on the second form without clicking jbutton2 in the first form. Instead, when I change jslider, it should create jbuttons on the second form at the run time and once i change jslider it should create that amount of button again on the second form and refreshing the second form button numbers according to jslider value. I have tried revalidate();, repaint(); but they do not work, they dont refresh the second form.

因此,当第一个表单上的jslider更改时,如何刷新第二个表单?请帮助.....

So, How can I refresh second form when the jslider ,that is on the first form, changes ? Please help.....

我正在使用netbeans的默认Jframe....

I am using default Jframe of netbeans....

/* *要更改此模板,请选择工具" |工具".范本 *并在编辑器中打开模板. */

/* * To change this template, choose Tools | Templates * and open the template in the editor. */

public class NewJFrame7 extends javax.swing.JFrame {


    /**
     * Creates new form NewJFrame7
     */
    public NewJFrame7() {
        initComponents();
    }

    /**
     * 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() {

        jSlider1 = new javax.swing.JSlider();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jSlider1.setMajorTickSpacing(2);
        jSlider1.setMaximum(20);
        jSlider1.setMinimum(1);
        jSlider1.setPaintLabels(true);
        jSlider1.setPaintTicks(true);
        jSlider1.setToolTipText("");
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jButton2.setText("jButton2");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(273, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(262, 262, 262)
                    .addComponent(jButton2)
                    .addContainerGap(262, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(168, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(138, 138, 138)
                    .addComponent(jButton2)
                    .addContainerGap(139, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>                        

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {                                      
        // TODO add your handling code here:



    }                                     

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        form2 = true;
        new NewJFrame8().setVisible(true);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame7().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton2;
    private javax.swing.JSlider jSlider1;
    // End of variables declaration                   
}

2.form

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;


public class NewJFrame8 extends javax.swing.JFrame {



    /**
     * Creates new form NewJFrame8
     */
    public NewJFrame8() {
        initComponents();

    }

    /**
     * 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();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(371, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(242, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame8().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

推荐答案

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;

public class SliderExample
{
    private JSlider slider;

    private static final int MIN_BUTTONS = 2;
    private static final int SOME_BUTTONS = 4;  
    private static final int MAX_BUTTONS = 6;

    private JButton[] buttonArray;
    private ActionListener actionButton = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            JButton button = (JButton) ae.getSource();
            System.out.println(button.getText());
        }
    };

    private void createAndDisplayGUI()
    {
        ButtonPanel bp = new ButtonPanel();
        JFrame frame = new JFrame("JSlider Example : ");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setLocationByPlatform(true);

        JPanel contentPane = new JPanel();
        slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
                                                            , SOME_BUTTONS);
        slider.addChangeListener(new ChangeListener()
        {
            public void stateChanged(ChangeEvent ce)
            {
                int value = (int) slider.getValue();
                ButtonPanel.panel.removeAll();
                buttonArray = new JButton[value];
                for (int i = 0; i < value; i++)
                {
                    buttonArray[i] = new JButton(String.valueOf(i));
                    buttonArray[i].addActionListener(actionButton);
                    ButtonPanel.panel.add(buttonArray[i]);
                }
                ButtonPanel.panel.revalidate();
                ButtonPanel.panel.repaint();
            }
        });

        contentPane.add(slider);
        frame.getContentPane().add(contentPane);
        frame.pack();
        frame.setVisible(true);

        frame.requestFocusInWindow();
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new SliderExample().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

class ButtonPanel extends JFrame
{
    public static JPanel panel;

    public ButtonPanel()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        panel = new JPanel();
        panel.setLayout(new GridLayout(0, 2));
        getContentPane().add(panel);
        setSize(300, 300);
        setVisible(true);       
    }
}

对于您的语句this.buttonArray[i].addActionListener(this);,之所以不起作用,是因为您位于anonymous class new ChangeListener()的对象内,该对象本身没有任何名为buttonArray[i]的东西,这是是SliderExample类的实例变量,因此可以放置SliderExample类的对象,或者如果您要引用代码,则使用该类的Object像在您编写的NewFrame8内部一样初始化该数组JButton[] buttonArray = new JButton[120];,因此请使用NewFrame8的对象而不是this来引用buttonArray[i] thingy.

For your statement this.buttonArray[i].addActionListener(this);, the reason as to why this is not working, is because, you are inside the object of anonymous class new ChangeListener(), which doesn't have anything named buttonArray[i] inside itself, it's the Instance Variable of SliderExample class, so either place an object of SliderExample class or if you are referring to your code, then use the Object of the class which initializes the array like inside inside NewFrame8 you had written JButton[] buttonArray = new JButton[120];, so use NewFrame8's object instead of this to refer to the buttonArray[i] thingy.

这篇关于Java刷新第二种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆