你能帮我解决这个问题吗?我给BitTorrent的客户编写了布局,我不知道为什么JScroll不能在右边的JSplitPane中工作。这里有更多代码:https://github.com/niesuch/bittorrentclient/blob/nie_bittorrentclient/src/Bittorrent.java 提前谢谢。
/**
* Initialization information panel
*/
private void _initInfoPanel() {
JPanel formPanel = new JPanel();
formPanel.setBorder(BorderFactory.createTitledBorder("Informations"));
JPanel form = new JPanel(new GridLayout(0, 2));
int i = 0;
for (String formLabel : _formLabels) {
form.add(new JLabel(formLabel));
_textFields[i] = new JTextField(10);
form.add(_textFields[i++]);
}
formPanel.add(form);
_infoPanel.add(formPanel);
_infoPanel.add(new JScrollPane(formPanel), BorderLayout.CENTER);
}
我的最小示例程序:
import java.awt.BorderLayout;
import java.awt.GridLayout;
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.JSplitPane;
import javax.swing.JTextField;
public class Test extends JFrame
{
private final JPanel _downloadsPanel;
private final JPanel _buttonsPanel;
private final JPanel _infoPanel;
private final JTextField[] _textFields;
private final String[] _formLabels =
{
"Name: ", "Size: ", "% downloaded: ", "Status: ",
"Download: ", "Upload: ", "Time remaining: ", "Pieces: ",
"Peer data including IP addresses: ", "Speed download from them: ",
"Speed upload to them: ", "Port using: ", "Port client: "
};
private JButton _pauseButton;
public Test() {
setTitle("BitTorrent");
setSize(1024, 768);
_downloadsPanel = new JPanel();
_buttonsPanel = new JPanel();
_infoPanel = new JPanel();
_textFields = new JTextField[_formLabels.length];
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, _downloadsPanel, _infoPanel);
splitPane.setResizeWeight(0.7);
_initInfoPanel();
_initButtonsPanel();
getContentPane().setLayout(new BorderLayout());
getContentPane().add(_buttonsPanel, BorderLayout.SOUTH);
getContentPane().add(splitPane, BorderLayout.CENTER);
}
private void _initInfoPanel()
{
JPanel formPanel = new JPanel();
formPanel.setBorder(BorderFactory.createTitledBorder("Informations"));
JPanel form = new JPanel(new GridLayout(0, 2));
int i = 0;
for (String formLabel : _formLabels)
{
form.add(new JLabel(formLabel));
_textFields[i] = new JTextField(10);
form.add(_textFields[i++]);
}
formPanel.add(form);
_infoPanel.add(formPanel);
_infoPanel.add(new JScrollPane(formPanel), BorderLayout.CENTER);
}
private void _initButtonsPanel()
{
_pauseButton = new JButton("Pause");
_pauseButton.setEnabled(false);
_buttonsPanel.add(_pauseButton);
}
public static void main(String[] args)
{
Test bittorrent = new Test();
bittorrent.setVisible(true);
}
}
答案 0 :(得分:1)
这是一个简单的错误。您将_infoPanel视为使用BorderLayout,例如,
_infoPanel.add(new JScrollPane(formPanel), BorderLayout.CENTER); //!!
但它并没有使用JPanel的默认FlowLayout:
_infoPanel = new JPanel();
FlowLayout将在其preferredSizes中显示组件,并且不会尝试缩小或扩展它们,因此JScrollPane不会更改其大小。所以做出明显的改变:
_infoPanel = new JPanel(new BorderLayout());