我寫了兩種方式來顯示圖像時,JPanel數組綁定,但它不顯示圖像。單擊JPanel數組時顯示圖像
這是我的代碼:
public class Mutil_Image_2 implements MouseListener {
public JPanel [][]sub=new JPanel[10][10];
public JPanel screen = new JPanel();
public JFrame f = new JFrame("Draw on Panel");
public static int v1,v2;
public static int x1 =1,y1=1;
public Mutil_Image_2(String title)
{
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setExtendedState(JFrame.MAXIMIZED_BOTH); //Full Screen
screen.setBorder(BorderFactory.createLineBorder(Color.black));
screen.setLayout(new GridLayout(10,10));
int dem =0;
for (int i=0; i<=9;i++)
{
for (int j=0; j<=9;j++)
{
sub[i][j]= new JPanel();
sub[i][j].setBorder(BorderFactory.createLineBorder(Color.red));
screen.add(sub[i][j]);
v1=i;
v2=j;
sub[i][j].addMouseListener(this);
f.add(screen);
}
}
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
new Mutil_Image_2("Grid Layout");
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
JPanel source = (JPanel) e.getSource();
BufferedImage img1;
if(e.getButton() == MouseEvent.BUTTON1)
{
x1=e.getX();
y1=e.getY();
//source.setBackground(Color.black);
source.setSize(500, 500);
try { // The first way to show Image
img1 = ImageIO.read(new File("D:\\Pict3.png"));
JLabel picLabel = new JLabel (new ImageIcon(img1));
source.add(picLabel);
} catch (IOException e1) {
e1.printStackTrace();
}
source.add(new draw_Image_in_MultiPanel()); //Second way to show Image
}
}
}
class draw_Image_in_MultiPanel extends JPanel {
Image img1,img2;
public draw_Image_in_MultiPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setSize(screenSize.width, screenSize.height);
}
public void paint(Graphics g) {
super.paintComponent(g);
int vt1 = Mutil_Image_2.x1;
int vt2 = Mutil_Image_2.y1;
try
{
img1 = ImageIO.read(new File("D:\\Pict3.jpg"));
g.drawImage(img1, vt1, vt2, img1.getWidth(this),img1.getHeight(this) , Color.darkGray, this);
g.drawString("Postion is:" + vt1 + " -" + vt2, vt1,vt2);
} catch (IOException e) {
e.printStackTrace();
}
} }
非常感謝我給你。我試着和它適用於第一種方式,但在第二個方法的Java說: 在java.security.AccessController.doPrivileged(本機方法) \t在java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(來源不明) \t在java.awt.EventQueue.dispatchEvent(未知來源) \t在java.awt.EventDispatchThread.pumpOneEventForFilters(未知來源) \t在java.awt.EventDispatchThread.pumpEventsForFilter(未知來源) \t在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知來源) –
這很有趣,我似乎無法複製那個錯誤。 –
您是否需要執行第一種方式和第二種方式,或者是否希望只有在第一種方式失敗時才執行第二種方式。如果是後者,嘗試在catch塊中粘貼第二個.add調用。如果兩種方法都打算做同樣的事情,那麼使用這兩種方法有點多餘。 –