【发布时间】:2017-04-10 18:44:05
【问题描述】:
对于某些课程作业,我必须使用 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);
}
}
【问题讨论】:
-
如果您需要更多帮助(以及未来的所有问题),请发布一个适当的 [minimal reproducible example 来证明问题。