如何使按钮打开一个新窗口并关闭旧窗口

时间:2012-07-01 20:18:51

标签: java swing jframe jbutton actionlistener

我希望它在按下按钮时关闭活动窗口并打开新窗口。

我得到它打开一个新窗口,但旧的窗口仍在那里。我试图实现frame.dispose();但我认为我做得不对。

这就是我所拥有的

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

public class MyPanel3 extends JPanel {

    private JTextField jcomp1;
    private JLabel jcomp2;
    private JLabel jcomp3;
    private JButton jcomp4;
    private JLabel clock;
    static final String ADD = "add";

    public MyPanel3() {
        //construct components
        jcomp1 = new JTextField(5);
        jcomp2 = new JLabel("How long were you parked?");
        jcomp3 = new JLabel("Minutes");
        jcomp4 = new JButton("Calculate Total");
        clock = new JLabel("newLabel");

        ImageIcon clockpic = new ImageIcon(
                "/Users/bnproductions/ALL/123FinalProject/bin/clock2.gif");
        JLabel clock = new JLabel(clockpic);
        jcomp4.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                final ImageIcon icon4 = new ImageIcon(
                        "/Users/bnproductions/ALL/123FinalProject/bin/money2.gif");
                JOptionPane.showMessageDialog(null, " Your total is $0.00",
                        "Parking Total", +JOptionPane.INFORMATION_MESSAGE, icon4);
            }
        });
        //adjust size and set layout
        setPreferredSize(new Dimension(335, 92));
        setLayout(null);

        //add components
        add(jcomp1);
        add(jcomp2);
        add(jcomp3);
        add(jcomp4);
        add(clock);

        //set component bounds (only needed by Absolute Positioning)
        jcomp1.setBounds(280, 30, 50, 20);
        jcomp2.setBounds(100, 25, 175, 30);
        jcomp3.setBounds(280, 15, 55, 20);
        jcomp4.setBounds(110, 55, 150, 25);
        clock.setBounds(5, 5, 90, 80);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("MyPanel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().add(new MyPanel3());
        frame.pack();
        frame.setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:6)

这是一个教科书示例,说明为什么有CardLayout,并同意JLabel最适合JComponents来展示ImageIcon / Icon

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

public class CardLayoutTest {

    private static final long serialVersionUID = 1L;
    private JPanel cardPanel;
    private CardLayout cardLayout;
    private JFrame frame;

    public CardLayoutTest() {
        JPanel cp = new JPanel(new BorderLayout());
        cp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        cardLayout = new CardLayout(5, 5);
        cardPanel = new JPanel(cardLayout);
        cp.add(cardPanel);
        for (int i = 0; i < 5; i++) {// Create random panels for testing.
            String name = "ImagePanel" + (i + 1);
            String image = (i & 1) == 0 ? "foo.gif" : "bar.gif";
            Color clr = (i & 1) == 0 ? Color.red : Color.blue;
            ImagePanel imgPanel = new ImagePanel(name, image, clr);
            cardPanel.add(imgPanel, name);
            cardLayout.addLayoutComponent(imgPanel, name);
        }
        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
        JButton prevButton = new JButton("< Previous");
        prevButton.setActionCommand("Previous");
        prevButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.previous(cardPanel);
            }
        });
        buttonPanel.add(prevButton);
        JButton nextButton = new JButton("Next >");
        nextButton.setActionCommand("Next");
        nextButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.next(cardPanel);
            }
        });
        buttonPanel.add(nextButton);
        JPanel temp = new JPanel(new BorderLayout());
        temp.add(buttonPanel, BorderLayout.LINE_END);
        cp.add(temp, BorderLayout.SOUTH);
        frame = new JFrame("Test");
        frame.add(cp);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CardLayoutTest();
            }
        });
    }
}

class ImagePanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private String imgString;
    private JLabel imgLabel;

    public ImagePanel(String name, String imgString, Color backGround) {
        setName(name);
        this.imgString = imgString;
        setLayout(new BorderLayout());
        setBackground((backGround));
        // Ensure size is correct even before any image is loaded.
        setPreferredSize(new Dimension(400, 300));
    }

    @Override
    public void setVisible(boolean visible) {
        if (visible) {
            System.err.println(getName() + ": Loading and adding image");
            ImageIcon icon = new ImageIcon(imgString);
            imgLabel = new JLabel(icon);
            add(imgLabel);
        }
        super.setVisible(visible);
        if (!visible) { // Do after super.setVisible() so image doesn't "disappear".
            System.err.println(getName() + ": Removing image");
            if (imgLabel != null) { // Before display, this will be null
                remove(imgLabel);
                imgLabel = null; // Hint to GC that component/image can be collected.
            }
        }
    }
}

答案 1 :(得分:4)

嗯,我写了一个简短的例子来做你要求的事情,希望你可以根据自己的需要进行调整:

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

public class JFramesTest extends JFrame {

    private JButton button = new JButton("Close This and Open another");

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFramesTest jFramesTest = new JFramesTest("Frame1");//create a new instance
            }
        });
    }

    public JFramesTest(String string) {
        super(string);
        createAndShowUI();
    }

    private void createAndShowUI() {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                dispose();//close the old frame of this instance
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        JFramesTest jFramesTest = new JFramesTest("Frame2");//create a new instance
                    }
                });
            }
        });

        getContentPane().add(button, BorderLayout.CENTER);
        setVisible(true);
    }
}