1
對不起,我知道這個主題有很多信息,但我仍然卡住了。我有兩個面板mainPanel和sidePanel。我想要做的是將一個圖像繪製到sidePanel。我的sidePanel將有其他組件,如按鈕和標籤。我可以使用JLabel將圖像添加到sidePanel,但是,圖像的大小和位置是一個問題。因此,我正在嘗試使用Graphics g將圖像繪製到sidePanel上。如果任何人可以幫助很多將不勝感激。謝謝你所有的幫助.` import java.awt.BorderLayout;試圖將圖像繪製到JPanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui extends JFrame {
private JPanel j;
private ImageIcon i;
public Gui(){
this.setSize(800,600);
this.setUp();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setUp(){
j = new JPanel();
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
contentPanel.setSize(new Dimension(800,600));
JPanel mainPanel = new JPanel();
JPanel sidePanel = new JPanel();
sidePanel.setPreferredSize(new Dimension(200,600));
mainPanel.setPreferredSize(new Dimension(600,600));
ImagePanel v = new ImagePanel();
//v.setBackground(Color.BLUE);
v.setPreferredSize(new Dimension(100,100));
sidePanel.add(v);
mainPanel.setBackground(Color.BLACK);
sidePanel.setBackground(Color.RED);
contentPanel.add(sidePanel, BorderLayout.WEST);
contentPanel.add(mainPanel, BorderLayout.CENTER);
this.add(contentPanel);
}
private class ImagePanel extends JPanel{
public void createImage(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("/GUI Practice/src/images.jpeg");
Image ii = i.getImage();
g.drawImage(ii, 10, 10, 90, 90, Color.WHITE, this);
repaint();
validate();
updateUI();
}
}
public static void main(String [] args){
Gui g = new Gui();
}
}
`
你可以提供你做了什麼的例子至今 – MadProgrammer
SO: - http://stackoverflow.com/questions/299495/how-to-add-an-image-to-a-jpanel –