有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在单击JButton时使用swing创建新窗口

我需要为学校创建一个银行账户管理程序,我创建了第一页的“框架”,但我不了解一些事情:

  1. 单击按钮时如何使用Swing打开新窗口
  2. 如何为每个按钮设置不同的ActionListener
  3. 如果我改变策略,只想使用一个大窗口,让工作文本字段/标签出现和消失,我该怎么做

代码:

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

public class CreditUnion extends JFrame
{
//declare buttons
private JButton openAccount;
private JButton closeAccount;
private JButton makeLodgement;
private JButton makeWithdrawal;
private JButton requestOverdraft;

//constructor
public CreditUnion()
{
    super("ATM@CreditUnion");

    Container c = getContentPane();
    c.setLayout(new FlowLayout() );

    openAccount = new JButton("Open account");
    c. add(openAccount);

    closeAccount = new JButton("Close account");
    c. add(closeAccount);

    makeLodgement = new JButton("Make lodgement");
    c. add(makeLodgement);

    makeWithdrawal = new JButton("Make withdrawal");
    c. add(makeWithdrawal);

    requestOverdraft = new JButton("Request overdraft");
    c. add(requestOverdraft);

    /*create instance of inner class ButtonHandler
    to use for button event handling*/
    ButtonHandler handler = new ButtonHandler();
    openAccount.addActionListener(handler);
    closeAccount.addActionListener(handler);
    makeLodgement.addActionListener(handler);
    makeWithdrawal.addActionListener(handler);
    requestOverdraft.addActionListener(handler);

    setSize(800,600);
    show();
}


public static void main (String args[])
{
    CreditUnion app = new CreditUnion();
    app.addWindowListener(
    new WindowAdapter()
    {
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
    }
    );
}

//inner class for button event handling

private class ButtonHandler implements ActionListener
{
    public void actionPerformed (ActionEvent e)
    {
        JOptionPane.showMessageDialog(null, "You Pressed: " + e.getActionCommand() );
    }
}

共 (2) 个答案

  1. # 1 楼答案

    1- how to open a new window with Swing when I click a button?

    与显示任何窗口的方式相同。在按钮的ActionListener中,创建一个新窗口我建议您创建一个JDialog而不是JFrame,但这也取决于您的作业要求,并显示它

    2- how can I have different ActionListener for each button?

    为每个按钮添加不同的ActionListener。一个匿名的内部类(搜索这个)将非常适合这个

    3- if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it?

    使用CardLayout交换“视图”,通常是带有要交换组件的JPanel

  2. # 2 楼答案

    how to open a new window with Swing when I click a button?

    不要使用CardLayout,这样会减少用户的注意力

    查看How to use CardLayout了解更多详细信息

    how can I have different ActionListener for each button?

    您可以使用单独的类、内部类或匿名类,具体取决于您要实现的目标

    查看Nested classes了解更多详细信息

    if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it

    看到第一点了吗