我正在尝试在自己的swing应用程序中应用scrollPane。
但是,一旦改变窗口的大小,我就看不到滚动条。
我知道在滚动窗格中有9个组件:视口,2个标题,2个滚动条和4个角。但是当我将边框的颜色设置为红色(应用于视口)时,结果表明窗口仅仅是视口。(因为红色边框遍布窗口。)
这是我的代码。
<input type="checkbox" id="WowClasses_@(i)_ClassName" name="WowClasses[@i].ClassName" value="true" />
我想看到滚动条。有人请吗?谢谢!
答案 0 :(得分:0)
代码存在一些问题,此示例应解决其中的一些问题。
主要问题是由将布局管理器设置为null
引起的。当滚动窗格尝试获取所包含面板的大小时,它无法获得很好的答案,因此无法显示滚动条。
您可能已经注意到,实际上所有内容都在屏幕上,只是所有内容都被挤压了。通过设置大小,一切都可见。
通过注释setLayout(null)
,我可能破坏了您想要的视觉布局,因此请调整口味。不过最好使用其中的布局管理器。
对scrollPane.setViewportView(panel)
的调用是不必要的,因为在您调用new JScrollPane(panel)
时已经在构造函数中进行了处理。这可能是良性的,但有时这些冗余的调用有时会导致Swing变得怪异,因为Swing经常在后台注册侦听器等。
最后,我向setDefaultCloseOperation
添加了通话,以便在单击窗口关闭按钮时退出该应用。
我希望这会有所帮助!
package swingDemo;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
;
public class ScrollDemo1 extends JFrame {
public ScrollDemo1() {
JLabel label = new JLabel();
label.setBounds(50, 0, 1000, 100);
label.setText("Do you want to have a coffee together?");
JButton button = new JButton("Of course!");
button.setBounds(10, 60, 150, 50);
button.addActionListener(e -> label.setText("Well, let's go!"));
JButton button2 = new JButton("No,sorry.");
button2.setBounds(170, 60, 150, 50);
button2.addActionListener(e -> label.setText("Well, let's go!"));
JPanel panel = new JPanel();
panel.setBounds(10, 10, 10, 10);
panel.add(button2);
panel.add(button);
panel.add(label);
// This causes problems:
// panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.red));
scrollPane.setPreferredSize(new Dimension(20, 20));
add(scrollPane);
// This is redundent:
// scrollPane.setViewportView(panel);
setBounds(10, 10, 40, 60);
setTitle("Dating Robot");
// Some initial size (or "pack") is needed to make it big enough to see
setSize(500, 500);
// This makes the app exit cleanly when closing the frame
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(() -> {
ScrollDemo1 obj = new ScrollDemo1();
obj.setVisible(true);
});
}
}