سؤال

كتبت هذا الرمز:

public class FileViewer extends JPanel implements ActionListener {

/**
 * 
 */
private static final long serialVersionUID = 1L;

JFileChooser chooser;

FileNameExtensionFilter filter = null;

JEditorPane pane = null;

JTextField text = null;

JButton button;

JTextArea o = null;

URL url;

public FileViewer(JTextArea o) {
    this.o = o;
    setLayout(new FlowLayout(FlowLayout.RIGHT));
    JTextField text = new JTextField("file...", 31);
    text.setColumns(45);
    text.revalidate();
    text.setEditable(true);

    button = new JButton("Browse");
    add(text);
    add(button);
    filter = new FileNameExtensionFilter("html", "html");
    chooser = new JFileChooser();
    chooser.addChoosableFileFilter(filter);

    button.addActionListener(this);

}

public void paintComponent(Graphics g) {
    super.paintComponents(g);
    Graphics2D graphic = (Graphics2D) g;
    graphic.drawString("HTML File:", 10, 20);

}

public void actionPerformed(ActionEvent event) {
    int returnVal = 0;
    if (event.getSource() == button) {
        returnVal = chooser.showOpenDialog(FileViewer.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            text.setToolTipText(chooser.getSelectedFile().getName());

        } else
            o.append("Open command cancled by user.");
      }
     }
}

ولكن في الخط: text.setToolTipText(chooser.getSelectedFile().getName()); يتم إلقاء nullpointerException!

تعديللقد قمت بإصلاح المشكلة التي ذكرتها أعلاه ولكنها لا تعمل بشكل صحيح (لا تكتب اسم الملف في النص!) :-(

هل كانت مفيدة؟

المحلول

الإجابة على وجهة نظرك الأخرى:

text.setToolTipText(chooser.getSelectedFile().getName());

هل كان هذا السلوك المقصود؟ سوف يظهر اسم الملف فقط كتاجر تلميح عند الماوس فوق حقل النص. لوضع النص مباشرة في jtextfield يجب عليك الاتصال setText() في حين أن.

نصائح أخرى

لقد أعلنت text على مستوى العالم وتعيينها NULL لذلك. في منشئك ل FileViewer أنت تعلن ذلك مرة أخرى مع new, ، ولكن هذا الإعلان محلي. المتغير المشار إليه في actionPerformed() هو العالم العالمي، الذي لا يزال NULL, ، لذلك تحصل على الاستثناء. إذا قمت بتغيير

JTextField text = new JTextField("file...", 31);

ل

text = new JTextField("file...", 31);

يجب أن إصلاحه.

استبدال هذا:

JTextField text = new JTextField("file...", 31);

مع هذا:

text = new JTextField("file...", 31);

النص الميداني فارغ كما هو الحال في منشئ FileViewer الخاص بك قمت بإنشاء متغير محلي يسمى النص الذي تمت إضافته إلى النموذج.

يستبدل

JTextField text = new JTextField("file...", 31);

مع

text = new JTextField("file...", 31);

setToolTipText الطريقة لا تعدد النص. يقوم بتعيين نص Tooltip، الذي يظهر عندما يحوم الماوس بالنص. يستخدم setText طريقة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top