JFrame просачивается через JInternalFrame

Пропускание JFrame через JInternalFrame

Я создаю настольное приложение и не могу понять, почему JFrame просачивается через JInternalFrame (см. рис.). Я попытался включить соответствующий код ниже, поэтому, пожалуйста, не обращайте внимания на отсутствующий {}, он работает без ошибок в реальном приложении.

public class MainJFrame extends JFrame {

private static final long serialVersionUID = 2377310559170663631L;
Container cPane;
JDesktopPane desktopPane = new JDesktopPane();
JPanel deskPanel;
JButton jButtonCreateWLog, jButtonCreateCLog;



public static void main(String args[]) {
    MainJFrame w = new MainJFrame();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int maxX = screenSize.width - 100;
    int maxY = screenSize.height - 200;
    w.setPreferredSize(new Dimension(maxX, maxY));
    w.setSize(maxX, maxY);
    w.setTitle("Estes Fitness Help");
    w.setVisible(true);
}

public MainJFrame() {
    super("Estes Fitness Help");
    getContentPane().add(desktopPane);
    cPane = getContentPane();
    cPane.setLayout(null);
    initiateComponents();
    initiateMenuBar();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initiateComponents(){

    //Set size to match desktop size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int maxX = screenSize.width - 100;
    int maxY = screenSize.height - 200;

    //Create panel inside desktop
    deskPanel = new JPanel();
    deskPanel.setName("Weight Log Entry");
    deskPanel.setLayout(null);
    deskPanel.setBackground(new Color(200, 50, 50));

    //button for creating a weight log
    jButtonCreateWLog = new JButton();
    jButtonCreateWLog.setText("Create Weight Log");
    jButtonCreateWLog.setBounds(80, 120, 150, 25);
    jButtonCreateWLog.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        jButtonCreateWLogActionPerformed(e);
      }
    });

    //button for creating a cardio log
    jButtonCreateCLog = new JButton();
    jButtonCreateCLog.setText("Create Cardio Log");
    jButtonCreateCLog.setBounds(250, 120, 150, 25);
    jButtonCreateCLog.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        jButtonCreateCLogActionPerformed(e);
      }
    });

    //add components to deskPanel
    deskPanel.add(jButtonCreateWLog);
    deskPanel.add(jButtonCreateCLog);
    deskPanel.setSize(maxX, maxY);
    cPane.add(deskPanel);

    pack();
    setVisible(true);

}

private void jButtonCreateWLogActionPerformed(ActionEvent e){
    MainJFrameController desktopPaneC = new MainJFrameController(this);
    desktopPaneC.actionPerformed(e);

}

Это MainJFrameController:

public class MainJFrameController implements ActionListener{

private MainJFrame desktopFrame;

public MainJFrameController(){

}

public MainJFrameController(MainJFrame desktopFrame){
    this.desktopFrame = desktopFrame;   
    desktopFrame.getCreateWLogButton().addActionListener(this);
    desktopFrame.getCreateCLogButton().addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
    String action = e.getActionCommand();
    if (action.equalsIgnoreCase("Create Weight Log")){
        getCreateWLogButton_actionPerformed(e);
    } else if (action.equalsIgnoreCase("Create Cardio Log")){
        getCreateCLogButton_actionPerformed(e);
    }
}

private void getCreateWLogButton_actionPerformed(ActionEvent e) {
    StoreWeightLogJFrame SWLJFrame = new StoreWeightLogJFrame();
    SWLJFrame.pack();
    SWLJFrame.setVisible(true);
    desktopFrame.add(SWLJFrame);

}
}

Это WeightLog JInternalFrame

public class StoreWeightLogJFrame extends JInternalFrame{

private static final long serialVersionUID = 7750452209025354283L;

JPanel jPanel1;
JLabel jLabelSets, jLabelReps, jLabelWeight;
JTextField jTextFieldSets, jTextFieldReps, jTextFieldWeight;
JButton jButtonSaveWLog;

public StoreWeightLogJFrame() {
    super("Store Weight Log");
    initiateComponents();
    this.add(jPanel1);
    this.setBounds(0, 0, 505, 505);
    this.setVisible(true);
    this.pack();
    this.setClosable(true);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    System.out.println("StoreWeightLogJFrame initialized");
}
private void initiateComponents(){

    jPanel1 = new JPanel();
    jLabelSets = new JLabel();
    jTextFieldSets = new JTextField();
    jLabelReps = new JLabel();
    jTextFieldReps = new JTextField();
    jLabelWeight = new JLabel();
    jTextFieldWeight = new JTextField();
    jButtonSaveWLog = new JButton();
    jPanel1.setName("Weight Log Entry");
    jPanel1.setLayout(null);
    jPanel1.setBackground(new Color(255, 50, 50));

    jLabelSets.setText("Sets: ");
    jLabelSets.setBounds(25, 25, 100, 50);
    jTextFieldSets.setText("3");
    jTextFieldSets.setBounds(80, 40, 25, 25);


    jLabelReps.setText("Reps: ");
    jLabelReps.setBounds(25, 60, 100, 50);
    jTextFieldReps.setText("10");
    jTextFieldReps.setBounds(80, 75, 25, 25);

    jLabelWeight.setText("Weight: ");
    jLabelWeight.setBounds(25, 110, 50, 25);
    jTextFieldWeight.setText("225");
    jTextFieldWeight.setBounds(80, 110, 30, 25);

    jButtonSaveWLog.setText("Save Log");
    jButtonSaveWLog.setBounds(40, 150, 100, 25);
    jButtonSaveWLog.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
        jButtonSaveWLogActionPerformed(e);
    }
    });

    jPanel1.add(jLabelSets);
    jPanel1.add(jTextFieldSets);
    jPanel1.add(jLabelReps);
    jPanel1.add(jTextFieldReps);
    jPanel1.add(jLabelWeight);
    jPanel1.add(jTextFieldWeight);
    jPanel1.add(jButtonSaveWLog);
    jPanel1.setBounds(5, 5, 500, 550);

}

person Will Estes    schedule 15.03.2017    source источник
comment
Похоже, у вас проблемы с z-упорядочением   -  person MadProgrammer    schedule 16.03.2017


Ответы (1)


getContentPane().add(desktopPane);
cPane = getContentPane();

Сначала вы добавляете панель рабочего стола к панели содержимого.

cPane.add(deskPanel);

Позже вы добавите deskPanel в панель содержимого.

Поскольку вы используете нулевой макет, вы добавили два компонента в один и тот же контейнер, и кнопка будет отображаться при наведении на нее указателя мыши.

Не знаю точно, что вы пытаетесь сделать, но я думаю, вам следует:

  1. не использовать нулевой макет. Swing был разработан для использования с менеджером компоновки.
  2. отображать «панель кнопок» и «панель рабочего стола» на панели содержимого с помощью соответствующего менеджера компоновки (BorderLayout) для управления расположением каждого компонента.

Итак, основная логика примерно такая:

JDesktopPane desktop = new JDesktopPane();
frame.add(desktop, BorderLayout.CENTER);

Теперь, если вы хотите, чтобы ваши «кнопки» отображались на рамке, вы можете создать другую панель для своих кнопок:

JPanel buttonPanel = new JPanel();
buttonPanel.add(theFirstButton);
buttonPanel.add(theSecondButton);
frame.add(buttonPanel, BorderLayout.PAGE_START);

Теперь фрейм будет содержать панель с кнопками в верхней части фрейма, а панель рабочего стола будет располагаться под этой панелью.

Прочтите раздел руководства по Swing, посвященный менеджерам компоновки. Информация и рабочие примеры.

person camickr    schedule 16.03.2017
comment
Я проверю вашу ссылку, как только вернусь из путешествия, и посмотрю, смогу ли я заставить ее работать. - person Will Estes; 18.03.2017