我想在 Swing GUI 的 JScrollPane 中添加一个非滚动元素、始终可见的元素(“固定”元素)。以这个示例代码为例:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JEditorPane editorPane = new JEditorPane();
editorPane.setText("""
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
""");
JScrollPane scroll = new JScrollPane(editorPane);
editorPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
editorPane.add(new JLabel("this shouldn't scroll!"));
frame.getContentPane().add(scroll);
frame.setSize(600, 400);
frame.setVisible(true);
}
}
我需要一种方法:
我已经能够使用 Swing 的玻璃面板来实现这一点,但这对我来说意味着更多的手动更新,并且无论 Swing 面板如何调整大小,位置始终相同。
感谢您的帮助!
我建议使用“列标题”(JScrollPane)。在下面的代码中,“列标题”是一个
JPanel
和 BoxLayout。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main implements Runnable {
@Override
public void run() {
JFrame frame = new JFrame("Pinned");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea txtAr = new JTextArea("""
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
d
""");
txtAr.setColumns(40);
JScrollPane scrollPane = new JScrollPane(txtAr);
JPanel hdr = new JPanel();
hdr.setBackground(txtAr.getBackground());
BoxLayout layout = new BoxLayout(hdr, BoxLayout.LINE_AXIS);
hdr.setLayout(layout);
JLabel first = new JLabel("d");
first.setFont(txtAr.getFont());
hdr.add(first);
hdr.add(Box.createHorizontalGlue());
JLabel last = new JLabel("this shouldn't scroll");
last.setFont(txtAr.getFont());
hdr.add(last);
scrollPane.setColumnHeaderView(hdr);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new GUI());
}
}
这是屏幕截图: