2014-02-05 6 views
0

Я использую образец кода с веб-сайта Java, и, как представляется, селектор файлов получает файл, который я хочу, но когда я пытаюсь обновить jframe и другие компоненты в gui Я называл селектор файлов, ничего не менял. Я попробовал немало из предложенных исправлений, чтобы обновить информацию, но ничего не работает. Большинство моих компонентов являются статическими, кстати ...Java: Swing компонент (ы), не перекраивающий

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import javax.swing.*; 
import java.awt.*; 
import java.io.File; 
import java.awt.event.*; 

public class GuiTester extends JFrame { 

    private static String fileName = "Input File: Please select a file"; 
    //Create a file chooser 
    private static final JFileChooser fc = new JFileChooser(); 
    private static JButton inputSelectorButton; 
    private static JButton outputSelectorButton; 
    private static JFrame frame = new JFrame("Gui Tester"); 
    private static JPanel panel = new JPanel(); 
    private static JLabel inputFile = new JLabel(fileName); 


    public static void main(String[] args) { 
     go(); 
    } 


    private static void go() { 
     inputSelectorButton = new JButton ("Select Input File"); 
     outputSelectorButton = new JButton ("Select Output File"); 
     Font bigFont = new Font("sans", Font.BOLD, 22); 
     Font smallFont = new Font("sans", Font.PLAIN, 9); 
     panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
     JLabel description0 = new JLabel(" ");   
     JLabel description6 = new JLabel(" "); 
     JLabel inputFile = new JLabel(fileName); 
     inputFile.setFont(smallFont); 
     inputSelectorButton.addActionListener(new inputSelectorListener()); 
     JButton startButton = new JButton ("GO!"); 

     panel.add(description0); 
     panel.add(description6); 
     panel.add(inputFile); 
     panel.add(inputSelectorButton); 
     panel.add(outputSelectorButton); 
     panel.add(startButton); 

     frame.getContentPane().add(BorderLayout.CENTER, panel); 
     inputFile.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     inputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     outputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     startButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     frame.setSize(370,400); 
     panel.setSize(370,400); 

     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 


    public static class inputSelectorListener implements ActionListener { 

     public void actionPerformed(ActionEvent e) { 
      if (e.getSource() == inputSelectorButton) { 
       int returnVal = fc.showOpenDialog(panel); 

       if (returnVal == JFileChooser.APPROVE_OPTION) { 
        File file = fc.getSelectedFile(); 
        if (file.exists()) 
         fileName = file.getPath(); 
        else 
         fileName = "File not found, please select a file"; 
        System.out.println(fileName); 
        inputFile.setText(fileName); 
        inputFile.validate(); 
        inputFile.repaint(); 
        panel.validate(); 
        panel.repaint(); 
        frame.validate(); 
        frame.repaint(); 
       } else { 
        System.out.println("Open command cancelled by user."); 
       } 
      } 
     } 
    } 

} 
+0

Вероятно потому, что ссылки у вас есть не являются ссылками на экране, но это только предположение, как вы смогли обеспечили работоспособный пример демонстрирует вашу проблему ... – MadProgrammer

+0

Для лучшего помогите раньше, опубликуйте [Минимальный полный испытанный и читаемый пример] (http://stackoverflow.com/help/mcve) (MCTRE). –

+0

@AndrewThompson сделано. – Lido

ответ

1

Я не вижу, где бы вы добавить

  • inputFile
  • panel

ко всему, что является отображаемым.

Вы также затеняете inputFile.

Вы создаете static ссылку ...

private static JLabel inputFile = new JLabel(fileName); 

Тогда в go, вы создаете локальную ссылку ...

JLabel inputFile = new JLabel(fileName); 

Это означает, что ссылку вы используете в методе actionPerformed является а не той же ссылкой, что и на экране.

Не полагайтесь на static решить ссылочные вопросы, это будет укусить вас более быстро, то вы можете реализовать ...

Вы хотели бы взглянуть на:

0

Вы должны попытаться использовать классы и лучше организовать свой код. Ниже я переработал существующий код. Я ничего не добавлял, но я перемещал некоторые вещи и удалял пару лишних переменных для этого примера.

Я изменил ваш ActionListener на AbstractAction, просто чтобы вы знали. :-P

import java.awt.Container; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.io.File; 

import javax.swing.AbstractAction; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JComponent; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

@SuppressWarnings("serial") 
public class GuiTester extends JPanel { 

    // Create a file chooser 
    private static final JFileChooser fc = new JFileChooser(); 

    private JLabel inputFile; 

    public GuiTester(int width, int height) { 
     Font smallFont = new Font("sans", Font.PLAIN, 9); 
     JLabel description0 = new JLabel(" "); 
     JLabel description6 = new JLabel(" "); 
     JButton startButton = new JButton("Enter"); 
     JButton inputSelectorButton = new JButton(new FileChooserAction(
       "Select Input File")); 
     JButton outputSelectorButton = new JButton("Select Output File"); 

     inputFile = new JLabel("Input File: Please select a file"); 
     inputFile.setFont(smallFont); 

     inputFile.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     inputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     outputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
     startButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); 

     add(description0); 
     add(description6); 
     add(inputFile); 
     add(inputSelectorButton); 
     add(outputSelectorButton); 
     add(startButton); 

     setSize(width, height); 
     setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 
    } 

    public JLabel getInputFileLabel() { 
     return inputFile; 
    } 

    @Override 
    public void invalidate() { 
     super.invalidate(); 

     // Invalidate the label, you really don't need this, but you should 
     // reference children in here if you want to explicitly invalidate them 
     // when the parent gets invalidated. The parent is responsible for 
     // telling its children what to do and when to do it. 
     inputFile.invalidate(); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     // This gets called when you repaint, since you are adding children 
     // to this panel, painting is pointless. You can however fill the 
     // background if you wish. 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame f = new JFrame("Gui Test"); 

       f.setContentPane(new GuiTester(370, 400)); 
       f.setSize(370, 400); 
       f.setVisible(true); 
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       f.setLocationRelativeTo(null); 
      } 
     }); 
    } 

    public class FileChooserAction extends AbstractAction { 
     public FileChooserAction(String name) { 
      super(name); 
     } 

     public void actionPerformed(ActionEvent e) { 
      Container c = ((JButton) e.getSource()).getParent(); 
      GuiTester g = null; 

      if (c instanceof GuiTester) { 
       g = (GuiTester) c; 
      } 

      int returnVal = fc.showOpenDialog(c); 

      if (g != null && returnVal == JFileChooser.APPROVE_OPTION) { 
       File file = fc.getSelectedFile(); 
       String fileName = "Input File: Please select a file"; 

       if (file.exists()) 
        fileName = file.getPath(); 
       else 
        fileName = "File not found, please select a file"; 

       System.out.println(fileName); 

       g.getInputFileLabel().setText(fileName); 

       g.validate(); 
       g.repaint(); 
      } else { 
       System.out.println("Open command cancelled by user."); 
      } 
     } 
    } 
} 
+0

Не нужно переопределять' invalidate', так как это будет означать, что иерархия компонентов должна быть автоматически перераспределена. – MadProgrammer

+0

Спасибо @ Mr.Polywhirl Я посмотрю на это и посмотреть, могу ли я узнать все! – Lido

Смежные вопросы