如何从另一种方法定义JTextfield?

时间:2014-09-01 22:59:12

标签: java swing browser actionlistener final

我正在创建一个浏览器,我正在创建浏览器以及它在main函数中的外观,但是为了调用actionListener我需要将它放在一个非{{1}的方法中},但是当我将static放在一个单独的方法中时,它会要求我将它actionListener放在final方法中?

CODE:

main

命令行编译器一直给我这些错误,说它需要声明import java.awt.*; import javax.swing.*; import java.util.*; import java.awt.event.*; import java.applet.*; public class browserPannel extends JFrame{ public static void main(String[] arg) { JFrame browser = new JFrame("A Nun In A Weelchair"); browser.setSize(1000,700); browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); browser.setLocationRelativeTo(null); browser.pack(); browser.setVisible(true); JPanel header = new JPanel(); header.setBackground(Color.lightGray); final JEditorPane htmlc = new JEditorPane(); htmlc.setBackground(Color.red); htmlc.setEditable(true); htmlc.setContentType("text/html"); final JTextField url = new JTextField(20); url.setSize(890,30); url.setVisible(true); JButton send = new JButton("Send"); send.setSize(75,30); send.setVisible(true); header.add(url, BorderLayout.SOUTH); header.add(send); browser.getContentPane().add(header, BorderLayout.NORTH); browser.getContentPane().add(new JScrollPane(htmlc)); } public void loader(JFrame browser, JTextField url, JEditorPane htmlc, JPanel header, JButton send, String[] arg) { url.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { loadHtml(htmlc, url, event.getActionCommand()); System.out.println("action performed"); } } ); } private void loadHtml(JEditorPane htmlc, JTextField url, String link) { try{ htmlc.setPage(link); url.setText(link); }catch(Exception e){ System.out.println("ops sorry could not fined Virgine Mobile"); e.printStackTrace(); } } } ,但我已经在主类中声明了final?

CMD MESSAGE:

final

1 个答案:

答案 0 :(得分:0)

您的方法的相关参数loader()需要声明为最终版。

public void loader(JFrame browser, final JTextField url, final JEditorPane htmlc, JPanel header, JButton send, String[] arg)
    {
       ...

除此之外,请阅读thread safety in Swing。几乎整个main方法都应该包含在Runnable中,并在Swing的Event Dispatch Thread上执行。

public static void main( String... args ) {

   SwingUtilities.invokeLater(new Runnable() {
      public void run() {

         Jframe browser = new Jframe( "Nun in a wheelchair." );
         ...

      }
    });

}