我正在创建一个显示图形和操作图形的用户界面。该类扩展JFrame实现了ActionListener。然后,ActionListener根据操作调用不同的类来操作图形。这种方法很有效,而班级的ActionListeners很少;然而,现在这堂课变得难以管理。
我知道,为了封装,最好在用户界面类中使用ActionListener,因为它需要访问接口的非静态组件。但是,封装和可读性之间似乎存在冲突。
我建议将类分为一个接口类,第二个接收ActionListener并静态访问接口组件。我想知道的是,这是遵循基本的设计惯例吗?并且,如果这是一种可接受的方法,您会将主类放在用户界面类或ActionListener类中吗?
答案 0 :(得分:6)
Not a duplicate question... but my answer should help with your question
简短的总结,我的偏好是让JFrame类不实现ActionListener,然后有许多带有JFrame的命名内部类,它们实现了ActionListener。
我会把主要的东西放在一个类中......并称之为Main。
以下是我喜欢的方式的示例代码:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main
{
private Main()
{
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
final FooFrame frame;
frame = new FooFrame();
frame.setupGUI();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
然后是GUI:
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FooFrame
extends JFrame
{
private final JButton incrementBtn;
private final JButton decrementBtn;
private int value;
{
incrementBtn = new JButton("++");
decrementBtn = new JButton("--");
}
private class IncrementListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
increment();
}
}
private class DecrementListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
decrement();
}
}
public void setupGUI()
{
final LayoutManager layout;
layout = new FlowLayout();
setLayout(layout);
setupListeners();
addComponents();
}
private void setupListeners()
{
incrementBtn.addActionListener(new IncrementListener());
decrementBtn.addActionListener(new DecrementListener());
}
private void addComponents()
{
add(incrementBtn);
add(decrementBtn);
}
private void increment()
{
value++;
System.out.println("value = " + value);
}
private void decrement()
{
value--;
System.out.println("value = " + value);
}
}