【发布时间】:2017-05-06 01:27:38
【问题描述】:
我在这个论坛上阅读了一些已回答的问题(例如this one),强烈建议避免使用 setXXXSize() 方法来调整 Swing 应用程序中的组件大小。
所以,谈到我的问题,我想知道如何最好地调整 JScrollPane 的大小,以避免其父面板在没有任何控制的情况下增加其大小。
在写一些代码之前,我想描述一下真实情况,因为我将发布一个“玩具示例”。
在我的 JFrame 中,我目前正在为我的内容窗格使用边框布局。在 BorderLayout.CENTER 有一个 JPanel,我可以在其中进行一些自定义绘画。 在 BorderLayout.EAST 有一个 JPanel(比如 eastPanel),其中包含另一个面板内的一些组件(此面板将添加到 BorderLayout.NORTH 的eastPanel),以及一个包含 JTable 的 JScrollPane(添加到 BorderLayout.CENTER 的eastPanel)。该表将有很多行。 由于我希望eastPanel 的高度与centerPanel 的高度相同,因此我需要一些方法来避免JScrollPane 增加其大小以尝试显示尽可能多的行。
目前,除了在包含滚动窗格的eastPanel 上调用 setPreferredSize 之外,我无法找到其他解决方案,但我不得不承认我讨厌这种解决方案。
示例代码
在这个代码示例中,我在eastPanel 的北部和JScrollPane 内部添加了一些随机标签,因为我的目的是发布一个简短的代码示例。 但是,情况与我上面描述的情况非常相似。 如果不使用这行“可怕”的代码,我无法解决我的问题:
eastPanel.setPreferredSize(new Dimension(eastPanel.getPreferredSize().width, centerPanel.getPreferredSize().height));
对于这样的简单情况,我想避免使用更复杂的布局。我错过了什么吗?另外,设置空边框是一种可接受的方式来设置我将在其中进行一些自定义绘画的面板大小吗?
代码:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Test
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestFrame().setVisible(true);
}
catch(Exception exception) {
JOptionPane.showMessageDialog(null, "Fatal error while initialiing application", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
class TestFrame extends JFrame
{
public TestFrame() {
super("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pane = new JPanel(new BorderLayout(20, 0));
pane.setBorder(new EmptyBorder(20, 20, 20, 20));
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(new EmptyBorder(400, 400, 0, 0));
// centerPanel.setPreferredSize(new Dimension(400, 400));
JPanel eastPanel = new JPanel(new BorderLayout(0, 20));
JPanel labelsContainer = new JPanel(new GridLayout(0, 1));
for(int i=0;i<7;i++) labelsContainer.add(new JLabel(String.valueOf(i)));
eastPanel.add(labelsContainer, BorderLayout.NORTH);
JPanel moreLabelsContainer = new JPanel(new GridLayout(0, 1));
for(int i=7;i<70;i++) moreLabelsContainer.add(new JLabel(String.valueOf(i)));
JScrollPane scroll = new JScrollPane(moreLabelsContainer, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
eastPanel.add(scroll, BorderLayout.CENTER);
eastPanel.setPreferredSize(new Dimension(eastPanel.getPreferredSize().width, centerPanel.getPreferredSize().height));
pane.add(centerPanel, BorderLayout.CENTER);
pane.add(eastPanel, BorderLayout.EAST);
setContentPane(pane);
pack();
setLocationRelativeTo(null);
}
}
感谢您的帮助!
【问题讨论】:
标签: java swing resize jscrollpane