所以我有一个大小为500x500的JFrame,我使用g.drawLine(x,y)从(0,200)到(100000,200)绘制一条线。问题是我看不到整行,因为没有滚动条。有人可以请告诉我如何在这种特殊情况下使用滚动条来查看整个行(100000,200)。
答案 0 :(得分:3)
虽然我有usability concerns,但下面的示例说明了如Scrollable
中所讨论的如何实现How to Use Scroll Panes: Implementing a Scrolling-Savvy Client接口。请特别注意getPreferredScrollableViewportSize()
的结果与getPreferredSize()
的结果有何不同。单位和块增量也使分页更容易。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
/**
* @see https://stackoverflow.com/a/37460185/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(new DrawingPanel()));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class DrawingPanel extends JPanel implements Scrollable {
private static final int W = 100_000;
private static final int H = 400;
@Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
g.drawLine(0, getHeight() / 4, 0, 3 * getHeight() / 4);
g.drawLine(W - 1, getHeight() / 4, W - 1, 3 * getHeight() / 4);
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(640, H);
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
if (orientation == SwingConstants.HORIZONTAL) {
return W / 10;
} else {
return 10;
}
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
if (orientation == SwingConstants.HORIZONTAL) {
return W / 10;
} else {
return 10;
}
}
@Override
public boolean getScrollableTracksViewportWidth() {
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
答案 1 :(得分:1)
你能告诉我们代码吗?由于在没有看到它的情况下很难知道,但是我认为你应该创建一个并将它添加到你的JFrame中,如下所示:
JTextArea ta = new JTextArea(); // Example with a JTextArea,
depends on what you have, as I said, we need to see the code
JScrollPane sp = new JScrollPane(ta); //Add it to the component
needed, in your case the drawn line i guess
jFrame.add(sp); //Add it to the frame
在添加之前,你可以操纵尺寸:
sp.setColumnHeaderView(new JLabel("header column"));
sp.setRowHeaderView(new JLabel("header row"));
sp.setPreferredSize(new Dimension(500, 300));