Ответ 1
Вот сначала посмотрите этот маленький пример, дайте мне знать, если вы понимаете, что здесь происходит. Тогда только мы будем идти дальше, медленно медленно. Попробуйте пройти этот пример, в котором я покажу вам, как рисовать на JPanel
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class PaintingExample {
private CustomPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Painting Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new CustomPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PaintingExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel {
private BufferedImage image;
public CustomPanel() {
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
try {
/*
* Since Images are Application Resources,
* it always best to access them in the
* form of a URL, instead of File, as you are doing.
* Uncomment this below line and watch this answer
* of mine, as to HOW TO ADD IMAGES TO THE PROJECT
* http://stackoverflow.com/a/9866659/1057230
* In order to access images with getClass().getResource(path)
* here your Directory structure has to be like this
* Project
* |
* ------------------------
* | |
* bin src
* | |
* --------- .java files
* | |
* package image(folder)
* ( or |
* .class 404error.jpg
* files, if
* no package
* exists.)
*/
//image = ImageIO.read(
// getClass().getResource(
// "/image/404error.jpg"));
image = ImageIO.read(new URL(
"http://i.imgur.com/8zgHpH8.jpg"));
} catch(IOException ioe) {
System.out.println("Unable to fetch image.");
ioe.printStackTrace();
}
}
/*
* Make this one customary habbit,
* of overriding this method, when
* you extends a JPanel/JComponent,
* to define it Preferred Size.
* Now in this case we want it to be
* as big as the Image itself.
*/
@Override
public Dimension getPreferredSize() {
return (new Dimension(image.getWidth(), image.getHeight()));
}
/*
* This is where the actual Painting
* Code for the JPanel/JComponent
* goes. Here we will draw the image.
* Here the first line super.paintComponent(...),
* means we want the JPanel to be drawn the usual
* Java way first (this usually depends on the opaque
* property of the said JComponent, if it true, then
* it becomes the responsibility on the part of the
* programmer to fill the content area with a fully
* opaque color. If it is false, then the programmer
* is free to leave it untouched. So in order to
* overcome the hassle assoicated with this contract,
* super.paintComponent(g) is used, since it adheres
* to the rules, and performs the same task, depending
* upon whether the opaque property is true or false),
* then later on we will add our image to it, by
* writing the other line, g.drawImage(...).
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
Скомпилировать и запустить:
- Запустить командную строку/терминал/cmd. И перейдите в указанное место к папке Проект
-
Теперь скомпилируйте код, используя:
C:\Project > javac -d bin src\*. java
-
Теперь перейдите в папку bin, выполнив команду:
C:\Project > cd bin
-
Внутри папки bin выполните следующую команду:
C:\Project\bin > java PaintingExample
Вот код при использовании JLabel
в качестве основы для изображения:
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class LabelExample {
private JPanel contentPane;
private JLabel imageLabel;
private void displayGUI() {
JFrame frame = new JFrame("Label Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBorder(
BorderFactory.createLineBorder(Color.BLACK, 5));
//imageLabel = new JLabel(
// new ImageIcon(
// getClass().getResource(
// "/image/404error.jpg")));
try {
imageLabel = new JLabel(new ImageIcon(
new URL("http://i.imgur.com/8zgHpH8.jpg")));
} catch(MalformedURLException mue) {
System.out.println(
"Unable to get Image from"
+ "the Resource specified.");
mue.printStackTrace();
}
contentPane.add(imageLabel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LabelExample().displayGUI();
}
});
}
}
Вот результат обоих приведенных выше кодов: