当我调整整个界面的大小时,Java Glass 窗格会自动调整大小,但我想让它固定在特定位置,它看起来像这样:
当我调整它的大小时,而不是四处走动。
谢谢
当我调整整个界面的大小时,Java Glass 窗格会自动调整大小,但我想让它固定在特定位置,它看起来像这样:
当我调整它的大小时,而不是四处走动。
谢谢
有多种方法可以实现这一点,但基本要求将需要对您的玻璃窗格内容试图坚持的组件进行某种引用。这意味着当组件更新并需要布局时,您可以找到粘性组件的位置并更新内容在玻璃窗格上的位置。
请记住,玻璃窗格是一个容器,它占据了一个窗口的全部内容,它是您需要更新的玻璃窗格中包含的内容
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StickyGlassPaneExample {
public static void main(String[] args) {
new StickyGlassPaneExample();
}
public StickyGlassPaneExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
StickyGlassPane stickyGlassPane = new StickyGlassPane();
TestPane testPane = new TestPane(stickyGlassPane);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(testPane);
frame.setSize(600, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setGlassPane(stickyGlassPane);
stickyGlassPane.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<JTextField> fields;
public TestPane(StickyGlassPane stickyGlassPane) {
fields = new ArrayList<JTextField>(100);
for (int index = 0; index < 100; index++) {
JTextField field = new JTextField(10);
fields.add(field);
add(field);
}
int fieldIndex = (int)(Math.random() * (fields.size() - 1));
JTextField sticky = fields.get(fieldIndex);
sticky.setText("Sticky");
stickyGlassPane.setStickyComponent(sticky);
}
}
public class StickyGlassPane extends JPanel {
private Component component;
private JPanel overlay;
public StickyGlassPane() {
setOpaque(false);
overlay = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, getWidth(), getHeight());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fillRect(0, 0, getWidth(), getHeight());
}
};
overlay.setOpaque(false);
add(overlay);
}
@Override
public void doLayout() {
if (component != null) {
Point p = component.getLocation();
SwingUtilities.convertPoint(component, p, this);
overlay.setLocation(p);
overlay.setSize(component.getSize());
} else {
overlay.setBounds(0, 0, 0, 0);
}
}
public void setStickyComponent(Component component) {
this.component = component;
revalidate();
}
}
}