我有一个公共类AppHelper用于显示一些使用jframe的帮助内容。在同一个JFrame上有一个退出按钮,点击该按钮可以放置jframe。 ActionListener被实现为上述类的静态嵌套类。使用静态方法在嵌套静态类中处理后重建JFrame
帮助窗口的所有组件都在外部类中定义,并且它们都是私有的和静态的。显示帮助窗口的方法也是静态的。
下面是一些代码,我已经实现:
public class AppHelper {
// helper frame
private static JFrame appHelperFrame;
// helper panel
private static JPanel appHelperPanel;
// helper pane
private static JEditorPane appHelperPane;
// exit helper button
private static JButton exitAppHelperButton;
// constraints
private static GridBagConstraints appHelperPaneCons, exitAppHelperButtonCons;
/**
set layout
*/
private static void setLayoutConstraints() {
// defines layout
}
/**
* initialize the helper elements
* @param void
* @return void
*/
public static void initializeElements() {
// initialize constraints
setLayoutConstraints();
// handler
AppHelper.AppHelperHandler appHelpHandler = new AppHelper.AppHelperHandler();
appHelperFrame = new JFrame("App Help");
appHelperPanel = new JPanel();
appHelperPanel.setLayout(new GridBagLayout());
appHelperPane = new JEditorPane();
exitAppHelperButton = new JButton("Exit");
exitAppHelperButton.addActionListener(appHelpHandler);
java.net.URL helpURL = null;
try {
helpURL = new File("AppHelp.html").toURI().toURL();
} catch (MalformedURLException ex) {
Logger.getLogger(AppHelper.class.getName()).log(Level.SEVERE, null, ex);
}
try {
appHelperPane.setPage(helpURL);
} catch (IOException ex) {
Logger.getLogger(AppHelper.class.getName()).log(Level.SEVERE, null, ex);
}
appHelperPane.setEditable(false);
appHelperFrame.add(appHelperPanel);
appHelperPanel.add(appHelperPane, appHelperPaneCons);
appHelperPanel.add(exitAppHelperButton, exitAppHelperButtonCons);
appHelperFrame.setSize(350, 400);
appHelperFrame.setResizable(false);
appHelperFrame.setVisible(true);
}
/**
* TODO
*/
public static void showAboutApp() {
//throw new UnsupportedOperationException("Not yet implemented");
}
/**
*
* Acts as the handler for the help window components
* Implement actionListener interface.
*/
private static class AppHelperHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == exitAppHelperButton) {
appHelperFrame.dispose();
}
}
}
}
处置JFrame中,而不是将它设置无形的原因是,我不想当这个JFrame中不使用此JFrame中消耗内存。
现在的问题是我第一次点击帮助按钮(在其他一些窗口)显示JFrame。现在,当我单击此帮助窗口上的退出按钮时,JFrame由处理程序处理。下次我再次点击帮助按钮,帮助窗口不显示。我想知道我的代码中是否有任何错误,或者我需要做其他事情。
我们需要在按下帮助按钮时执行的代码。 –
*“或者我需要做其他事情。”*使用一个在需要时创建的单帧(或可能更好,JDialog),然后进行缓存。当第二次或以后显示时,它闪电般快速,并将用户位置保留在帮助中。该显示组件消耗的内存通常无需担心。 –
@SoboLAN:单击帮助按钮时,会调用代码中上面的initializeElements方法。 –