在createWorkPanel()
方法中,我创建了一个Label并在其中放置了图片,但是该图片未显示在屏幕上。也许有人知道为什么,请告诉我?
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class MainWindow extends JFrame {
private JButton button1;
public MainWindow() throws IOException
{
setLayout(new BorderLayout());
createWorkPanel();
setTitle("Графический дизайнер");
//setDefaultLookAndFeelDecorated(true);
setSize(1000,600);
// setLocation(400,100);
// setVisible(true);
// pack(); // automatically size the window to fit its components
setLocationRelativeTo(null); // center this window on the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void createWorkPanel() throws IOException
{
setLayout(new FlowLayout());
button1 = new JButton("Load Images");
button1.setActionCommand("Button 1 was prassed!");
add(button1);
ActionListener actionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
File fImg = MyFileChooser.chooseFile("Image Files (png & jpg)", "png", "jpg");
if (fImg != null)
{
JLabel background=new JLabel(new ImageIcon(fImg.getAbsolutePath()));
// background.setLayout(new FlowLayout());
add(background);
System.out.println(" файл создан");
}
}
};
button1.addActionListener(actionListener);
}
public static void main (String [] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new MainWindow ().setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
class MyFileChooser {
public static File chooseFile(String description, String... extensions) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + selectedFile.getAbsolutePath());
return selectedFile;
} else {
return null;
}
}
}
答案 0 :(得分:0)
遵循以下代码。
if (fImg != null) {
JLabel background = new JLabel(new ImageIcon(fImg.getAbsolutePath()));
add(background);
MainWindow.this.revalidate();
}
添加MainWindow.this.revalidate();
应该会有所帮助。