gpt4 book ai didi

java - Java动态添加ImageIcon

转载 作者:行者123 更新时间:2023-11-29 04:40:55 26 4
gpt4 key购买 nike

好的,我是 GUI 方面的新手。我正在试验一个简单的程序,您可以在其中选择颜色、宽度、高度,它会生成一个具有指定值的 png 文件。我的问题是在我的生成函数执行后将图像图标添加到标签。文件已创建,但 imageIcon 未显示在 imagePanel 中。这只是我正在创建的测试。

这是我遇到问题的地方:

    private void generateActionPerformed(java.awt.event.ActionEvent evt) {                                    
int Width=getWidthInput();
int Height= getHeightInput();
BufferedImage image= new BufferedImage(Width,Height, BufferedImage.TYPE_INT_ARGB);
File directory= null;
BufferedImage generatedPic;
//drawing portions of image
for(int i = 0; i < Height; i++){
for(int j=0; j<Width; j++){
int a=255;
int r=getRed();
int g=getGreen();
int b=getBlue();
int p= (a<<24)|(r<<16)|(g<<8)|b;
image.setRGB(j,i,p);
}
}
try{
directory= new File("testImg.png");
ImageIO.write(image,"png",directory);
System.out.println("Image Has Been Written");
ImageIcon ii= new ImageIcon(getClass().getResource("testImg.png"));
imageLabel.setIcon(ii);
revalidate();
repaint();
}
catch(IOException e){
System.out.println("Error: "+ e);
}
directory.deleteOnExit();
}

这是整个程序:

public class MainFrame extends javax.swing.JFrame {
private JButton submitBtn;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}

public int getRed(){
return Integer.parseInt(red.getText());
}

public int getGreen(){
return Integer.parseInt(green.getText());
}

public int getBlue(){
return Integer.parseInt(blue.getText());
}

public int getWidthInput(){
return Integer.parseInt(width.getText());
}

public int getHeightInput(){
return Integer.parseInt(height.getText());
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")

private void initComponents() {

mainPanel = new javax.swing.JPanel();
imagePanel = new javax.swing.JPanel();
imageLabel= new JLabel();


jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
red = new javax.swing.JTextField();
green = new javax.swing.JTextField();
blue = new javax.swing.JTextField();
width = new javax.swing.JTextField();
height = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
submitBtn= new JButton("Generate Image");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

mainPanel.setForeground(new java.awt.Color(54, 136, 137));
mainPanel.setAutoscrolls(true);





jLabel2.setText("color:");

jLabel3.setText("width:");

jLabel4.setText("height:");

submitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
generateActionPerformed(evt);
}
});

javax.swing.GroupLayout imagePanelLayout = new javax.swing.GroupLayout(imagePanel);
imagePanel.setLayout(imagePanelLayout);
imagePanelLayout.setHorizontalGroup(
imagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
);
imagePanelLayout.setVerticalGroup(
imagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(red, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(green, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(blue, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(width)
.addComponent(height)
.addComponent(submitBtn))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addComponent(imagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(red, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(green, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(blue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(297, Short.MAX_VALUE))
);

jMenuBar1.setBackground(new java.awt.Color(54, 136, 137));

jMenu1.setText("File");
jMenuBar1.add(jMenu1);

jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);

jMenu3.setText("jMenu3");
jMenuBar1.add(jMenu3);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}
private void generateActionPerformed(java.awt.event.ActionEvent evt) {
int Width=getWidthInput();
int Height= getHeightInput();
BufferedImage image= new BufferedImage(Width,Height, BufferedImage.TYPE_INT_ARGB);
File directory= null;
BufferedImage generatedPic;
//drawing portions of image
for(int i = 0; i < Height; i++){
for(int j=0; j<Width; j++){
int a=255;
int r=getRed();
int g=getGreen();
int b=getBlue();
int p= (a<<24)|(r<<16)|(g<<8)|b;
image.setRGB(j,i,p);
}
}
try{
directory= new File("testImg.png");
ImageIO.write(image,"png",directory);
System.out.println("Image Has Been Written");
ImageIcon ii= new ImageIcon(getClass().getResource("testImg.png"));
imageLabel.setIcon(ii);
revalidate();
repaint();
}
catch(IOException e){
System.out.println("Error: "+ e);
}
directory.deleteOnExit();




}




/*
private void redActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
*/
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws IOException {

/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {

new MainFrame().setVisible(true);

}
});
}

// Variables declaration - do not modify
private javax.swing.JTextField blue;
private javax.swing.JTextField green;
private javax.swing.JTextField height;
private javax.swing.JLabel imageLabel;
private javax.swing.JPanel imagePanel;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel mainPanel;
private javax.swing.JTextField red;
private javax.swing.JTextField width;
// End of variables declaration
}

最佳答案

由于代码已经创建了一个 File,因此使用该文件作为 ImageIconURL 的基础非常有意义!例如

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SavedImageDisplayer {

public static void main(String[] args) throws IOException {
BufferedImage img = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
final File file = new File("testImg.png");
ImageIO.write(img, "png", file);
Runnable r = new Runnable() {
@Override
public void run() {
ImageIcon imageIcon;
try {
// use the File as basis for the URL!
imageIcon = new ImageIcon(file.toURI().toURL());
JOptionPane.showMessageDialog(null, imageIcon);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
};
SwingUtilities.invokeLater(r);
}
}

关于java - Java动态添加ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39237665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com