【问题标题】:Card Layout will originally switch panels, by why won't it switch after the start of the program? [duplicate]Card Layout本来会切换面板,为什么程序启动后不切换? [复制]
【发布时间】:2016-08-01 19:15:53
【问题描述】:

所以我遇到了一种奇怪的错误。我正在使用卡片布局在 GUI 中的帮助面板和用户面板之间切换。在最初启动程序时,卡片布局按预期工作,并且每当用户按下“H”时都会切换,但如果您单击任何按钮或在文本字段中键入,您将无法再切换卡片面板。我查看了 oracle 文档,但一无所获。有谁知道是什么导致了这个问题?

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainPanel extends JPanel implements KeyListener{

    CardLayout cl = new CardLayout();
    userPanel up = new userPanel();
    HelpPanel hp = new HelpPanel();
    private boolean showUserPanel = true;

    private Timer mainTimer = new Timer(500, new ActionListener(){
        public void actionPerformed(ActionEvent event){
            up.setTipPercent();
        }
    });
//---------------------------------------------------------------------
//Constructor
    public MainPanel(){
        setLayout(cl);
        add(up, "userPanel");
        add(hp, "HelpPanel");
        cl.show(this, "userPanel");
        addKeyListener(this);
        setFocusable(true);
        mainTimer.start();
    }
//---------------------------------------------------------------------
//Key Listener Methods
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_H && showUserPanel == true){
            cl.show(this, "HelpPanel");
            mainTimer.stop();
            showUserPanel = false;
        }else if(keyCode == e.VK_H && showUserPanel == false){
            cl.show(this, "userPanel");
            showUserPanel = true;
            mainTimer.start();
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub

    }


}

这是userPanel

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;

//---------------------------------------------------------------------
public class userPanel extends JPanel{
    //Fields
    private JButton calc;
    private JRadioButton fiveP, tenP, fiftP, twenP;
    private ButtonGroup buttonGroup;
    private double tipAmount = 0.0;
    private JTextField tipArea;
    private JTextArea totalArea;

//---------------------------------------------------------------------         
//Constructor
    public userPanel(){
        setBackground(Color.BLACK);
        tipArea = new JTextField("Enter bill amount");
        totalArea = new JTextArea("");
        setupButtons();
        tipArea.setPreferredSize(new Dimension(300,40));
        totalArea.setPreferredSize(new Dimension(300,40));
    }
//---------------------------------------------------------------------
//Setup JComponents
    public void setupButtons(){
        calc = new JButton("Calculate the Tip");
        calc.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                calculateTheTip(tipAmount);
            }
        });
        buttonGroup = new ButtonGroup();

        fiveP = new JRadioButton("Five Percent");
        tenP = new JRadioButton("Ten Percent");
        fiftP = new JRadioButton("Fifteen Percent");
        twenP = new JRadioButton("Twenty Percent");

        buttonGroup.add(fiveP);
        buttonGroup.add(tenP);
        buttonGroup.add(fiftP);
        buttonGroup.add(twenP);

        add(fiveP);
        add(tenP);
        add(fiftP);
        add(twenP);

        add(tipArea);
        add(totalArea);

        add(calc);
    }
//---------------------------------------------------------------------
//Calculate the total and display it to the user
public void calculateTheTip(double total){
    String theTotal = tipArea.getText();
    //Take user input and make sure it is a number
    try{
        double billAmount = Double.parseDouble(theTotal);
        total = billAmount*total;
        double totalAmt = billAmount + billAmount*tipAmount;
        totalArea.setText("Tip: "+total+ " \nTotal: " + totalAmt);
    }catch(NumberFormatException E){
        totalArea.setText("Please Enter only the amount without a $ or text!");
    }
    return;
}
//---------------------------------------------------------------------
//Chose which tipPercent to use     
    public void setTipPercent(){
        if(fiveP.isSelected()){
            tipAmount = .05;
        }else if(tenP.isSelected()){
            tipAmount = .1;
        }else if(fiftP.isSelected()){
            tipAmount = .15;
        }else{
            tipAmount = .2;
        }
    }
}

这是Help Panel

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

public class HelpPanel extends JPanel{
    public HelpPanel(){
        setBackground(Color.BLACK);
    }
}

【问题讨论】:

    标签: java swing jpanel cardlayout


    【解决方案1】:

    按下按钮等,将焦点从MainPanel 移开。 KeyEvents 被发送到具有焦点的对象而不是 MainPanel

    我建议将KeyListener 创建为一个单独的对象并将其添加到其他组件中。

    【讨论】:

    • 添加到其他组件是什么意思?
    • @BobbyC.Robillard 在MainPanel 的构造函数中,你有addKeyListener(this)。这会将KeyListener 添加到您的Main Panel 实例中。您必须对其他组件执行此操作,例如 `button.addKeyListener(listener); This thread 可能会有所帮助。
    • 为什么要将keyListener添加到按钮或其他组件中?这些都不应该成为焦点。我不明白您为什么要链接该主题,它似乎不适用,或者如果适用,请您解释原因?
    • 当用户点击一个按钮时,该按钮获得焦点。该按钮将保持焦点,直到用户单击其他内容或您的代码以编程方式将焦点转移到另一个组件。听起来您应该查看Focus TutorialKeyListener Tutorial
    • 我相信我现在明白了,我正在查看 Java Key_Binding 文档。感谢您的帮助!
    【解决方案2】:

    您的程序无法知道单击H 是否意味着按下了换卡键,或者您正在写入JTextField

    对于您的问题,使用键绑定,这是最好的解决方案,因为它将焦点更改为您想要关注的组件。阅读docs

    【讨论】:

    • 是的,我可以这样做,但这不是目标。但是,如果我理解正确,任何时候用户与 userPanel 的另一个组件交互时,焦点都会转移到该组件?
    • @BobbyC.Robillard 好的,我编辑了我的答案,结果发现键绑定可能是解决您问题的最佳方法,因为这里的对象是对特定组件的关注,请仔细阅读文档,我希望这会对你有所帮助。
    • 是的,我相信是的,我目前正在审核文件,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2021-07-11
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多