【发布时间】:2014-03-01 05:50:27
【问题描述】:
我正在使用 Java 网站上的一些示例代码,文件选择器似乎得到了我想要的文件,但是当我尝试更新我曾经调用文件选择器的 gui 中的 jframe 和其他组件时,什么也没有变化。我已经尝试了很多建议的修复程序来更新内容,但似乎没有任何效果。顺便说一句,我的大部分组件都是静态的......
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.");
}
}
}
}
}
【问题讨论】:
-
可能是因为您拥有的引用不是屏幕上的引用,但这只是猜测,因为您未能提供一个可运行的示例来证明您的问题...
-
如需尽快获得更好的帮助,请发帖Minimal Complete Tested and Readable Example (MCTRE)。
-
@AndrewThompson 完成。
-
@MadProgrammer,抱歉,已修复。
-
小心过度使用
static,它不是你的朋友...