對於一些課程,我必須使用swing製作瀏覽器並實現多種功能,例如書籤功能。我想在這裏做的是有一個新窗口的類,顯示我的存儲書籤的下拉菜單。Java Swing - 如何使它關閉對話框不會關閉整個程序?
我在這裏使用了一個對話框,因爲我不希望窗口有一個最小化按鈕,但是,現在當關閉對話框時,整個程序關閉(實際的瀏覽器JFrame和程序中的其他所有內容)。
我已經將Dlg框的setDefaultCloseOperation設置爲DISPOSE_ON_CLOSE,但它似乎不起作用,我也試圖簡單地隱藏框。
這是我的代碼,想知道如果我做錯了什麼,或者它只是對話框的工作方式。乾杯
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SeeBookmarks extends JFrame {
private JComboBox<String> seeBookmarks = new JComboBox<String>(); //Drop down box for the bookmarks
public SeeBookmarks(BrowserPane screen, JButton seeBookmarksBtn) throws IOException {
Dlg bookmarksFrame = new Dlg(new JFrame(), "Bookmarks"); //Dialog box (Replacement JFrame)
try {
Scanner bookmarks = new Scanner(new FileReader("bookmarks.txt")); //Read the bookmarks file
while (bookmarks.hasNextLine()) { //While the file has another bookmark line
seeBookmarks.addItem(bookmarks.nextLine()); // add it to the drop down box
}
bookmarks.close(); //Close file reader
} catch (FileNotFoundException fnfe) { //In case file does not exist
FileWriter bookmarks = new FileWriter("bookmarks.txt"); //Create an empty bookmarks file
bookmarks.close(); //Close file writer
}
seeBookmarks.addItemListener(new ItemListener() { //Listener for the bookmarks drop down box
public void itemStateChanged(ItemEvent item) {
if (item.getStateChange() == ItemEvent.SELECTED) { //If an item is selected
screen.search(seeBookmarks.getSelectedItem().toString(), true); // Search selected item, add to history
bookmarksFrame.dispose(); // Close Dialog box
seeBookmarksBtn.setEnabled(true); // Re-enable seeBookmarksBtn
}
}
});
bookmarksFrame.setLayout(new BorderLayout()); //Set Dialog box to Border layout
bookmarksFrame.add(seeBookmarks, BorderLayout.CENTER); //Display drop down box in center for dialog box
bookmarksFrame.pack();
bookmarksFrame.setSize(300, 70);
bookmarksFrame.setLocationRelativeTo(null);
bookmarksFrame.setVisible(true);
bookmarksFrame.setDefaultCloseOperation(Dlg.DISPOSE_ON_CLOSE); //Meant to dispose the Dialog box
bookmarksFrame.setResizable(false);
bookmarksFrame.setAlwaysOnTop(true);
}
}
如果您需要更多幫助(以及所有將來的問題),請發佈一個適當的[[mcve]來展示問題。 – camickr
使用[DO_NOTHING_ON_CLOSE](https://docs.oracle.com/javase/7/docs/api/javax/swing/WindowConstants.html#DO_NOTHING_ON_CLOSE)。 –