Java - 透明的 JScrollPane [英] Java - Transparent JScrollPane
问题描述
我有一个 JTextArea,它位于 JScrollPane 之上.无论如何,我知道我可以使用 getViewPort()
方法来设置视口的不透明属性,但我似乎无法在任何地方找到任何迹象表明如何做到这一点.
I have a JTextArea and it's riding on top of a JScrollPane. Anyways, I know I can use the getViewPort()
method to set the opaque property of the viewport, but I cannot seem to find any sign of how to do that anywhere.
这是我目前所拥有的:
if (e.getKeyCode() == KeyEvent.VK_F)
{
if (sp.isVisible())
{
sp.setVisible(false);
}
else
{
sp.setVisible(true);
}
}
推荐答案
您与@Serplat 的对话表明您可能混淆了不透明度 和透明度.
Your colloquy with @Serplat suggests that you may be confounding opacity and transparency.
不透明度是用于优化绘图的 Swing 组件的布尔属性:
Opacity is a boolean property of Swing components used to optimize drawing:
true
:组件同意绘制包含在其矩形边界内的所有位.false
:组件不保证在其矩形范围内绘制所有位.
true
: The component agrees to paint all of the bits contained within its rectangular bounds.false
: The component makes no guarantees about painting all the bits within its rectangular bounds.
考虑区别可能有助于澄清您的问题或集中搜索更多信息.
Considering the distinction may help to clarify your question or focus your search for more information.
附录:基于@camickr 的示例,下面的示例显示了一个粘"到视口的蓝色方块,而灰色棋盘可以在上面滚动.
Addendum: Based on @camickr's example, the example below shows a blue square that "sticks" to the viewport, while the gray checkerboard may be scrolled over it.
import java.awt.*;
import javax.swing.*;
/** @see https://stackoverflow.com/questions/2846497 */
public class ScrollPanePaint extends JFrame {
private static final int TILE = 64;
public ScrollPanePaint() {
JViewport viewport = new MyViewport();
viewport.setView(new MyPanel());
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewport(viewport);
this.add(scrollPane);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private static class MyViewport extends JViewport {
public MyViewport() {
this.setOpaque(false);
this.setPreferredSize(new Dimension(6 * TILE, 6 * TILE));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(TILE, TILE, 3 * TILE, 3 * TILE);
}
}
private static class MyPanel extends JPanel {
public MyPanel() {
this.setOpaque(false);
this.setPreferredSize(new Dimension(9 * TILE, 9 * TILE));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.lightGray);
int w = this.getWidth() / TILE + 1;
int h = this.getHeight() / TILE + 1;
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if ((row + col) % 2 == 0) {
g.fillRect(col * TILE, row * TILE, TILE, TILE);
}
}
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ScrollPanePaint();
}
});
}
}
这篇关于Java - 透明的 JScrollPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!