我在JSplitPane中组合了两个JPanel。用户应该可以非常自由地移动分割窗格分隔符,但分隔符不应该太大(最好只有1px)。
有没有办法将dividerSize保持在1但是增加点击分隔符的hitbox?因此,单击鼠标时,每侧可能会有20px的分区?
答案 0 :(得分:2)
您可以将MouseListener添加到组件中,手动调整分隔符位置。
这是一个帮助您入门的基本示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DividerListener extends MouseAdapter
{
private JSplitPane splitPane;
private Component component;
private int pressedX;
private int dividerLocation;
public DividerListener(JSplitPane splitPane, Component component)
{
this.splitPane = splitPane;
this.component = component;
component.addMouseListener(this);
component.addMouseMotionListener(this);
}
@Override
public void mousePressed(MouseEvent e)
{
pressedX = SwingUtilities.convertPoint(component, e.getPoint(), splitPane).x;
dividerLocation = splitPane.getDividerLocation();
}
@Override
public void mouseDragged(MouseEvent e)
{
int draggedX = SwingUtilities.convertPoint(component, e.getPoint(), splitPane).x;
int deltaX = draggedX - pressedX;
splitPane.setDividerLocation(dividerLocation + deltaX);
}
private static void createAndShowGUI()
{
JSplitPane splitPane = new JSplitPane();
JLabel left = new JLabel("LEFT");
splitPane.setLeftComponent(left);
new DividerListener(splitPane, left);
JLabel right = new JLabel("RIGHT");
splitPane.setRightComponent(right);
new DividerListener(splitPane, right);
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( splitPane);
frame.setLocationByPlatform( true );
frame.setSize(200, 200);
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
您需要自定义逻辑以检查是否在左侧组件的右边缘或右侧组件的左侧边缘按下了鼠标。因此,您可能需要添加另一个参数,以便了解如何进行边界检查。
然后你需要设置一个标志,这样mouseDragged代码可以处理事件,也可以在你不靠近边缘时忽略它。