如何使 txPanel 仅在单击'enter pin ok'按钮后可见?


public class ATMgui extends JFrame implements ActionListener {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 500;
    public static final int HEIGHT = 200;
    private ATMbizlogic theBLU;// short for the Business Logic Unit
    public JLabel totalBalanceLabel;
    public JTextField withdrawTextField;
    public JTextField depositTextField;
    public JTextField pinTextField;
    /**
     * Creates a new instance of ATMgui
     */
    public ATMgui() {
        setTitle("ATM Transactions");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setBackground(Color.BLACK);
        contentPane.setLayout(new BorderLayout());

        // Do the panel for the rest stop
        JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
        Font curFont = start.getFont();
        start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
        start.setForeground(Color.BLUE);
        start.setOpaque(true);
        start.setBackground(Color.BLACK);

        pinTextField = new JTextField();
        JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
        pinLabel.setForeground(Color.RED);
        pinLabel.setOpaque(true);
        pinLabel.setBackground(Color.WHITE);

        JButton pinButton = new JButton("Enter Pin OK");
        pinButton.addActionListener(this);
        pinButton.setBackground(Color.red);
        JPanel pinPanel = new JPanel();
        pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
        pinPanel.add(pinLabel);
        pinPanel.add(pinTextField);
        pinPanel.add(pinButton);
        contentPane.add(pinPanel, BorderLayout.WEST);

        JPanel headingPanel = new JPanel();
        headingPanel.setLayout(new GridLayout());
        headingPanel.add(start);
        contentPane.add(headingPanel, BorderLayout.NORTH);

        // Do the panel for the amount & type of transactions
        withdrawTextField = new JTextField();
        JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
        withdrawLabel.setForeground(Color.RED);
        withdrawLabel.setOpaque(true);
        withdrawLabel.setBackground(Color.WHITE);

        depositTextField = new JTextField();
        JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
        depositLabel.setForeground(Color.RED);
        depositLabel.setOpaque(true);
        depositLabel.setBackground(Color.WHITE);

        JButton txButton = new JButton("Transactions OK");
        txButton.addActionListener(this);
        txButton.setBackground(Color.red);


        JPanel txPanel = new JPanel();
        txPanel.setLayout(new GridLayout(5, 1, 30, 0));
        txPanel.add(withdrawLabel);
        txPanel.add(withdrawTextField);
        txPanel.add(depositLabel);
        txPanel.add(depositTextField);
        txPanel.add(txButton);
        contentPane.add(txPanel, BorderLayout.EAST);
        txPanel.setVisible(true);

        totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
        totalBalanceLabel.setForeground(Color.BLUE);
        totalBalanceLabel.setOpaque(true);
        totalBalanceLabel.setBackground(Color.BLACK);

        contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);

        theBLU = new ATMbizlogic();
    }
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        // Container contentPane = getContentPane();
        if (actionCommand.equals("Transactions OK")) {
            try {
                double deposit = Double.parseDouble(depositTextField.getText().trim());
                double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
                theBLU.computeBalance(withdraw, deposit);
                totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
            } catch (ATMexception ex) {
                totalBalanceLabel.setText("Error: " + ex.getMessage());
            } catch (Exception ex) {
                totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
            }
        } else if (actionCommand.equals("Enter Pin OK")) {
            try {
                double pin = Double.parseDouble(pinTextField.getText().trim());
                theBLU.checkPin(pin);
                totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());

            } catch (ATMexception ex) {
                totalBalanceLabel.setText("Error: " + ex.getMessage());
            } catch (Exception ex) {
                totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
            }
        } else {
            System.out.println("Error in button interface.");
        }
    }
    public static void main(String[] args) {
        ATMgui gui = new ATMgui();
        gui.setVisible(true);
    }
}

我认为这不是实现按钮ActionListeners的正确方法。

public void actionPerformed(ActionEvent e) 
    {   
       String actionCommand = e.getActionCommand();
      // Container contentPane = getContentPane();
        if (actionCommand.equals("Transactions OK"))
        else ...
    }

使用actionPerformed方法中的if-else stamments,程序被迫在每次按下任何按钮时检查要调用哪个侦听器,这样一来,代码就不容易编辑和重用。此外,GUI容器的作用就像事件的接收器,那么您应该避免

pinButton.addActionListener(this);

尝试为每个按钮实现自己的内部类,如下所示:

JButton pinButton = new JButton("Enter Pin OK");
        pinButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae){
                    //enter here your action
                                     txPanel.setVisible(true);
                }
            });

通过这种方式,您不需要为类实现ActionListener接口,因为您正在为pinButton实现接口的内部距离。检查SO的这个老问题。此外,您应该避免在类构造函数中实现所有GUI元素,最好在单独的方法中实现GUI,如createAndShowGui(),并在构造函数中调用它,以尊重Java Swing约定,并在不同于应用程序主线程的另一个线程(称为Event Dispatch thread)中运行Swing组件。阅读此问题。

然后在createAndShowGui()方法中加入txPanel.setVisible(false);

请记住,Swing组件不是线程安全的。

由于您粘贴的代码不起作用,我为您制作了一个小程序,请看一看,看看您可以做些什么更改来将其纳入您的案例中:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelTest extends JFrame
{
    private JPanel eastPanel;
    public PanelTest()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);
        Container container = getContentPane();
        eastPanel = new JPanel();
        eastPanel.setBackground(Color.DARK_GRAY);
        JPanel westPanel = new JPanel();
        westPanel.setBackground(Color.YELLOW);
        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.BLUE);
        container.add(eastPanel, BorderLayout.LINE_START);
        container.add(centerPanel, BorderLayout.CENTER);
        container.add(westPanel, BorderLayout.LINE_END);
        eastPanel.setVisible(false);
        JButton showButton = new JButton("Click Me to Display EAST JPanel");
        showButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                eastPanel.setVisible(true);
            }
        });
        JButton hideButton = new JButton("Click Me to Hide EAST JPanel");
        hideButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                eastPanel.setVisible(false);
            }
        });
        container.add(hideButton, BorderLayout.PAGE_START);
        container.add(showButton, BorderLayout.PAGE_END);
        setSize(300, 300);
        setVisible(true);
    }
    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new PanelTest();
            }
        });
    }
}

今后,BorderLayout永远不要使用NORTHEASTWESTSOUTH。它们分别被PAGE_STARTLINE_STARTLINE_ENDPAGE_END取代。

BorderLayout对象有五个区域。这些区域由BorderLayout常量指定:

  • 页面启动
  • 页面结束
  • LINE_START
  • LINE_END
  • 中心

版本说明:在JDK 1.4版本之前,不同区域的首选名称是不同的,从指南针的点(例如,顶部区域的BorderLayout.NORTH)到我们在示例中使用的常量的更详细版本。我们的例子使用的常量是首选的,因为它们是标准的,使程序能够适应不同方向的语言

我修改了ATMLogin类的checkPin(...)方法,以返回boolean而不是void,因此在ATMgui类的actionPerformed(...)方法中,如果此项返回true,则仅将所需的JPanel设置为可见,否则将不执行任何操作

一定要检查代码,看看你能做些什么更改来让它为你的目的工作。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMgui extends JFrame implements ActionListener 
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 500;
    public static final int HEIGHT = 200;
    private ATMbizlogic theBLU;// short for the Business Logic Unit
    private JPanel txPanel;
    public JLabel totalBalanceLabel;
    public JTextField withdrawTextField;
    public JTextField depositTextField;
    public JTextField pinTextField;
    /**
     * Creates a new instance of ATMgui
     */
    public ATMgui() 
    {
        setTitle("ATM Transactions");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setBackground(Color.BLACK);
        contentPane.setLayout(new BorderLayout());

        // Do the panel for the rest stop
        JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
        Font curFont = start.getFont();
        start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
        start.setForeground(Color.BLUE);
        start.setOpaque(true);
        start.setBackground(Color.BLACK);

        pinTextField = new JTextField();
        JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
        pinLabel.setForeground(Color.RED);
        pinLabel.setOpaque(true);
        pinLabel.setBackground(Color.WHITE);

        JButton pinButton = new JButton("Enter Pin OK");
        pinButton.addActionListener(this);
        pinButton.setBackground(Color.red);
        JPanel pinPanel = new JPanel();
        pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
        pinPanel.add(pinLabel);
        pinPanel.add(pinTextField);
        pinPanel.add(pinButton);
        contentPane.add(pinPanel, BorderLayout.WEST);

        JPanel headingPanel = new JPanel();
        headingPanel.setLayout(new GridLayout());
        headingPanel.add(start);
        contentPane.add(headingPanel, BorderLayout.NORTH);

        // Do the panel for the amount & type of transactions
        withdrawTextField = new JTextField();
        JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
        withdrawLabel.setForeground(Color.RED);
        withdrawLabel.setOpaque(true);
        withdrawLabel.setBackground(Color.WHITE);

        depositTextField = new JTextField();
        JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
        depositLabel.setForeground(Color.RED);
        depositLabel.setOpaque(true);
        depositLabel.setBackground(Color.WHITE);

        JButton txButton = new JButton("Transactions OK");
        txButton.addActionListener(this);
        txButton.setBackground(Color.red);


        txPanel = new JPanel();
        txPanel.setLayout(new GridLayout(5, 1, 30, 0));
        txPanel.add(withdrawLabel);
        txPanel.add(withdrawTextField);
        txPanel.add(depositLabel);
        txPanel.add(depositTextField);
        txPanel.add(txButton);
        contentPane.add(txPanel, BorderLayout.EAST);
        txPanel.setVisible(false);

        totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
        totalBalanceLabel.setForeground(Color.BLUE);
        totalBalanceLabel.setOpaque(true);
        totalBalanceLabel.setBackground(Color.BLACK);

        contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);

        theBLU = new ATMbizlogic();
    }
    public void actionPerformed(ActionEvent e) 
    {
        String actionCommand = e.getActionCommand();
        // Container contentPane = getContentPane();
        if (actionCommand.equals("Transactions OK")) 
        {
            try 
            {
                double deposit = Double.parseDouble(depositTextField.getText().trim());
                double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
                theBLU.computeBalance(withdraw, deposit);
                totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
            } 
            /*catch (ATMexception ex) 
            {
                totalBalanceLabel.setText("Error: " + ex.getMessage());
            }*/ 
            catch (Exception ex) 
            {
                totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
            }
        } 
        else if (actionCommand.equals("Enter Pin OK")) 
        {
            try 
            {               
                double pin = Double.parseDouble(pinTextField.getText().trim());
                if(theBLU.checkPin(pin))
                    txPanel.setVisible(true);
                totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());               
            } 
            /*catch (ATMexception ex) 
            {
                totalBalanceLabel.setText("Error: " + ex.getMessage());
            }*/ 
            catch (Exception ex) 
            {
                totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
                ex.printStackTrace();
            }
        } 
        else 
        {
            System.out.println("Error in button interface.");
        }
    }
    public static void main(String[] args) 
    {
        ATMgui gui = new ATMgui();
        gui.setVisible(true);
    }
}
class ATMbizlogic 
{
    private double totalBalance;
    private boolean rightPinEntered;
    /**
     * Creates a new instance of ATMbizlogic
     */
    public ATMbizlogic() 
    {
        totalBalance = 0.0;
        rightPinEntered =  true;
    }
    public void computeBalance(double withdraw, double deposit)
    //throws ATMexception 
    {
        if(withdraw <=0)
        {
            System.out.println("Negative withdraw not allowed");
            //throw new ATMexception("Negative withdraw not allowed");
        }   
        if(deposit <=0)
        {
            System.out.println("Negative deposit not allowed");
            //throw new ATMexception("Negative deposit not allowed");
        }   
         double balance = deposit - withdraw;
        totalBalance = totalBalance + balance;
    }
    public boolean checkPin(double pin)
    //throws ATMexception 
    {
        if(pin <=0)
        {
            System.out.println("Negative pin not allowed");
            rightPinEntered = false;
            //throw new ATMexception("Negative pin not allowed");
        }   
        /*else if(rightPinEntered == false)
        {
            System.out.println("Can not take another pin");
            rightPinEntered = false;
            //throw new ATMexception("Can not take another pin");
        }*/ 
        else if(pin<1111 || pin>9999)
        {
            System.out.println("Enter a valid pin");
            rightPinEntered = false;
            //throw new ATMexception("Enter a valid pin");
        }
        else
        {       
            rightPinEntered = true;
        }
        return rightPinEntered;
    }
    public double getBalance()
    {
        return totalBalance;
    }
}

在对构造函数ATMgui()的调用中,放入

txPanel.setVisible(false);

在actionCommand.equals("Enter Pin OK")部分,您可以将其设置为true。

这就是你想要的吗?

最新更新