我正在创建一个可重用的控件,该控件将显示在 JFrame 中。该控件上将有滚动条。 (显示此控件的 JFrame 不会。)当我将此控件传递给 JFrame 进行显示时,控件滚动条永远不可见 - 即使我明确告诉控件使其可见。
当用户控件显示在 JFrame 中时,如何使滚动条在用户控件上可见?我错过了什么?
这是用户控件代码:
public class TestUserControl extends JPanel {
public TestUserControl(String greeting) {
setLayout(null);
JLabel lblTestLabel = new JLabel("This textbox will greet you.");
lblTestLabel.setBounds(113, 12, 192, 15);
lblTestLabel.setHorizontalAlignment(SwingConstants.LEFT);
add(lblTestLabel);
txtfTextField = new JTextField();
txtfTextField.setBounds(66, 37, 303, 81);
txtfTextField.setHorizontalAlignment(SwingConstants.LEFT);
add(txtfTextField);
txtfTextField.setColumns(10);
JButton btnOkButton = new JButton("OK");
btnOkButton.setBounds(184, 130, 54, 25);
add(btnOkButton);
btnOkButton.addActionListener(new OkButtonClickManager());
txtfTextField.setText(greeting);
JScrollPane scrollPane = new JScrollPane(this, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
scrollPane.setSize(400, 250);
scrollPane.setVisible(true);
}
}
这是 JFrame 代码:
public class Main {
public static void main(String [] args) {
TestUserControl testControl = new TestUserControl("Hello, Joe Smith.");
testControl.setVisible(true);
createGui(testControl, "Testing 1,2,3...");
}
private static void createGui(JPanel contents, String windowTitle) {
JFrame frame = new JFrame(windowTitle);
frame.setSize(400, 300);
frame.getContentPane().add(contents);
frame.addWindowListener(new WindowCloseManager());
frame.setVisible(true);
}
}
最佳答案
不要使用空布局!!!
当面板的首选大小
大于滚动 Pane 的大小时,滚动条将自动显示。布局管理器负责确定面板的首选大小
。由于您没有使用布局管理器,因此首选大小为零,因此滚动条不会出现。
阅读 Swing 教程中关于 Using Layout Managers 的部分了解更多信息和示例。
关于java - 在传递给 JFrame 的 java 控件上显示滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702555/