- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我打开了两个 JFrame
。我让窗口 B 在窗口 A 的右侧生成,紧贴窗口 A 的右边缘。我想让它粘在 窗口 A 上并移动。我怎样才能让它做到这一点?
最佳答案
我制作了一个名为 DockingManager 的类,可让您停靠 Dialogs 和 Frames pseudo Winamp Style
它还可以让你制作不同的簇并设置磁场水平来选择哪个帧拖动其他帧)
package com.gsteren.docking;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
public class DockingManager {
public static enum DockingMode {
EAST, WEST, NORTH, SOUTH, NONE
}
int magneticDistance = 20;
public static Map<Component, DockingApplier> monitoredComponents = new HashMap<Component, DockingApplier>();
/**
* Para saber cual es el último Component movido por el usuario.
*/
private static DockingApplier focusedApplier;
public void registerComponent(Component component) {
this.registerComponent(component, 1);
}
public void registerComponent(Component component, int magneticLevel) {
DockingApplier applier = new DockingApplier(component, magneticLevel);
monitoredComponents.put(component, applier);
}
/**
* Indica el grupo completo de componentes pegados al que pertenece un
* componente.
*
* @author Guillermo
*
*/
protected class DockingApplierCluster {
Set<DockingApplier> appliers = new HashSet<DockingApplier>();
DockingApplier leader = null;
public DockingApplierCluster(DockingApplier applier) {
this.addToCluster(applier);
}
public DockingApplierCluster(Set<DockingApplier> appliers) {
for (DockingApplier applier : appliers) {
this.addToCluster(applier);
}
}
public void addToCluster(DockingApplier applier) {
appliers.add(applier);
applier.setCluster(this);
if (null == leader || applier.getMagneticLevel() < leader.getMagneticLevel()) {
this.setLeader(applier);
}
}
public int getSize() {
return getAppliers().size();
}
public void mergeCluster(DockingApplierCluster cluster) {
DockingApplierCluster bigCluster;
DockingApplierCluster smallCluster;
if (getSize() > cluster.getSize()) {
bigCluster = this;
smallCluster = cluster;
} else {
bigCluster = cluster;
smallCluster = this;
}
for (DockingApplier applier : smallCluster.getAppliers()) {
bigCluster.addToCluster(applier);
}
}
public Set<DockingApplier> getAppliers() {
return this.appliers;
}
/**
* @return the leader
*/
public DockingApplier getLeader() {
return leader;
}
/**
* @param leader
* the leader to set
*/
public void setLeader(DockingApplier leader) {
this.leader = leader;
}
public void remove(DockingApplier applier) {
if (this.getAppliers().size() == 1) {
/* No sacamos el único elemento */
return;
}
this.getAppliers().remove(applier);
if (this.leader == applier) {
this.leader = findLeader();
}
/* Pude haber dividido en varios clusters */
this.recalculateClustersAfterRemoval();
}
public void recalculateClustersAfterRemoval() {
Set<DockingApplier> myAppliersCopy = new HashSet<DockingManager.DockingApplier>(getAppliers());
Set<DockingApplier> visitedAppliers = new HashSet<DockingManager.DockingApplier>();
for (DockingApplier applier : myAppliersCopy) {
if (visitedAppliers.contains(applier)) {
continue;
}
Set<DockingApplier> newClusterComponents = findClusteredAppliers(applier);
if (newClusterComponents.size() == myAppliersCopy.size()) {
/* No se dividieron los clusters */
return;
}
visitedAppliers.addAll(newClusterComponents);
/* Creo un nuevo cluster, y le agrego los elementos */
new DockingApplierCluster(newClusterComponents);
}
}
/**
* Devuelve todos los DockingAppliers anexos entre si.
*
* @param anApplier
* @return
*/
public Set<DockingApplier> findClusteredAppliers(DockingApplier anApplier) {
return findClusteredAppliers(anApplier, new HashSet<DockingManager.DockingApplier>());
}
public Set<DockingApplier> findClusteredAppliers(DockingApplier anApplier, Set<DockingApplier> currentSet) {
currentSet.add(anApplier);
for (DockingApplier applier : anApplier.getAttachedComponents()) {
if (currentSet.contains(applier)) {
continue;
}
currentSet.add(applier);
currentSet.addAll(findClusteredAppliers(applier, currentSet));
}
return currentSet;
}
private DockingApplier findLeader() {
DockingApplier leaderCandidate = null;
for (DockingApplier applier : getAppliers()) {
if (leaderCandidate == null || applier.getMagneticLevel() < leaderCandidate.getMagneticLevel()) {
leaderCandidate = applier;
if (applier.getMagneticLevel() == 1) {
/* Encontramos óptimo */
break;
}
}
}
return leaderCandidate;
}
}
protected class DockingApplier implements ComponentListener, FocusListener {
private Component component = null;
private DockingApplierCluster cluster;
public DockingApplier(Component component, int magneticLevel) {
this.component = component;
this.cluster = new DockingApplierCluster(this);
this.magneticLevel = magneticLevel;
this.updateLastLocation();
/*
* Esto no es necesario ya que registerComponent es quien crea el
* applier
*/
if (!monitoredComponents.containsKey(component)) {
monitoredComponents.put(component, this);
}
this.component.addComponentListener(this);
this.component.addFocusListener(this);
componentFinishedMovingDetector.setRepeats(false);
}
public void setCluster(DockingApplierCluster cluster) {
this.cluster = cluster;
}
/**
* @return the cluster
*/
public DockingApplierCluster getCluster() {
return cluster;
}
boolean isClusterLeader() {
return getCluster().getLeader() == this;
}
/**
* @return the magneticLevel
*/
public Integer getMagneticLevel() {
return magneticLevel;
}
/**
* @param magneticLevel
* the magneticLevel to set
*/
public void setMagneticLevel(Integer magneticLevel) {
this.magneticLevel = magneticLevel;
}
/**
* @return the isDocking
*/
protected boolean isDocking() {
return isDocking;
}
/**
* @param isDocking
* the isDocking to set
*/
protected void setDocking(boolean isDocking) {
this.isDocking = isDocking;
}
/**
* @return the attachedComponents
*/
public Set<DockingApplier> getAttachedComponents() {
return attachedComponents;
}
int northY;
int southY;
int westX;
int eastX;
public void recalculateBorderCoordinates() {
Point compLoc = component.getLocation();
Dimension compDim = component.getSize();
northY = compLoc.y;
southY = northY + compDim.height;
westX = compLoc.x;
eastX = westX + compDim.width;
}
public DockingMode calculateWhereToDock(DockingApplier other, int magneticDistance) {
return calculateWhereToDock(this, other, magneticDistance);
}
/**
* Indica si me debería lockearse con other
*
* @param me
* @param other
* @return
*/
public DockingMode calculateWhereToDock(DockingApplier me, DockingApplier other, int magneticDistance) {
/* Talvez innecesario */
me.recalculateBorderCoordinates();
other.recalculateBorderCoordinates();
if (me.getAttachedComponents().contains(other)) {
/* Ya estan conectados */
return DockingMode.NONE;
}
int dockDistN = me.northY - other.southY;
int dockDistS = other.northY - me.southY;
int dockDistW = me.westX - other.eastX;
int dockDistE = other.westX - me.eastX;
if (dockDistN > 0 && magneticDistance > dockDistN && checkOverlappingEastWest(me, other)) {
return DockingMode.NORTH;
} else if (dockDistS > 0 && magneticDistance > dockDistS && checkOverlappingEastWest(me, other)) {
return DockingMode.SOUTH;
} else if (dockDistW > 0 && magneticDistance > dockDistW && checkOverlappingNorthSouth(me, other)) {
return DockingMode.WEST;
} else if (dockDistE > 0 && magneticDistance > dockDistE && checkOverlappingNorthSouth(me, other)) {
return DockingMode.EAST;
}
return DockingMode.NONE;
}
/**
* Checks whether components overlap in north/south direction.
*/
protected boolean checkOverlappingEastWest(DockingApplier me, DockingApplier other) {
return checkOverlappingEastWest_aux(me, other) || checkOverlappingEastWest_aux(other, me);
}
/**
* Checks whether components overlap in east/west direction.
*/
protected boolean checkOverlappingEastWest_aux(DockingApplier me, DockingApplier other) {
return me.westX >= other.westX && me.westX <= other.eastX || me.eastX >= other.westX
&& me.eastX <= other.eastX;
}
/**
* Checks whether components overlap in north/south direction.
*/
protected boolean checkOverlappingNorthSouth(DockingApplier me, DockingApplier other) {
return checkOverlappingNorthSouth_aux(me, other) || checkOverlappingNorthSouth_aux(other, me);
}
/**
* Checks whether components overlap in north/south direction.
*/
protected boolean checkOverlappingNorthSouth_aux(DockingApplier me, DockingApplier other) {
return me.northY >= other.northY && me.northY <= other.southY || me.southY >= other.northY
&& me.southY <= other.southY;
}
public Point calculateDockedLocation(DockingApplier other, DockingMode mode) {
return calculateDockedLocation(this, other, mode);
}
public Point calculateDockedLocation(DockingApplier me, DockingApplier other, DockingMode mode) {
final Point meLoc = me.getComponent().getLocation();
final Point otherLoc = other.getComponent().getLocation();
final Dimension otherDim = other.getComponent().getSize();
final Dimension meDim = me.getComponent().getSize();
/* Posiciones relativas a other */
switch (mode) {
case NORTH:
return new Point(meLoc.x, otherLoc.y + otherDim.height);
case SOUTH:
return new Point(meLoc.x, otherLoc.y - meDim.height);
case WEST:
return new Point(otherLoc.x + otherDim.width, meLoc.y);
case EAST:
return new Point(otherLoc.x - meDim.width, meLoc.y);
default:
return new Point(meLoc.x - otherLoc.x, meLoc.y);
}
}
/**
* Retrasa la accion a ejecutar en onComponentFinishedMoving hasta que
* pasan 10ms sin que se mueva el componente afectado.
*/
Timer componentFinishedMovingDetector = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onComponentFinishedMoving();
}
});
/**
* Resetea el componentFinishedMovingDetector, se debe llamar cada vez
* que se mueve o cambia el tamaño de la ventana.
*/
protected void startComponentFinishedMovingDetector() {
if (componentFinishedMovingDetector.isRunning()) {
componentFinishedMovingDetector.restart();
} else {
componentFinishedMovingDetector.start();
}
}
/* Mientras es menor, más probable es ser lider */
int magneticLevel = 1;
/* Indica si el componente esta en proceso de hacer dock */
boolean isDocking = false;
/* Para desconectarlos en resize */
Set<DockingApplier> attachedComponents = new HashSet<DockingApplier>();
/* Indica la posición del componente */
private Point lastLocation;
public boolean isDocked() {
return getCluster().getSize() > 1;
}
/**
* @return the component
*/
protected Component getComponent() {
return component;
}
public void componentResized(ComponentEvent e) {
startComponentFinishedMovingDetector();
this.recalculateBorderCoordinates();
this.unDock();
}
public void componentMoved(ComponentEvent e) {
this.recalculateBorderCoordinates();
/*
* Si el movimiento es consecuencia de hacer dock lo ignoro y marco
* como que el docking se completó
*/
if (this.isDocking()) {
this.setDocking(false);
return;
}
startComponentFinishedMovingDetector();
if (this != focusedApplier) {
return;
}
if (getCluster().getSize() == 1) {
return;
}
if (!this.isClusterLeader()) {
this.updateLastLocation();
this.unDock();
return;
}
positionAttachedComponents();
}
public void onComponentFinishedMoving() {
this.recalculateBorderCoordinates();
for (DockingApplier otherDockingApplier : getMonitoredComponents().values()) {
if (otherDockingApplier == this) {
continue;
}
DockingMode dockMode = calculateWhereToDock(this, otherDockingApplier);
if (!DockingMode.NONE.equals(dockMode)) {
System.out.println("shouldAttach");
this.dock(otherDockingApplier, dockMode);
this.updateLastLocation();
} else {
System.out.println("shouldNotAttach");
}
}
}
public void setLocation(int x, int y) {
this.setLocation(new Point(x, y));
}
public void setLocation(Point location) {
this.getComponent().removeComponentListener(this);
this.getComponent().setLocation(location);
this.setLastLocation(location);
this.getComponent().addComponentListener(this);
}
private void setLastLocation(Point location) {
this.lastLocation = location;
}
public Point getLocation() {
return this.getComponent().getLocation();
}
/**
* @return the lastLocation
*/
public Point getLastLocation() {
return lastLocation;
}
protected void dock(DockingApplier otherDockingApplier, DockingMode dockMode) {
this.setDocking(true);
Point dockInfo = this.calculateDockedLocation(otherDockingApplier, dockMode);
this.setLocation(dockInfo.x, dockInfo.y);
this.bindAppliers(otherDockingApplier);
/* Uno los clusters */
otherDockingApplier.getCluster().mergeCluster(this.getCluster());
}
public void bindAppliers(DockingApplier otherDockingApplier) {
this.getAttachedComponents().add(otherDockingApplier);
otherDockingApplier.getAttachedComponents().add(this);
}
public void unDock() {
if (this.getCluster().getSize() == 1) {
return;
}
/*
* Primero lo quito de sus vecinos, luego del cluster, el orden es
* importante para el calculo de clusters en caso de división.
*/
Set<DockingApplier> attachedComponentsCopy = new HashSet<DockingManager.DockingApplier>(
this.getAttachedComponents());
for (DockingApplier applier : attachedComponentsCopy) {
this.unbind(applier);
}
this.getCluster().remove(this);
this.setCluster(new DockingApplierCluster(this));
}
public void unbind(DockingApplier dockingApplier) {
this.getAttachedComponents().remove(dockingApplier);
dockingApplier.getAttachedComponents().remove(this);
}
private DockingMode calculateWhereToDock(DockingApplier component, DockingApplier otherDockingApplier) {
return this.calculateWhereToDock(otherDockingApplier, magneticDistance);
}
public void componentShown(ComponentEvent e) {
getMonitoredComponents().get(component).recalculateBorderCoordinates();
// positionAttachedComponents(e);
}
public void componentHidden(ComponentEvent e) {
getMonitoredComponents().get(component).recalculateBorderCoordinates();
// positionAttachedComponents(e);
}
private void positionAttachedComponents() {
/* El lider del cluster debe arrastrar a los otros componentes */
Point currentLocation = getComponent().getLocation();
int xDiff = currentLocation.x - getLastLocation().x;
int yDiff = currentLocation.y - getLastLocation().y;
if (xDiff == 0 && yDiff == 0) {
return;
}
this.updateLastLocation();
for (DockingApplier otherApplier : getCluster().getAppliers()) {
if (otherApplier == this) {
continue;
}
Point otherComponentLocation = otherApplier.getComponent().getLocation();
otherApplier.getComponent().removeComponentListener(otherApplier);
otherApplier.setDocking(true);
otherApplier.getComponent().setLocation(otherComponentLocation.x + xDiff,
otherComponentLocation.y + yDiff);
otherApplier.getComponent().addComponentListener(otherApplier);
}
}
public void updateLastLocation() {
this.setLastLocation(getComponent().getLocation());
}
@Override
public void focusGained(FocusEvent e) {
DockingManager.setFocusedApplier(this);
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
}
public DockingManager() {
}
public static void setFocusedApplier(DockingApplier applier) {
DockingManager.focusedApplier = applier;
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
JFrame frame1 = new JFrame("Frame 1");
JDialog dialog2 = new JDialog((JFrame) null, "Dialog 2");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(200, 50);
dialog2.setSize(200, 50);
frame1.setVisible(true);
dialog2.setVisible(true);
JDialog dialog1 = new JDialog((JFrame) null, "Dialog 1");
dialog1.setSize(200, 50);
dialog1.setVisible(true);
DockingManager manager = new DockingManager();
manager.registerComponent(frame1, 1);
manager.registerComponent(dialog2, 2);
manager.registerComponent(dialog1, 2);
}
/**
* @return the monitoredComponents
*/
protected static Map<Component, DockingApplier> getMonitoredComponents() {
return monitoredComponents;
}
}
关于java - 如何在 Swing 中将一个窗口停靠到另一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682334/
这个问题在这里已经有了答案: How to initialize var? (11 个答案) 关闭 8 年前。 我想给一个变量赋初值 null,并在下一个 if-else block 中赋值,但是编
我正在使用 TypeScript 3.8 编写 JS 和 TS 混合的代码。我写了以下行: export * as Easing from './easing'; 应该是 fair game在 Typ
我需要将 R 代码中的“/”更改为“\”。我有这样的事情: tmp <- paste(getwd(),"tmp.xls",sep="/") 所以我的 tmp是 c:/Study/tmp.xls 我希望
我有个问题。例如我有这个: id truth count 1 1 1 2 1 2 3 0 0 4 1 1 5 1 2 6 1
我正在尝试使用“IN”和“=”来查找一些 bean。我目前正在使用此代码: $ids = array(1,2,3,4); $user = 1; $things = R::find( 'thing'
是否可以在 Xcode 中部署到其他人的手机上?我没有 iPhone,但我想测试我在 friend 手机上制作的应用程序。在我支付 99 美元之前,我想确保这不会造成麻烦。 谢谢。 最佳答案 不会有任
我试图得到一个非常大的数字(超过 unsigned long long int )。所以我把它作为一个字符串,然后一个数字一个数字地转换成整数并使用它。 #include #include int
我在 Rust 中有 C 语言库的绑定(bind),但它们并不完整。 在 C 代码中,我定义了一个简化的宏,如下所示: #define MY_MACROS1(PTR) (((my_struct1
我正在努力解决这个问题。 http://jsfiddle.net/yhcqfy44/ 动画应该自动相对于 滚动到顶部每次出现滚动条时的高度。 我已经写了这个,但没有运气: var hheight =
我正在处理一个将数字作为字符串返回的 JSON API。例如 "12" ,但是,该字段值也可以是非数字的,例如:"-" . 我已将 JSON 数据解析为映射,我想将此字段提取为 elixir 中的整数
我正在尝试编写一个类,将.wav文件转换为.aiff文件作为项目的一部分。 我遇到了几个库Alvas.Audio(http://alvas.net/alvas.audio,overview.aspx)
我想在 Lucene 中将像“New York”这样的“复合词”索引为单个术语,而不是像“new”、“york”那样。这样,如果有人搜索“new place”,则包含“new york”的文档将不会匹
我希望这个解释能让我更好地了解使用宏的优点。 最佳答案 在函数中,所有参数在调用之前都会被评估。 这意味着 or 作为函数不能是惰性的,而宏可以将 or 重写为 if 语句,该语句仅在以下情况下计算分
我有一些看起来像这样的 XML foo ]]> (注意 > 登录 "> foo")和 XSLT 样式表 当我运行xsltproc stylesheet.xs
当我尝试将 Any 转换为 List 时,如下面的示例所示,我得到“Unchecked cast: Any!”到列表'警告。有没有解决此类问题的方法? val x: List = objectOfTy
我正在使用 Python 开发一个简单的爬虫。目的是创建一个 sitemap.xml。(你可以在这里找到真正的 alpha 版本:http://code.google.com/p/sitemappy/
我想知道在 VBScript 中是否可以在多行中中断 If 语句。喜欢: If (UCase(Trim(objSheet.Cells(i, a).Value)) = "YES") Or _ (UCas
for (String item : someList) { System.out.println(item); } 使用“do while”是否等效? 谢谢。 最佳答案 如果列表为空,f
这个问题已经有答案了: 已关闭10 年前。 Possible Duplicate: Split string with delimiters in C 在 C 中将“,”分隔的列表拆分为数组的最佳方法
我有一个如下所示的字符数组: [0, 10, 20, 30, 670] 如何将此字符串转换为整数数组? 这是我的数组 int i=0; size_t dim = 1; char* array = (c
我是一名优秀的程序员,十分优秀!