I've been searching for an answer, but everything else comes very close, but isn't the problem I'm having.
So my main class creates a new JFrame, adds a panel as the content panel, and I add a scrollpanel to that content panel.
Now I create some of my extending JPanel classes, add them to the scroll pane and see nothing but an empty frame.
And I have checked to make sure there is indeed a list of FTPFile's
Here is the main code:
public browser(ftpHandler _FTP) {
FTP = _FTP;
Panels = new ArrayList<JPanel>();
frame = new JFrame("File Browser");
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(750, 500));
frame.setSize(frame.getPreferredSize());
frame.setMinimumSize(frame.getSize());
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
listFiles();
frame.pack();
frame.setVisible(true);
}
public void listFiles(){
Panels.clear();
FTPFile[] list = null;
try {
list = FTP.listFiles();
} catch (Exception e) {
e.printStackTrace();
}
for(FTPFile file : list){
fileObject FO = new fileObject(file);
Panels.add(FO);
scrollPane.add(FO);
}
scrollPane.updateUI();
}
And my extended JPanel, fileObject
public class fileObject extends JPanel {
private FTPFile file;
private JLabel Label;
private ImageIcon Icon;
private int FileType;
private final int IconSize = 25;
private final Dimension panelSize = new Dimension(150, 40);
public fileObject(FTPFile FILE){
file = FILE;
FileType = file.getType();
this.setSize(panelSize);
this.setPreferredSize(panelSize);
this.setMinimumSize(panelSize);
this.setLayout(new WrapLayout());
switch (FileType){
case FTPFile.TYPE_DIRECTORY:
Icon = resizeImage(new ImageIcon(getClass().getResource("/com/taylor/48px/folder.png")),IconSize);
break;
case FTPFile.TYPE_FILE:
try {
String FileExtension = file.getName().substring(file.getName().lastIndexOf(".")+1);
Icon = resizeImage(new ImageIcon(getClass().getResource("/com/taylor/48px/"+FileExtension+".png")),IconSize);
} catch(Exception e) {
Icon = resizeImage(new ImageIcon(getClass().getResource("/com/taylor/48px/_blank.png")),IconSize);
}
break;
case FTPFile.TYPE_LINK:
Icon = resizeImage(new ImageIcon(getClass().getResource("/com/taylor/48px/_page.png")),IconSize);
break;
}
Label = new JLabel(file.getName(), Icon, JLabel.LEFT);
this.add(Label);
}
private ImageIcon resizeImage(ImageIcon II, int Size){
Image img = II.getImage();
BufferedImage resizedImage = new BufferedImage(Size, Size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, Size, Size, null);
g2.dispose();
return new ImageIcon(resizedImage);
}
}
I got this working, it turns out I was had my panels set up wrong, they were setup like this:
JFrame
--mainPanel
----scrollPane
And I was adding my extended panel to the scrollPane
And this seemed to not work, so I added another panel inside the scrollPane and started adding my extended panels to this new panel and it started working!
Related
I'm making a board game in Java, and I am trying to render the board itself in JPanel. The way I'm trying to do this is by inserting a image of the board (which is represented by a JLabel) and a grid (which is also represented by a JPanel). The idea is for each grid square to correspond to the squares on the image of the board.
Here is what it currently looks like
As you can see, it's not aligning correctly. Here is the code I tried to accomplish this:
public class BoardImage {
ImagePanel test = new ImagePanel();
GridPanel grid = new GridPanel();
public void returnBoardPanel() {
JFrame frame = new JFrame("JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel image = new JLabel();
image = test.createImage();
image.setLayout(new BorderLayout());
frame.setContentPane(image);
frame.add(grid.paintMe());
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
public static void main (String[] agrs) {
BoardImage test = new BoardImage();
test.returnBoardPanel();
}
}
class ImagePanel extends JPanel{
public JLabel createImage() {
JLabel temp = new JLabel();
ImageIcon icon = new ImageIcon(this.getImage("/boardEdit.jpeg"));
temp.setIcon(icon);
temp.setBounds(0, 0, 552, 575); //needed in order for 24x25 to work
return temp;
}
public Image getImage(String filePath) {
int width, height;
Image tempImage = null;
try {
/* Loads the image, and assigns it to the tempImage var */
URL imagePath = BoardImage.class.getResource(filePath);
tempImage = Toolkit.getDefaultToolkit().getImage(imagePath);
}
catch(Exception e){ //if the filePath does not exist, or something else messed up
System.err.println("We were not able to load the requested image form the given filePath: " + "\n" + filePath);
}
return tempImage;
}
}
class GridPanel extends JPanel{
private JLabel[][] grid;
public GridPanel paintMe(){
this.setBounds(0, 0, 552, 575); //needed in order for 24x25 to work
this.fillGrid();
this.setOpaque(false);
return this;
}
public void fillGrid() {
this.setLayout(new GridLayout(24, 25));
grid = new JLabel[24][25];
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 25; j++) {
grid[i][j] = new JLabel();
grid[i][j].setBorder(new LineBorder(Color.BLACK));//keep this until it works
grid[i][j].setOpaque(false);
this.add(grid[i][j]);
}
}
}
}
I've tried everything I've found online, and on SO, but I can't seem to figure it out. Any suggestions?
I have a GridBagConstraints gbcImage and a JLabel that is initialized like this:
gbcImage.gridx = 1; // column 0
gbcImage.gridy = 2; // row 2
gbcImage.ipady = 100;
gbcImage.ipadx = 100;
JLabel label = new JLabel("", null, JLabel.CENTER);
label.setOpaque(true);
label.setBackground(Color.WHITE);
panel.add(label, gbcImage);
Where panel is added to a JFrame.
So I implemented a MouseListener to the label:
public void mouseClicked(MouseEvent e) {
JFileChooser jfc = new JFileChooser();
int iRet = jfc.showOpenDialog(panel);
if (iRet == jfc.APPROVE_OPTION)
{
File file = jfc.getSelectedFile();
try
{
BufferedImage bi = ImageIO.read(file);
image = new ImageIcon(bi);
JLabel label = new JLabel("", image, JLabel.CENTER);
panel.add(label, gbcImage);
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
But it didn't work. The image doesn't show in the panel at runtime.
What am I missing?
There is no need to create a new JLabel. The problem is you added a new label to the panel but its default size is (0, 0) because you didn't reavalidate() and repaint() the panel.
There is no need to create a new label.
Instead you keep a reference to the original label (like you do for the panel) and then you just replace the icon:
image = new ImageIcon(bi);
label.setIcon( image );
I need to put a menu in a game, so I've created a frame called menuFrame and a panel called menuPanel. I've been able to get a button and a label with text to appear on this panel, but I can't get an image to display.
Here is the bulk of my code:
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel);
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
} catch (IOException e) {
e.printStackTrace();
}
I've been messing with it for a very long time, and the image simply wont appear. I've tried using just ImageIcon and no BufferedImage and that didn't work. I put the image in the same package as the class.
You could do something like this:
ImageIcon imgIcon = new ImageIcon("background2.png");
JLabel menuLabel = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(imgIcon);
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel); //This might not work, try the name of the JFrame instance
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
this.revalidate() //Use the name of the JFrame if this is not a JFrame or if this.add(menuPanel); doesnt work
} catch (IOException e) {
e.printStackTrace();
}
I have a JFrame that shoud show an image (retrieved from web) and two lateral buttons for show next and previous image. Original image size is too big, and i would scale it before show. this is my code:
public class ShowPicture extends JFrame implements ActionListener {
private String link;
private JButton next;
private JButton prev;
private Image image;
public ShowPicture(String link) {
this.setSize(300, 200);
setLocationRelativeTo(null); //center
setVisible(true);
this.link = link;
this.setLayout(new FlowLayout());
prev = new JButton("prev");
next = new JButton("next");
URL url;
try {
url = new URL(link + "/front.jpg");
image = ImageIO.read(url);
} catch (MalformedURLException ex) {
Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel image_label = new JLabel(new ImageIcon(image));
image_label.setSize(100, 100);
this.add(prev);
this.add(image_label);
this.add(next);
pack();
}
but image is not scaled
how can i do?
I would scaled the image itself not the JLabel. Use :
image = ImageIO.read(url);
image = image.getScaledInstance(100,100,Image.SCALE_DEFAULT);
JLabel image_label = new JLabel(new ImageIcon(image));
This is my first time on stackoverflow and I am having an issue which I can't seem to get to the bottom of. I am trying to independently develop a small desktop game which uses a class called "Frame.java" to create a JFrame with all the menus and such that I need using a method called "create()", which returns the frame. I'm also using another class called "MainPanel.java", which extends JPanel, to create an instance of MainPanel to add to the frame's contentpane. However, when I run all the code in my little driver program, nothing seems to be displaying. any help would be appreciated!
public class MainPanel extends JPanel{
//the background image of the game
private BufferedImage img = null;
//GUI components of the game
private JPanel gameWindow, gameWindowHolder, gameInfoHolder, LevelPanel, RevenuePanel,
ActionPanel, TimePanel;
public MainPanel(String path, int width, int height){
//create BufferedImage based on path
img = new ImageHelper().createBufferedImage(path);
//use img to create JPanel gameWindow
gameWindow = ImageHelper.makeImageComponent(img, width, height);
gameInfoHolder = new JPanel();
gameInfoHolder.setPreferredSize(new Dimension(width+10, height+10));
gameInfoHolder.setBackground(Color.black);
gameInfoHolder.add(gameWindow);
//set size of this MainPanel
setPreferredSize(new Dimension(width+300, height+10));
//add gameInfoHolder to MainPanel
add(gameInfoHolder);
}
public void paint(Graphics g) {
super.paintComponent(g);
}
}
public class Driver {
public static void main( String []args){
JFrame frame = Frame.create();
JPanel panel = new MainPanel("images/backgrounds/jessicaAlba.jpg", 330, 500);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
public class ImageHelper {
//
//Returns an ImageIcon object based on the path
//
public ImageIcon createImageIcon(String path, String description){
URL imgURL = getClass().getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL, description);
else {
System.err.println("Couldn't find this file: " + path + ". Check path.");
return null;
}
}
//
//Returns an Image object based on the path
//
public Image createImage(String path){
URL imgURL = getClass().getResource(path);
Toolkit kit = Toolkit.getDefaultToolkit();
if (imgURL != null){
return kit.createImage(imgURL);
}
else {
System.err.println("Couldn't find this file: " + path + ". Check path.");
return null;
}
}
//
//Returns a BufferedImage object based on the path
//
public BufferedImage createBufferedImage(String path){
BufferedImage image;
URL imgURL = getClass().getResource(path);
try
{
image = ImageIO.read(imgURL);
}
catch (IOException e)
{
System.err.println("Couldn't find this file: \""+ path +"\". Check path.");
return null;
}
return image;
}
//
//Returns a JPanel object composed of the image found in the path.
//
public static JPanel makeImageComponent(String path, int width, int height){
BufferedImage image;
JLabel picLabel;
ImageIcon icon;
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
ImageHelper h = new ImageHelper();
image = h.createBufferedImage(path);
image = resize(image, width, height);
icon = new ImageIcon(image);
panel.setPreferredSize(new Dimension(width, height));
panel2.setPreferredSize(new Dimension(width+10, height+10));
panel2.setBackground(Color.black);
picLabel = new JLabel(icon);
panel.add(picLabel);
panel2.add(panel);
return panel2;
}
//
//Returns a JPanel object composed of the BufferedImage object in the argument
//
public static JPanel makeImageComponent(BufferedImage image, int width, int height){
JLabel picLabel;
ImageIcon icon;
JPanel panel = new JPanel();
image = resize(image, width, height);
icon = new ImageIcon(image);
panel.setPreferredSize(new Dimension(width, height));
picLabel = new JLabel(icon);
panel.add(picLabel);
return panel;
}
//
//Resizes the BufferedImage object to the specified new width and new height.
//
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
}
Nothing is displayed as you're short-circuiting the paint 'stack' with super.paintComponent so no child components will be painted.
public void paint(Graphics g) {
super.paintComponent(g);
}
As this is really serving no purpose it can be removed and the added panels will be displayed.