0

我在弄清楚如何使用事件处理程序以在 2 个面板之间删除和重绘时遇到问题。

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

public class PanelSwitcherView extends JFrame {
private JPanel panel1, panel2;

public PanelSwitcherView() {
    super("Panel Switching Test");

    Font font = new Font("SansSerif", Font.BOLD, 30);
    panel1 = new JPanel();
    panel1.setLayout(new GridLayout(2, 2, 5, 5));

    font = new Font("Serif", Font.ITALIC, 30);
    panel2 = new JPanel();
    panel2.setLayout(new BorderLayout());

在这里我决定添加一个测试 ActionListener 但不确定是否正确使用

    font = new Font("Monospaced", Font.BOLD + Font.ITALIC, 30);
    JButton button = new JButton("Switch Panels");
    button.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
          System.out.print("Test");
          PanelSwitcherModel.switchPanel(); // used to make value of whichpanel 1 or 2
       }
    });
    button.setFont(font);
    add(button, BorderLayout.NORTH);

    add(panel1, BorderLayout.CENTER);
}

也不完全确定如何使用它

    public void displayPanel(int whichPanel) {
    remove(panel1);
    remove(panel2); 
    if (whichPanel == 1) {
        System.out.println("Should display panel1");
        add(panel1, BorderLayout.CENTER);
    } else {
        System.out.println("Should display panel2");
        add(panel2, BorderLayout.CENTER);
    }
    validate();
    repaint();
}

我的控制器(下面的类)

public void register(PanelSwitcherController controller) {

   }

问题主要出在这里,我是这里的新手,我是否以某种方式将我的 ActionListener 移到这里?如何访问其他类以将面板选项的数字从 1 更改为 2?

import java.awt.event.*;


public class PanelSwitcherController implements ActionListener{

  public PanelSwitcherController(PanelSwitcherView view,
         PanelSwitcherModel model) {
   }

   public void actionPerformed(ActionEvent e) {

   }

   }
4

0 回答 0