java - 当我在框架上滚动时,如何让 JButton 移动?
问题描述
我有一个面板,在我的框架中可以滚动。我需要的是添加一个即使在我滚动时也保持固定在右下角的按钮。我是 Java Swing 的新手,所以我会很感激我能得到的所有帮助。
mainPanel = new SimulationPanel(); //class SimulationPanel extends JPanel
//making mainPanel scrollable
mainPanel.setPreferredSize(new Dimension(((int)(WIDTH*1.2)), HEIGHT));
JScrollPane scrollPane = new JScrollPane(mainPanel);
scrollPane.setViewportView(mainPanel);
// Settings for JFrame
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Warehouse Simulator");
frame.setContentPane(scrollPane);
frame.setSize(screenSize.width, screenSize.height);
frame.setResizable(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
解决方案
我会使用嵌套面板和外部面板BorderLayout
。然后一个FlowLayout
并对齐FlowLayout.RIGHT
和里面的按钮。
public class Example extends JFrame {
public Example() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextArea textArea = new JTextArea(10000, 0);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("button");
JPanel panelWithButton = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panelWithButton.add(button);
add(panelWithButton, BorderLayout.PAGE_END);
setLocationByPlatform(true);
pack();
setSize(600, 600);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Example().setVisible(true);
});
}
}
结果:
推荐阅读
- reactjs - 如何将 nextProps 传递给子组件
- python - Cloud SQL/NiFi:使用 python 和 NiFi 连接到云 sql 数据库
- python - 规范化特殊字符字体
- android - 通知自定义声音和振动不起作用?
- python - ValueError: 维度必须相等,但对于 'softmax_cross_entropy_with_logits_sg 是 2 和 3799
- html - 使用 HTML 从远程服务器播放视频
- json - $.each 只显示最后一个元素
- proxy - 调试在 package.json 中使用代理的 API 调用
- c - 使用 WinHTTP 传输不带标头的数据
- swift - 如何更改集合视图中的 UIbutton?