下面的 SSCCE 是一个扩展JPanel
. 是日历的JPanel
基本轮廓(为简单起见,我将其剥离了),它由JButton
组件 aJLabel
和 a组成JTable
。当我将此框架添加到窗口(即JDialog
)时,它会正常显示。但是,当我用它添加另一个组件时,它就会消失。为什么会发生这种情况,我怎样才能不发生这种情况?
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class CalendarPanel extends JPanel {
private static JDialog dialog = new JDialog();
public static void main(String[] args) {
setDialogProperties();
addComponentsToDialog();
dialog.setVisible(true);
}
private static void setDialogProperties() {
dialog.setModal(true);
dialog.setResizable(false);
dialog.setSize(new Dimension(330, 400));
dialog.setDefaultCloseOperation(2);
dialog.setLocationRelativeTo(null);
}
private static void addComponentsToDialog() {
CalendarPanel calendar = new CalendarPanel();
JPanel panel = new JPanel();
panel.add(calendar);
dialog.add(panel);
//dialog.add(new JLabel("Hello"));
}
private static final long serialVersionUID = 1L;
private JLabel lblMonth;
private JButton btnPrev, btnNext;
private JTable tblCalendar;
private DefaultTableModel mtblCalendar;
private JScrollPane stblCalendar;
private static GridBagLayout gridBag = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public CalendarPanel() {
super(gridBag);
createControls();
addControlsToPanel();
addHeaders();
setTableProperties();
}
private void createControls() {
lblMonth = new JLabel("January");
btnPrev = new JButton("<");
btnNext = new JButton(">");
mtblCalendar = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
tblCalendar = new JTable(mtblCalendar);
stblCalendar = new JScrollPane(tblCalendar);
stblCalendar.setPreferredSize(new Dimension(300, 247));
}
private void addControlsToPanel() {
GridBagLayout topGridBag = new GridBagLayout();
JPanel topPanel = new JPanel(topGridBag);
JPanel labelPanel = new JPanel();
labelPanel.add(lblMonth);
labelPanel.setPreferredSize(new Dimension(180, 20));
constraints.gridx = 1;
topGridBag.setConstraints(labelPanel, constraints);
constraints.gridx = 2;
topGridBag.setConstraints(btnNext, constraints);
topPanel.add(btnPrev);
topPanel.add(labelPanel);
topPanel.add(btnNext);
gridBag.setConstraints(topPanel, constraints);
constraints.gridy = 1;
gridBag.setConstraints(stblCalendar, constraints);
this.add(topPanel);
this.add(stblCalendar);
}
private void addHeaders() {
String[] headers = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
for (int i = 0; i < 7; i++) {
mtblCalendar.addColumn(headers[i]);
}
}
private void setTableProperties() {
tblCalendar.getTableHeader().setReorderingAllowed(false);
tblCalendar.setRowHeight(38);
mtblCalendar.setColumnCount(7);
mtblCalendar.setRowCount(6);
}
}