[英]How to NOT extend Swing components?
I've seen a number of posters argue that Swing components should not be extended, and that functionality should instead be added via composition. 我已经看到许多张贴者认为不应扩展Swing组件,而应该通过合成来添加功能。 So say I want to reusably create a JPanel
with absolute positioning (no layout manager) in which I can reposition components with the mouse: 可以这么说,我想可重复使用的JPanel
具有绝对定位(无布局管理器),可以用鼠标重新定位组件:
public class MoveableComponentPanel
{
private final JPanel m_panel;
public MoveableComponentPanel()
{
m_panel = new JPanel(null);
}
public void add(Component c)
{
m_panel.add(c);
c.addMouseListener(m_mover);
c.setSize(c.getPreferredSize());
}
private final MouseListener m_mover = new MouseListener()
{
private int m_startX, m_startY;
@Override
public void mousePressed(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
m_startX = e.getX();
m_startY = e.getY();
}
}
@Override
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
Component c = e.getComponent();
Point p = c.getLocation();
p.x += e.getX() - m_startX;
p.y += e.getY() - m_startY;
c.setLocation(p);
c.repaint();
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
};
}
Looks nice, but there's no way to add the panel to a container. 看起来不错,但是无法将面板添加到容器中。 Further headaches if I want to allow a calling class to interact with the panel, eg change size, background color, register event listeners, etc. Either I add a getPanel()
accessor, which breaks encapsulation, or write pass-through methods for the JPanel
methods/properties I want to expose (potentially many). 如果我想允许调用类与面板进行交互,则更令人头疼,例如,更改大小,背景色,注册事件侦听器等。我添加了一个getPanel()
访问器,该访问器将破坏封装,或者为getPanel()
编写传递方法。我要公开的JPanel
方法/属性(可能很多)。 Is there some other strategy I'm missing here? 我在这里还缺少其他一些策略吗? What is the accepted best practice? 什么是公认的最佳实践?
in which I can reposition components with the mouse: 在其中可以用鼠标重新放置组件:
Then you just add the MouseListener/MouseMotionListener
to the components that you want to drag. 然后,只需将MouseListener/MouseMotionListener
添加到要拖动的组件。 There is no need to extend any component to add that functionality. 无需扩展任何组件即可添加该功能。
Check out the Component Mover class for examples of ways to do basic dragging of a component as well as a more complex dragging solution. 请查看Component Mover类,以获取对组件进行基本拖动的方法示例以及更复杂的拖动解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.