Kar*_*120 4 java swing jpanel jscrollpane
所以,我正在制作一种文本编辑器,我需要一个JScrollPane来进行垂直导航.但我无法让它发挥作用.
我已经阅读了前十页谷歌搜索结果的每一个怪异教程,我无法让它发挥作用.
可以说我有JFrame(大小1000x800).我想在其中放置一个JPanel(1000x2000),以便它与JFrame水平对齐.我想在JPanel的右侧贴上一个简单的滚动条,这样我就可以了解其余内容.
我缩小了尺寸,我已经将JPanel添加到JScrollBar,反之亦然,将其中一个添加到JFrame,两者都没有,但没有.
所以,在这一点上,我不介意几行完成的代码......
编辑:很好,这是代码......
mWindow = new JFrame(lang.getString("title"));
mWindow.setSize(1000, 800);
mWindow.setLocationRelativeTo(null);
mWindow.setResizable(false);
mWindow.setLayout(null);
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
workspace = new JPanel();
workspace.setBounds(0,0, 1000, 1203);
workspace.setBackground(Color.RED);
scroll = new JScrollPane(workspace, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds(0, 20, 600, 600);
//scroll.setLayout(null);
mWindow.getContentPane().add(scroll);
mWindow.repaint();
mWindow.validate();
Run Code Online (Sandbox Code Playgroud)
这显示了JPanel的一部分(600X600,(JScrollPane大小)),并显示滚动条,但不可滚动
所以,我做了这个非常快速的测试,它对我来说很好......
public class TestPane extends JPanel {
public TestPane() {
setBorder(new LineBorder(Color.RED));
// This is for demonstration purposes only
// One should always rely on the layout manager
// to define this value
// Thank kleopatra
setPreferredSize(new Dimension(1000, 1000));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics();
Dimension size = getPreferredSize();
String text = "Pref: " + size.width + "x" + size.height;
g.drawString(text, 0, fm.getAscent());
size = getSize();
text = "Size: " + size.width + "x" + size.height;
g.drawString(text, 0, fm.getHeight() + fm.getAscent());
}
}
Run Code Online (Sandbox Code Playgroud)
和测试框架
public class TestFrame {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JScrollPane scroll = new JScrollPane(new TestPane());
frame.add(scroll);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
产生这个:

在旁注中,我不知道为什么人们坚持使用空布局,他们只会造成更多麻烦,心痛然后他们是值得的.花点时间找一些简单的布局管理器.我讨厌VB有很多原因,但布局管理是我的首选,恕我直言