【发布时间】:2017-05-12 14:34:49
【问题描述】:
我正在尝试使用 Java Swing 为小型电话簿应用程序编写布局。我遇到了无法修复的尺寸问题。我希望过滤器(显示在搜索结果下)足够宽以在搜索短语很短时显示整个标题。这是它的样子:
如您所见,名称已缩短。姓氏带有较长的文本,并按我的意愿显示。
过滤器类:
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import java.awt.*;
public class Filter
{
private JLabel label;
private JPanel filterPane;
Filter(String name)
{
// Filter text
label = new JLabel();
label.setForeground(new Color(0xAA0000));
// Closing button
JButton closeButton = new JButton("X");
closeButton.setFont(new Font("Dialog", Font.BOLD, 20));
closeButton.setMargin(new Insets(0, 0, 0, 0));
filterPane = new JPanel();
filterPane.setLayout(new BoxLayout(filterPane, BoxLayout.X_AXIS));
// Frame with title + 50px padding on the right side for the next filter
filterPane.setBorder(new CompoundBorder(
BorderFactory.createEmptyBorder(0, 0, 0, 50),
BorderFactory.createTitledBorder(name)));
filterPane.add(closeButton);
filterPane.add(Box.createRigidArea(new Dimension(5, 0)));
filterPane.add(label);
filterPane.setVisible(false);
}
public void setValue(String value) {
if (value == null || value.isEmpty())
filterPane.setVisible(false);
else
{
this.label.setText(value);
filterPane.setVisible(true);
}
}
public JPanel getFilterPane() {
return filterPane;
}
}
主类:
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
public class TestWindow
{
private static void init()
{
JFrame frame = new JFrame("Stackoverflow test window");
frame.setSize(new Dimension(480, 320));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// Main panel - 20 px padding from each side
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// Create panel for filters
JPanel filterPane = new JPanel();
filterPane.setLayout(new BoxLayout(filterPane, BoxLayout.X_AXIS));
filterPane.setPreferredSize(new Dimension(0, 60));
// Add sample filters
Filter filter = new Filter("name");
filter.setValue("i");
filter.getFilterPane().setAlignmentY(Component.BOTTOM_ALIGNMENT);
filterPane.add(filter.getFilterPane());
filter = new Filter("surname");
filter.setValue("loooooong text");
filter.getFilterPane().setAlignmentY(Component.BOTTOM_ALIGNMENT);
filterPane.add(filter.getFilterPane());
// Add everything to main panel
pane.add(new JTextArea("Nothing fancy here, just to fill out space"), BorderLayout.CENTER);
pane.add(filterPane, BorderLayout.SOUTH);
frame.setContentPane(pane);
frame.setVisible(true);
}
public static void main (String [] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeLater(TestWindow::init);
}
}
我在 Filter 构造函数中为label 和filterPane 尝试了setMinimumSize 和setPreferredSize,但它没有帮助。你能帮帮我吗?
【问题讨论】:
-
如何将窗格添加到父窗口?你用的是什么布局?请edit问题并添加适用的代码。
-
谢谢,你是对的。完成。
-
覆盖类的
getXxxSize,而不是设置大小。发布minimal reproducible example。 -
是的,filterPane 和 label 都适用。没用。 @user1803551 你的意思是应用这些规则重写我的问题?