我想要这样的实现。
JscrollPane的面板分为两列。
第一栏有jtextarea。
第二列应该有一个带有Ok文本的jbutton。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestScrollPane extends JFrame {
JPanel newScrollPanel;
JPanel leftPanel;
JScrollPane scrollPane;
JEditorPane editorPane;
JButton button;
public TestScrollPane() {
leftPanel = new JPanel();
newScrollPanel = new JPanel();
editorPane = new JEditorPane();
scrollPane = new JScrollPane(editorPane);
button = new JButton("ok");
leftPanel.setBackground(Color.WHITE);
leftPanel.add(button);
editorPane.setEditable(false);
scrollPane.setPreferredSize(new Dimension(250, 140));
scrollPane.setMinimumSize(new Dimension(10, 10));
String text = "";
for(int i=0;i<50;i++){
text = text + "line " + i + "\n";
}
editorPane.setText(text);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
newScrollPanel.setLayout(new BoxLayout(newScrollPanel, BoxLayout.X_AXIS));
newScrollPanel.add(editorPane);
newScrollPanel.add(leftPanel);
scrollPane.getViewport().add(newScrollPanel);
addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent evt) { }
@Override
public void componentShown(ComponentEvent evt) {
changePane();
}
});
this.add(scrollPane);
setFrame();
}
private void changePane() {
leftPanel.setLayout(null);
Insets insets = leftPanel.getInsets();
Dimension size = button.getPreferredSize();
int buttonY = (int) (insets.top + scrollPane.getHeight() - size.getHeight());
button.setPreferredSize(size);
leftPanel.setPreferredSize(new Dimension(((int) size.getWidth()), editorPane.getHeight()));
button.setBounds(0, buttonY, size.width, size.height);
}
void setFrame(){
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TestScrollPane testScrollPane = new TestScrollPane();
}
});
}
}
我有两个问题。
在我班上,确定按钮没有放在正确的位置。当滚动条移动器位于顶角时,确定按钮应位于可见区域的右下角。确定按钮应完全可见。在我的代码中只显示按钮的一部分。确定Y坐标有什么问题吗?
int buttonY = (int) (insets.top + scrollPane.getHeight() - size.getHeight());
即使滚动移动,ok按钮也不应随滚动条移动。这有可能实现吗?