我制作了一个简单的表格,如下所示:
如何使“显示详细信息”按钮显示另一个面板和表单,如下所示:
再次单击该按钮时,它会隐藏控件和面板。
答案 0 :(得分:1)
显示/隐藏详细信息面板后,必须调用pack()
来调整框架大小。并setLocationRelativeTo()
分别正确定位。
这是一个例子
<强> Main.java 强>
import javax.swing.*;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame("Test Frame").setVisible(true));
}
}
<强> MainFrame.java 强>
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame {
private DetailsPanel detailsPanel;
public MainFrame(String title) throws HeadlessException {
super(title);
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
detailsPanel = new DetailsPanel();
add(new MainPanel(this), BorderLayout.CENTER);
add(detailsPanel, BorderLayout.LINE_END);
pack();
setLocationRelativeTo(null);
}
public void showDetails(boolean show) {
detailsPanel.setVisible(show);
pack();
setLocationRelativeTo(null);
}
}
<强> MainPanel.java 强>
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class MainPanel extends JPanel {
private MainFrame owner;
private JButton showDetailsButton;
private boolean details = false;
public MainPanel(MainFrame owner) {
super();
this.owner = owner;
createGUI();
}
private void createGUI() {
showDetailsButton = new JButton("Details >>>");
showDetailsButton.addActionListener(this::showDetais);
JPanel contentPanel = new JPanel();
contentPanel.setPreferredSize(new Dimension(400, 400));
contentPanel.setBackground(Color.CYAN);
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonsPanel.add(showDetailsButton);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 400));
setMinimumSize(getPreferredSize());
add(contentPanel, BorderLayout.CENTER);
add(buttonsPanel, BorderLayout.PAGE_END);
}
private void showDetais(ActionEvent event) {
showDetailsButton.setText(details ? "Details >>>" : "<<< Details");
details = !details;
owner.showDetails(details);
}
}
和 DetailsPanel.java
import javax.swing.*;
import java.awt.*;
public class DetailsPanel extends JPanel {
public DetailsPanel() {
super();
createGUI();
}
private void createGUI() {
setBackground(Color.BLUE);
setPreferredSize(new Dimension(200, 800));
setVisible(false);
}
}
答案 1 :(得分:1)
让我们假设从Filter
向下到Show Details
的控件位于单个(永久可见 - PV)面板中,并且要显示/隐藏的控件位于第二个(隐藏或显示 - HS hideOrShowPanel
)小组。将PV面板放在CENTER
的{{1}}和BorderLayout
中的HS面板中。
按钮切换,请拨打..
LINE_END
private void changePanelVisibility(Boolean visible) {
hideOrShowPanel.setVisible(visible);
topLevelContainer.pack(); // revalidate layout and size the GUI to fit the controls
}
可能是topLevelContainer
,但此GUI似乎更适合在JFrame
中显示。特别是因为这在固定大小(非用户可调整大小的)顶级容器中看起来最好,默认情况下对话框是。
答案 2 :(得分:0)
它可能取决于您使用的LayoutManager。但一般情况下,将详细信息面板始终添加到对话框中,但在开始时将其设置为不可见。按“显示详细信息”按钮时,切换“详细信息”面板的可见性并调整对话框大小以适应所需的额外空间。