在java swing中从一帧移动到另一帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18224635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:27:48  来源:igfitidea点击:

Moving from one frame to another in java swing

javaswingjframemultiple-instanceswindowbuilder

提问by user2681161

I'm just making a small application on window builder and need some help with it. I've made 2 frames individually and I don't know how to specify the action of the button in such a way that when I click on the 'next' botton in the first frame, I want it to move to the second frame.

我只是在窗口构建器上制作一个小应用程序,需要一些帮助。我已经单独制作了 2 帧,但我不知道如何指定按钮的动作,这样当我单击第一帧中的“下一个”按钮时,我希望它移动到第二帧。

Here's the source code for each file.

这是每个文件的源代码。

first.java

首先.java

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;

import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;


public class first extends JFrame {

private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                first frame = new first();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public first() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnNext = new JButton("Next");
    btnNext.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnNext.setAction(action_1);
    btnNext.setBounds(257, 228, 55, 23);
    contentPane.add(btnNext);

    JButton btnExit = new JButton("Exit");
    btnExit.setBounds(344, 228, 51, 23);
    contentPane.add(btnExit);

    JRadioButton rdbtnAdd = new JRadioButton("Add");
    rdbtnAdd.setBounds(27, 80, 109, 23);
    contentPane.add(rdbtnAdd);

    JRadioButton rdbtnDelete = new JRadioButton("Delete");
    rdbtnDelete.setBounds(27, 130, 109, 23);
    contentPane.add(rdbtnDelete);

    JRadioButton rdbtnEdit = new JRadioButton("Edit");
    rdbtnEdit.setBounds(27, 180, 109, 23);
    contentPane.add(rdbtnEdit);

    JLabel lblSelectAnOption = new JLabel("Select an Option");
    lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblSelectAnOption.setBounds(27, 36, 121, 23);
    contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
    public SwingAction() {
        putValue(NAME, "Next");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        new second_add();
    }
}
}

second.java

第二个.java

    import java.awt.BorderLayout;
    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    import javax.swing.JComboBox;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import javax.swing.Action;
    import java.awt.event.ActionListener;


    public class second_add extends JFrame {

        private JPanel contentPane;
        private JTextField txtTypeYourQuestion;
        private JTextField txtQuestionWeight;
        private JTextField txtEnter;
        private JTextField txtEnter_1;
        private JTextField txtValue;
        private JTextField txtValue_1;
        private final Action action = new SwingAction();

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        second_add frame = new second_add();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public second_add() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 450, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);

            txtTypeYourQuestion = new JTextField();
            txtTypeYourQuestion.setBounds(22, 11, 177, 20);
            txtTypeYourQuestion.setText("Type your Question Here");
            contentPane.add(txtTypeYourQuestion);
            txtTypeYourQuestion.setColumns(10);

            txtQuestionWeight = new JTextField();
            txtQuestionWeight.setBounds(209, 11, 86, 20);
            txtQuestionWeight.setText("Question weight");
            contentPane.add(txtQuestionWeight);
            txtQuestionWeight.setColumns(10);

            txtEnter = new JTextField();
            txtEnter.setBounds(22, 55, 86, 20);
            txtEnter.setText("Enter . . .");
            contentPane.add(txtEnter);
            txtEnter.setColumns(10);

            txtEnter_1 = new JTextField();
            txtEnter_1.setText("Enter . . . ");
            txtEnter_1.setBounds(22, 104, 86, 20);
            contentPane.add(txtEnter_1);
            txtEnter_1.setColumns(10);

            txtValue = new JTextField();
            txtValue.setText("Value . .");
            txtValue.setBounds(118, 55, 51, 20);
            contentPane.add(txtValue);
            txtValue.setColumns(10);

            txtValue_1 = new JTextField();
            txtValue_1.setText("Value . .");
            txtValue_1.setBounds(118, 104, 51, 20);
            contentPane.add(txtValue_1);
            txtValue_1.setColumns(10);

            JButton btnFinish = new JButton("Finish");
            btnFinish.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                }
            });
            btnFinish.setAction(action);
            btnFinish.setBounds(335, 228, 89, 23);
            contentPane.add(btnFinish);

            JButton btnAddChoice = new JButton("Add choice");
            btnAddChoice.setBounds(236, 228, 89, 23);
            contentPane.add(btnAddChoice);

            JButton btnAddQuestion = new JButton("Add question");
            btnAddQuestion.setBounds(136, 228, 89, 23);
            contentPane.add(btnAddQuestion);

        }
        private class SwingAction extends AbstractAction {
            public SwingAction() {
                putValue(NAME, "");
                putValue(SHORT_DESCRIPTION, "Some short description");
            }
            public void actionPerformed(ActionEvent e) {
            }
        }
    }

回答by Sajal Dutta

Modify like this-

修改成这样——

JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        second_add second = new second_add();   
        setVisible(false); // Hide current frame
        second.setVisible(true);
    }
});

回答by LuigiEdlCarno

The quick and dirty solution would to set the first frame's visibility to false and the second frames visibility to true in your buttonclick action. (see Sajal Dutta's answer)

快速而肮脏的解决方案是在按钮单击操作中将第一帧的可见性设置为 false,将第二帧的可见性设置为 true。(见 Sajal Dutta 的回答)

But to have a consistent behaviour even for more than 2 frames, let each frame be stored in a HashTable in your main class (class holding the mainmethod and notextending JFrame) with the ID being the order of the frame (first frame D 1, second: ID 2, etc.).

但是为了即使超过 2 帧也有一致的行为,让每个帧都存储在主类(持有main方法的类而不是扩展 JFrame 的类)中的 HashTable 中,ID 是帧的顺序(第一帧 D 1,第二个:ID 2 等)。

Then create a static method

然后创建一个静态方法

public void switchFrame(JFrame originatingFrame, int NextFrame){
    originatingFrame.this.setVisible(false);
    ((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}

in your main class which can be called from each frame using

在您的主类中,可以使用从每个框架调用

mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);

that way you can also implement "Back"- and "Skip"-Buttons should you want to create something like a wizard.

这样,如果您想创建类似向导的东西,您还可以实现“返回”和“跳过”按钮。

NOTE:I did not test this code. This should just be seen as a general overview of how to do this.

注意:我没有测试这段代码。这应该被视为如何做到这一点的一般概述。

回答by maneesh

  • Having multiple JFrame instances in one application is bad usability
  • Consider using something like a CardLayoutinstead.
  • 在一个应用程序中拥有多个 JFrame 实例的可用性很差
  • 考虑使用类似CardLayout 的东西。

回答by Malwaregeek

You can navigate to a frame by creating its object and using setVisible method to display it. If you want to do it on a button click, write it inside its event handler.

您可以通过创建框架对象并使用 setVisible 方法显示它来导航到框架。如果您想在单击按钮时执行此操作,请将其写入其事件处理程序中。

JFrame o = new JFrame();
o.setVisible(true);
dispose();        // This will close the current frame

回答by edr007

The below piece of code will show to navigate from one page to another page in a menu format.

下面的一段代码将显示以菜单格式从一个页面导航到另一个页面。

 import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.CardLayout;
    import java.awt.Container;
    import java.awt.GraphicsEnvironment;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Panel;
    import java.awt.TextArea;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;

    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;

public class AddressBookDemo implements ActionListener, Runnable {

    ArrayList personsList;
    PersonDAO pDAO;
    Panel panel;
    JFrame appFrame;
    JLabel jlbName, jblPassword, jlbAddress;
    JPasswordField jPassword;
    JTextField jtfName, jtfAddress;
    JButton jbbSave, jbnClear, jbnExit, btnNext, button;
    String name, address, password;
    final int CARDS = 4;
    CardLayout cl = new CardLayout();
    JPanel cardPanel = new JPanel(cl);
    CardLayout c2 = new CardLayout();
    JPanel cardPanel2 = new JPanel(c2);
    int currentlyShowing = 0;
    Thread errorThrower; 
    // int phone;
    // int recordNumber; // used to naviagate using >> and buttons
    Container cPane;
    Container cPane2;

    private JFrame frame;
    private TextArea textArea;
    private Thread reader;
    private Thread reader2;
    private boolean quit;

    private final PipedInputStream pin = new PipedInputStream();
    private final PipedInputStream pin2 = new PipedInputStream();
    public static void main(String args[]) {
        new AddressBookDemo();
    }

    public AddressBookDemo() {
        name = "";
        password = "";
        address = "";
        // phone = -1; //Stores 0 to indicate no Phone Number
        // recordNumber = -1;
        createGUI();
        personsList = new ArrayList();
        // creating PersonDAO object
        pDAO = new PersonDAO();
    }

    public void createGUI() {

        /* Create a frame, get its contentpane and set layout */
        appFrame = new JFrame("ManualDeploy ");
        cPane = appFrame.getContentPane();
        cPane.setLayout(new GridBagLayout());
//      frame=new JFrame("Java Console");
        textArea=new TextArea();
        textArea.setEditable(false);
        Button button=new Button("clear");

         panel=new Panel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
        gridBagConstraintsx01.gridx = 0;
        gridBagConstraintsx01.gridy = 0;
        gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
        panel.add(textArea,gridBagConstraintsx01);
        GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
        gridBagConstraintsx03.gridx = 0;
        gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx03.gridy = 1;
        panel.add(button,gridBagConstraintsx03);
//      frame.add(panel);

//      frame.setVisible(true);     
//      cPane2 = frame.getContentPane();
//      cPane2.setLayout(new GridBagLayout());
        button.addActionListener(this);

        try
        {
            PipedOutputStream pout=new PipedOutputStream(this.pin);
            System.setOut(new PrintStream(pout,true));  
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
        } 

        try 
        {
            PipedOutputStream pout2=new PipedOutputStream(this.pin2);
            System.setErr(new PrintStream(pout2,true));
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
        }       

        quit=false; // signals the Threads that they should exit

        // Starting two seperate threads to read from the PipedInputStreams             
        //
        reader=new Thread(this);
        reader.setDaemon(true); 
        reader.start(); 
        //
        reader2=new Thread(this);   
        reader2.setDaemon(true);    
        reader2.start();

        // testing part
        // you may omit this part for your application
        // 
        System.out.println("Hello World 2");
        System.out.println("All fonts available to Graphic2D:\n");
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames=ge.getAvailableFontFamilyNames();
        for(int n=0;n<fontNames.length;n++)  System.out.println(fontNames[n]);      
        // Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
        // We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
        System.out.println("\nLets throw an error on this console");    
        errorThrower=new Thread(this);
        errorThrower.setDaemon(true);
        errorThrower.start();



        arrangeComponents();
        // arrangeComponents2();
        final int CARDS = 2;
        final CardLayout cl = new CardLayout();
        final JPanel cardPanel = new JPanel(cl);
        JMenu menu = new JMenu("M");
        for (int x = 0; x < CARDS; x++) {
            final int SELECTION = x;
            JPanel jp = new JPanel();
            if (x == 0) {
                jp.add(cPane);
            } else if (x == 1) {
                 jp.add(panel);
            } else if (x == 2)
                jp.add(new JButton("Panel 2"));
            else
                jp.add(new JComboBox(new String[] { "Panel 3" }));
            cardPanel.add("" + SELECTION, jp);
            JMenuItem menuItem = new JMenuItem("Show Panel " + x);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    currentlyShowing = SELECTION;
                    cl.show(cardPanel, "" + SELECTION);
                }
            });
            menu.add(menuItem);
        }
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);

        btnNext = new JButton("Next >>");

        JButton btnPrev = new JButton("<< Previous");
        JPanel p = new JPanel(new GridLayout(1, 2));
        p.add(btnPrev);
        p.add(btnNext);
        btnNext.setVisible(false);
        JFrame f = new JFrame();
        f.getContentPane().add(cardPanel);
        f.getContentPane().add(p, BorderLayout.SOUTH);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 500);
        f.setLocationRelativeTo(null);
        f.setJMenuBar(menuBar);
        f.setVisible(true);
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (currentlyShowing < CARDS - 1) {
                    cl.next(cardPanel);
                    currentlyShowing++;
                }
            }
        });
        btnPrev.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (currentlyShowing > 0) {
                    cl.previous(cardPanel);
                    currentlyShowing--;
                }
            }
        });

    }

    public void arrangeComponents() {
        jlbName = new JLabel("Username");
        jblPassword = new JLabel("Password");
        jlbAddress = new JLabel("Sftpserver");
        jtfName = new JTextField(20);
        jPassword = new JPasswordField(20);
        jtfAddress = new JTextField(20);
        jbbSave = new JButton("move sftp");
        jbnClear = new JButton("Clear");
        jbnExit = new JButton("Exit");
        /* add all initialized components to the container */
        GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
        gridBagConstraintsx01.gridx = 0;
        gridBagConstraintsx01.gridy = 0;
        gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
        cPane.add(jlbName, gridBagConstraintsx01);
        GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
        gridBagConstraintsx02.gridx = 1;
        gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx02.gridy = 0;
        gridBagConstraintsx02.gridwidth = 2;
        gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
        cPane.add(jtfName, gridBagConstraintsx02);
        GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
        gridBagConstraintsx03.gridx = 0;
        gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx03.gridy = 1;
        cPane.add(jblPassword, gridBagConstraintsx03);
        GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
        gridBagConstraintsx04.gridx = 1;
        gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx04.gridy = 1;
        gridBagConstraintsx04.gridwidth = 2;
        gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
        cPane.add(jPassword, gridBagConstraintsx04);
        GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
        gridBagConstraintsx05.gridx = 0;
        gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx05.gridy = 2;
        cPane.add(jlbAddress, gridBagConstraintsx05);
        GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
        gridBagConstraintsx06.gridx = 1;
        gridBagConstraintsx06.gridy = 2;
        gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx06.gridwidth = 2;
        gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
        cPane.add(jtfAddress, gridBagConstraintsx06);
        GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
        gridBagConstraintsx09.gridx = 0;
        gridBagConstraintsx09.gridy = 4;
        gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbbSave, gridBagConstraintsx09);
        GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
        gridBagConstraintsx10.gridx = 1;
        gridBagConstraintsx10.gridy = 4;
        gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbnClear, gridBagConstraintsx10);
        GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
        gridBagConstraintsx11.gridx = 2;
        gridBagConstraintsx11.gridy = 4;
        gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbnExit, gridBagConstraintsx11);
        jbbSave.addActionListener(this);
        // jbnDelete.addActionListener(this);
        jbnClear.addActionListener(this);
        jbnExit.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("inside button123");
        if (e.getSource() == jbbSave) {
            savePerson();
        } else if (e.getSource() == jbnClear) {
            clear();
        } else if (e.getSource() == jbnExit) {
            System.exit(0);
        }
        else if (e.getSource() == button)
        {
            System.out.println("inside button");
            textArea.setText(" ");
        }
    }

    // Save the Person into the Address Book
    public void savePerson() {
        name = jtfName.getText();
        password = jPassword.getText();
        address = jtfAddress.getText();
        if (name.equals("")) {
            JOptionPane.showMessageDialog(null, "Please enter password",
                    "ERROR", JOptionPane.ERROR_MESSAGE);
        } else if (password != null && password.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Please enter password",
                    "ERROR", JOptionPane.ERROR_MESSAGE);
        }

        else {
            btnNext.setVisible(true);
            JOptionPane.showMessageDialog(null, "Person Saved");
        }
    }

    public void clear() {
        jtfName.setText("");
        jPassword.setText("");
        jtfAddress.setText("");
        personsList.clear();
    }

    public synchronized void run()
    {
        try
        {           
            while (Thread.currentThread()==reader)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin.available()!=0)
                {
                    String input=this.readLine(pin);
                    textArea.append(input);
                }
                if (quit) return;
            }

            while (Thread.currentThread()==reader2)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin2.available()!=0)
                {
                    String input=this.readLine(pin2);
                    textArea.append(input);
                }
                if (quit) return;
            }           
        } catch (Exception e)
        {
            textArea.append("\nConsole reports an Internal error.");
            textArea.append("The error is: "+e);            
        }

        // just for testing (Throw a Nullpointer after 1 second)
//      if (Thread.currentThread()==errorThrower)
//      {
//          try { this.wait(1000); }catch(InterruptedException ie){}
//          throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
//      }

    }

    public synchronized String readLine(PipedInputStream in) throws IOException
    {
        String input="";
        do
        {
            int available=in.available();
            if (available==0) break;
            byte b[]=new byte[available];
            in.read(b);
            input=input+new String(b,0,b.length);                                                       
        }while( !input.endsWith("\n") &&  !input.endsWith("\r\n") && !quit);
        return input;
    }   
    public synchronized void windowClosed(WindowEvent evt)
    {
        quit=true;
        this.notifyAll(); // stop all threads
        try { reader.join(1000);pin.close();   } catch (Exception e){}      
        try { reader2.join(1000);pin2.close(); } catch (Exception e){}
        System.exit(0);
    }       



}