Reputation: 91
I need a program that displays many images and I need window that can be scrolled for that. I read the documentation and searched on the forum but I still didn't manage to do it. I tried with JScrollPane and JFrame as you can see below.
JScrollPane class:
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class EmojiWindow extends JScrollPane {
private void newImg(String emojiLocation, String emojiName) {
JLabel emoji = new JLabel(new ImageIcon(emojiLocation));
Emoji.setToolTipText(emojiName);
add(emoji);
Emoji.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e))
{
JFrame frame = new JFrame("new frame");
frame.setSize(300, 10);
frame.setVisible(true);
}
}
});
}
public EmojiWindow(){
newImg("fbike.png", "Riding a bike");
newImg("fdizzy.png", "Dizzy");
newImg("fcubehead.png", "Cube head");
newImg("fhappy.png", "Happy");
}
}
Main:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args)
{
EmojiWindow scrollPane = new EmojiWindow();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JFrame window = new JFrame();
window.add(scrollPane, BorderLayout.SOUTH);
window.setSize(300, 400);
window.setVisible(true);
}
}
Edit: Changed the variables' and methods' names to camel-case to stop triggering people.
Upvotes: 1
Views: 2049
Reputation: 324207
First of all, learn and follow Java naming conventions. Variable names should NOT start with an upper case character. Any example you find in this forum or text book uses this convention. Learn by example!!!
Don't extend JScrollPane. There is no need to do this as you are not adding any new functionality to the class.
Also, never add components to a JScrollPane
. A single component is added to the JViewPort
of the scroll pane.
So in this case you would create a JPanel using an appropriate layout manager. Then you add the panel to the viewport of the scroll pane.
So the basic code might be something like:
JPanel imagePanel = new JPanel();
imagePanel.add( label1 );
imagePanel.add( label2 );
...
JScrollPane scrollPane = new JScrollPane( imagePanel );
window.add( scrollPane );
Read the Swing Tutorial for working examples of all the Swing basics.
Edit:
You can also try the Wrap Layout which will cause components to wrap to the next line when a horizontal row is full.
Upvotes: 3