Java:为多个动作扩展JFrame含义和1个侦听器

Nox*_*ous 3 java eclipse swing actionlistener

我有点困惑.我现在正在工作(刚开始学徒),需要创建一个完全可编辑的表(我很快就会使用SQL).所以我在这里有两个问题:

  1. 你不是说"不扩展JFrame"是什么意思?假设我有一个名为"TestDialog"的类,还有一个名为"TestUI"的JFrame.写的可以吗

    public class TestDialog extends TestUI

    正如我已经理解的那样,不应该创建一个类(称为MyExample)并且在这个类的内部只是写

    public class MyExample extends JFrame

    因为您在现有类中创建JFrame而不是单独创建它.

  2. 我会保持简短 - 我可以在1个监听器中使用2个动作(1个按钮)吗?就像是:

     public void actionPerformed(ActionEvent e) 
     {
         Action_One; Action_Two;
     }
    
    Run Code Online (Sandbox Code Playgroud)
    • 或者我需要使用2个不同的听众?

好吧,我想是的.对不起,我没有写清楚一切,我刚刚在这里注册,实际上专注于将我的语言翻译成英语.如果有人能像在Eclipse中那样告诉我如何在这里写,我会很感激,因为我无法真正了解如何.

Ser*_*kyy 5

继承的组合是一种重要的编程方法.所以我喜欢构建GUI.

public class Application {

  private JFrame mainFrame;

  private MainPanel mainPanel;

  private void installFrame() {
    // initialize main frame
    mainFrame = new JFrame("Title");
  }

  private void installComponents() {
    // install all components
    mainPanel = new MainPanel();
  }

  private void layout() {
    // provide layouting
    mainFrame.add(mainPanel.getComponent());
  }

  private void show() {
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        Application app = new Application();
        app.installFrame();
        app.installComponents();
        app.layout();
        app.show();
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

主面板没有JPanel的继承,但使用它的实例.

public class MainPanel {
  private JPanel mainPanel;

  public MainPanel() {
    mainPanel = new JPanel(new GridBagLayout()); // or another layout
    initComponents();
    layout();
  }

  private void initComponents() {
    // init all components here
  }

  private void layout() {
    // layout panel here
  }

  public Component getComponent() {
    return mainPanel;
  }
}
Run Code Online (Sandbox Code Playgroud)

我用于每个复杂组件的相同模式(例如树,表,列表,选项卡式窗格等).但是这种方法有一个缺点:没有支持它的GUI构建器.

关于操作:您可以提供组合操作.像这样的东西

public class CombinedAction extends AbstractAction {
  private Action[] delegates;
  public CombinedAction(String name, Icon icon, Action... someDelegates) {
    super(name, icon);
    delegates = someDelegates;
  }

  public void actionPerformed(ActionEvent ae) {
    for (Action delegate : delegates) {
      delegate.actionPerfromed(ae);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)