How to find JLabel that was clicked and show ImageIcon from it? - java

Here is my code. I want to know which l was clicked and then in a new frame, display that ImageIcon.
The e.getSource() is not working...
final JFrame shirts = new JFrame("T-shirts");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
for (int i = 1; i < 13; i++) {
l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
l.setFont(l.getFont().deriveFont(20f));
panel.add(l);
}//end of for loop
panel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
sizes = new JFrame("Shopping");
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
if(e.getSource()==l){//FIX
sizes.add(l);
}//end of if
}
});
shirts.setContentPane(panel);
shirts.setSize(1000, 1000);
shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shirts.setVisible(true);

If you add your MouseListener directly to your JLabels, then you can display the pressed label's icon easily in a JOptionPane:
#Override
public void mousePressed(MouseEvent mEvt) {
JLabel label = (JLabel) mEvt.getSource();
Icon icon = label.getIcon();
JOptionPane.showMessageDialog(label, icon);
}
For example:
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
public class FooMouseListener extends JPanel {
private GetImages getImages;
public FooMouseListener() throws IOException {
getImages = new GetImages();
setLayout(new GridLayout(GetImages.SPRITE_ROWS, GetImages.SPRITE_COLS));
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
for (int i = 0; i < GetImages.SPRITE_CELLS; i++) {
JLabel label = new JLabel(getImages.getIcon(i));
add(label);
label.addMouseListener(myMouseAdapter);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
Icon icon = label.getIcon();
JOptionPane.showMessageDialog(label, icon, "Selected Icon", JOptionPane.PLAIN_MESSAGE);
}
}
private static void createAndShowGui() {
FooMouseListener mainPanel = null;
try {
mainPanel = new FooMouseListener();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("FooMouseListener");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GetImages {
private static final String SPRITE_PATH = "http://th02.deviantart.net/"
+ "fs70/PRE/i/2011/169/0/8/blue_player_sprite_sheet_by_resetado-d3j7zba.png";
public static final int SPRITE_ROWS = 6;
public static final int SPRITE_COLS = 6;
public static final int SPRITE_CELLS = SPRITE_COLS * SPRITE_ROWS;
private List<Icon> iconList = new ArrayList<>();
public GetImages() throws IOException {
URL imgUrl = new URL(SPRITE_PATH);
BufferedImage mainImage = ImageIO.read(imgUrl);
for (int i = 0; i < SPRITE_CELLS; i++) {
int row = i / SPRITE_COLS;
int col = i % SPRITE_COLS;
int x = (int) (((double) mainImage.getWidth() * col) / SPRITE_COLS);
int y = (int) ((double) (mainImage.getHeight() * row) / SPRITE_ROWS);
int w = (int) ((double) mainImage.getWidth() / SPRITE_COLS);
int h = (int) ((double) mainImage.getHeight() / SPRITE_ROWS);
BufferedImage img = mainImage.getSubimage(x, y, w, h);
ImageIcon icon = new ImageIcon(img);
iconList.add(icon);
}
}
// get the Icon from the List at index position
public Icon getIcon(int index) {
if (index < 0 || index >= iconList.size()) {
throw new ArrayIndexOutOfBoundsException(index);
}
return iconList.get(index);
}
public int getIconListSize() {
return iconList.size();
}
}

Have you tried this?
public void mouseClicked(MouseEvent e)
{
sizes = new JFrame("Shopping");
sizes.add(l);
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
//Remove the "e.getSource()" part.
}
It will automatically display the image, because you are assigning the Image Name to it, in the same segment as the Addition to the new JFrame.
Let me know of the outcome

Related

Can I return something from mouseClicked to my main

We are supposed to display an image and a button. If you press the button the image should change.
My problem is that im unsure how to return the changed image. Since i cant change the return type from mouseClicked. I also tried get and set but this doesnt work because im working on diffrent objects since mouseClicked and main are in diffrent classes.
This is what i have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
class AppFrame extends JFrame {
public AppFrame(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Original extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 0){
try {
AppDrawEvent obj = new AppDrawEvent();
BufferedImage img = obj.getImg();
int w = img.getWidth();
int h = img.getHeight();
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int pixel = img.getRGB(j, i);
img.setRGB(j,i,pixel+100);
}
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
public class AppDrawEvent
{
private BufferedImage img=ImageIO.read(new File("FILEPATH"));
public AppDrawEvent() throws IOException {
}
public BufferedImage getImg() {
return img;
}
public void setImg(BufferedImage img) {
this.img = img;
}
public static void main(String[] args ) throws IOException
{
JFrame frame = new AppFrame("TITEL");
JPanel panel = new JPanel();
frame.add(panel);
FlowLayout Layout = new FlowLayout(FlowLayout.LEFT);
panel.setLayout(Layout);
JButton bOrg = new JButton("Original");
panel.add(bOrg, BorderLayout.NORTH);
Original m = new Original();
bOrg.addMouseListener(m);
AppDrawEvent obj = new AppDrawEvent();
BufferedImage img= obj.getImg();
JLabel picLabel = new JLabel(new ImageIcon(img));
panel.add(picLabel, BorderLayout.CENTER);
frame.setSize(new Dimension(img.getWidth()+150,img.getHeight()+100));
frame.setVisible(true);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Why do the panels disappear when i press UP?

This is my code for a game im making. At the moment im not worried about how the game functions I've been more so worried about the fact that each time I hit the UP button the panels disappear and sometimes when i hit the LEFT button as well. Is there an explanation to this can anyone help me understand why this happens?? I have a feeling it has something to do with my if statements but im not really sure. also, im messing around with the key listener and if you could give me some advice on key listeners like some dos and donts I really appreciate the help!!
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Game extends Applet implements ActionListener,KeyListener {
Image image;
MediaTracker tr;
JLabel label,computerLabel;
JPanel panel,computerPanel;
Button start,up,down;
Label result;
Dimension SIZE = new Dimension(50,50);
int x = 0;
int y = 0;
int w = 100;
int q = 100;
int WIDTH = 50;
int HEIGHT = 50;
//Player Integers
int zeroPosX,zeroPosY,xLeft,xUp;
//Computer integers
int compZeroPosX,compZeroPosY,compXLeft,compXUp;
//--------------------------------------
public void init() {
setLayout(new FlowLayout());
start = new Button("Start");
up = new Button("UP");
down = new Button("LEFT");
//PlayerPiece stuff
ImageIcon icon = new ImageIcon("playerpiece.png");
label = new JLabel(icon);
panel = new JPanel();
label.setVisible(true);
panel.add(label);
panel.setPreferredSize(SIZE);
//ComputerPiece Stuff
ImageIcon computerIcon = new ImageIcon("computerPiece.png");
computerPanel = new JPanel();
computerLabel = new JLabel(computerIcon);
computerLabel.setVisible(true);
computerPanel.add(computerLabel);
computerPanel.setPreferredSize(SIZE);
//===============================================
result = new Label("=========");
addKeyListener(this);
setSize(650,650);
up.addActionListener(this);
down.addActionListener(this);
start.addActionListener(this);
label.setSize(WIDTH,HEIGHT);
label.setLocation(0,0);
add(computerPanel);
add(panel);
add(start);
add(up);
add(down);
add(result);
}
//--------------------------------------
public void paint(Graphics g) {
Graphics2D firstLayer = (Graphics2D)g;
Graphics2D secondLayer = (Graphics2D)g;
Graphics2D thirdLayer = (Graphics2D)g;
secondLayer.setColor(Color.BLACK);
for(x=100; x<=500; x+=100)
for(y=100; y <=500; y+=100)
{
firstLayer.fillRect(x,y,WIDTH,HEIGHT);
}
for(w=150; w<=500; w+=100)
for(q=150; q <=500; q+=100)
{
secondLayer.fillRect(w,q,WIDTH,HEIGHT);
}
}
//--------------------------------------
public void actionPerformed(ActionEvent ae) {
int [] range = {50,0,0,0,0};
int selection = (int)Math.random()*5 ;
//~~~~~~~~~~~~~~~~~~~~~~~~~
//PlayerPositioning
zeroPosX = panel.getX();
zeroPosY = panel.getY();
xLeft = zeroPosX - 50;
xUp = zeroPosY - 50;
//ComputerPositioning
compZeroPosX = computerPanel.getX();
compZeroPosY = computerPanel.getY();
compXLeft = compZeroPosX - range[selection];
compXUp = compZeroPosY - range[selection];
//~~~~~~~~~~~~~~~~~~~~~~~~~~
Button user = (Button)ae.getSource();
//Starting the game
if(user.getLabel() == "Start") {
result.setText("=========");
//playersetup
label.setLocation(0,0);
panel.setLocation(300,500);
//============================
//npc setup
computerLabel.setLocation(0,0);
computerPanel.setLocation(500,300);
}
if(compZeroPosX >= 150) {
if(compZeroPosY >= 150) {
if(zeroPosX >= 150) {
if(zeroPosY >=150) {
if(user.getLabel() == "UP") {
panel.setLocation(zeroPosX,xUp);
}
else
computerPanel.setLocation(compZeroPosX,compXUp);
if(user.getLabel() == "LEFT") {
panel.setLocation(xLeft,zeroPosY);
}
else
computerPanel.setLocation(compXLeft,compZeroPosY);
if(panel.getX() < 150)
result.setText("GAME-OVER");
if(panel.getY() < 150)
result.setText("GAME-OVER");
}
}
}
}
}
#Override
public void keyPressed(KeyEvent kp) {
int keycode = kp.getKeyCode();
switch (keycode) {
case KeyEvent.VK_W:
panel.setLocation(xLeft,zeroPosY);
break;
}
}
#Override
public void keyReleased(KeyEvent kr) {
}
#Override
public void keyTyped(KeyEvent kt) {
}
}
Issues and suggestions:
You're mixing AWT (e.g., Applet, Button, Label) with Swing (e.g., JPanel, JLabel) dangerously and without need. Stick with Swing and get rid of all vestiges of AWT.
You're painting directly in a top-level window, here the Applet, a dangerous thing to do. Don't. Follow the Swing graphics tutorials and do your drawing in a JPanel's paintComponent method.
You're not calling the super method within your painting method override, another dangerous thing to do, and another indication that you're trying to do this without reading the important relevant tutorials.
Don't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
You're trying to directly set the location of a component such as a JPanel without regard for the layout managers. Don't do this. Instead move logical (non-component) entities and display the movement in your graphics.
You can find links to the Swing tutorials and to other Swing resources here: Swing Info
Later we can talk why you should avoid applets of all flavors...
Myself, I'd move ImageIcons around a grid of JLabels and not directly use a painting method at all. For example,
To see, run the following code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class Game2 extends JPanel {
private static final String CPU_PATH = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/"
+ "Gorilla-thinclient.svg/50px-Gorilla-thinclient.svg.png";
private static final String PERSON_PATH = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/"
+ "Emblem-person-blue.svg/50px-Emblem-person-blue.svg.png";
private static final int SQR_WIDTH = 50;
private static final int SIDES = 10;
private static final Dimension SQR_SIZE = new Dimension(SQR_WIDTH, SQR_WIDTH);
private static final Color DARK = new Color(149, 69, 53);
private static final Color LIGHT = new Color(240, 220, 130);
private JLabel[][] labelGrid = new JLabel[SIDES][SIDES];
private Icon playerIcon;
private Icon computerIcon;
public Game2() throws IOException {
// would use images instead
playerIcon = createIcon(PERSON_PATH);
computerIcon = createIcon(CPU_PATH);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new StartAction("Start", KeyEvent.VK_S)));
buttonPanel.add(new JButton(new UpAction("Up", KeyEvent.VK_U)));
buttonPanel.add(new JButton(new LeftAction("Left", KeyEvent.VK_L)));
JPanel gameBrd = new JPanel(new GridLayout(SIDES, SIDES));
gameBrd.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for (int i = 0; i < labelGrid.length; i++) {
for (int j = 0; j < labelGrid[i].length; j++) {
JLabel label = new JLabel();
label.setPreferredSize(SQR_SIZE);
label.setOpaque(true);
Color c = i % 2 == j % 2 ? DARK : LIGHT;
label.setBackground(c);
gameBrd.add(label);
labelGrid[i][j] = label;
}
}
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.PAGE_START);
add(gameBrd);
// random placement, just for example
labelGrid[4][4].setIcon(computerIcon);
labelGrid[5][5].setIcon(playerIcon);
}
private Icon createIcon(String path) throws IOException {
URL url = new URL(path);
BufferedImage img = ImageIO.read(url);
return new ImageIcon(img);
}
private abstract class MyAction extends AbstractAction {
public MyAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
}
private class StartAction extends MyAction {
public StartAction(String name, int mnemonic) {
super(name, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO start game code
}
}
// move all icons up
private class UpAction extends MyAction {
public UpAction(String name, int mnemonic) {
super(name, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// collection to hold label that needs to be moved
Map<JLabel, Icon> labelMap = new HashMap<>();
for (int i = 0; i < labelGrid.length; i++) {
for (int j = 0; j < labelGrid[i].length; j++) {
Icon icon = labelGrid[i][j].getIcon();
if (icon != null) {
int newI = i == 0 ? labelGrid.length - 1 : i - 1;
labelGrid[i][j].setIcon(null);
labelMap.put(labelGrid[newI][j], icon);
}
}
}
// move the icon after the iteration complete so as not to move it twice
for (JLabel label : labelMap.keySet()) {
label.setIcon(labelMap.get(label));
}
}
}
// move all icons left
private class LeftAction extends MyAction {
public LeftAction(String name, int mnemonic) {
super(name, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Map<JLabel, Icon> labelMap = new HashMap<>();
for (int i = 0; i < labelGrid.length; i++) {
for (int j = 0; j < labelGrid[i].length; j++) {
Icon icon = labelGrid[i][j].getIcon();
if (icon != null) {
int newJ = j == 0 ? labelGrid[i].length - 1 : j - 1;
labelGrid[i][j].setIcon(null);
labelMap.put(labelGrid[i][newJ], icon);
}
}
}
for (JLabel label : labelMap.keySet()) {
label.setIcon(labelMap.get(label));
}
}
}
private static void createAndShowGui() {
Game2 mainPanel = null;
try {
mainPanel = new Game2();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("Game2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}

Closeable JTabbedPane - alignment of the close button

I have implemented my own closeable JTabbedPane (essentially following advice from here - by extending JTabbedPane and overriding some methods and calling setTabComponentAt(...)). It works perfectly except one thing - when there are too many tabs to fit on one row (when there are 2 or more rows of tabs), the cross button/icon is not aligned to the right of the tab but it remains next to the tab title, which looks ugly. I've tried the demo from Java tutorials and it suffers from the same problem.
What I want is that the cross button/icon is always aligned to the very right, but the text is always aligned to the center. Can this be achieved by some layouting tricks? Note: I do not want to implement a custom TabbedPaneUI as this leads to other problems.
UPDATE I'm forced to use Java 6
The complete code is below, just run it and add 5 or more tabs.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/**
* CloseableTabbedPane is a tabbed pane with a close icon on the right side of all tabs making it possible to close a tab.
* You can pass an instance of TabClosingListener to one of the constructors to react to tab closing.
*
* #author WiR
*/
public class CloseableTabbedPane extends JTabbedPane {
public static interface TabClosingListener {
/**
* #param aTabIndex the index of the tab that is about to be closed
* #return true if the tab can be really closed
*/
public boolean tabClosing(int aTabIndex);
/**
* #param aTabIndex the index of the tab that is about to be closed
* #return true if the tab should be selected before closing
*/
public boolean selectTabBeforeClosing(int aTabIndex);
}
private TabClosingListener tabClosingListener;
private String iconFileName = "images/cross.gif";
private String selectedIconFileName = "images/cross_selected.gif";
private static Icon CLOSING_ICON;
private static Icon CLOSING_ICON_SELECTED;
private class PaintedCrossIcon implements Icon {
int size = 10;
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.drawLine(x, y, x + size, y + size);
g.drawLine(x + size, y, x, y + size);
}
#Override
public int getIconWidth() {
return size;
}
#Override
public int getIconHeight() {
return size;
}
}
public CloseableTabbedPane() {
super();
}
public CloseableTabbedPane(TabClosingListener aTabClosingListener) {
super();
tabClosingListener = aTabClosingListener;
}
/**
* Sets the file name of the closing icon along with the optional variant of the icon when the mouse is over the icon.
*/
public void setClosingIconFileName(String aIconFileName, String aSelectedIconFileName) {
iconFileName = aIconFileName;
selectedIconFileName = aSelectedIconFileName;
}
/**
* Makes the close button at the specified indes visible or invisible
*/
public void setCloseButtonVisibleAt(int aIndex, boolean aVisible) {
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(aIndex);
cbt.closingLabel.setVisible(aVisible);
}
#Override
public void insertTab(String title, Icon icon, Component component, String tip, int index) {
super.insertTab(title, icon, component, tip, index);
setTabComponentAt(index, new CloseButtonTab(component, title, icon));
}
#Override
public void setTitleAt(int index, String title) {
super.setTitleAt(index, title);
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
cbt.label.setText(title);
}
#Override
public void setIconAt(int index, Icon icon) {
super.setIconAt(index, icon);
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
cbt.label.setIcon(icon);
}
#Override
public void setComponentAt(int index, Component component) {
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
super.setComponentAt(index, component);
cbt.tab = component;
}
//note: setToolTipTextAt(int) must NOT be overridden !
private Icon getImageIcon(String aImageName) {
URL imageUrl = CloseableTabbedPane.class.getClassLoader().getResource(aImageName);
if (imageUrl == null) {
return new PaintedCrossIcon();
}
ImageIcon result = new ImageIcon(imageUrl);
if (result.getIconWidth() != -1) {
return result;
} else {
return null;
}
}
private class CloseButtonTab extends JPanel {
private Component tab;
private JLabel label;
private JLabel closingLabel;
public CloseButtonTab(Component aTab, String aTitle, Icon aIcon) {
tab = aTab;
setOpaque(false);
setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 0, 0, 5);
label = new JLabel(aTitle);
label.setIcon(aIcon);
add(label, gbc);
if (CLOSING_ICON == null) {
CLOSING_ICON = getImageIcon(iconFileName);
CLOSING_ICON_SELECTED = getImageIcon(selectedIconFileName);
}
closingLabel = new JLabel(CLOSING_ICON);
closingLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent();
int tabIndex = indexOfComponent(tab);
if (tabClosingListener != null) {
if (tabClosingListener.selectTabBeforeClosing(tabIndex)) {
tabbedPane.setSelectedIndex(tabIndex);
}
if (tabClosingListener.tabClosing(tabIndex)) {
tabbedPane.removeTabAt(tabIndex);
}
} else {
tabbedPane.removeTabAt(tabIndex);
}
}
#Override
public void mouseEntered(MouseEvent e) {
if (CLOSING_ICON_SELECTED != null) {
closingLabel.setIcon(CLOSING_ICON_SELECTED);
}
}
#Override
public void mouseExited(MouseEvent e) {
if (CLOSING_ICON_SELECTED != null) {
closingLabel.setIcon(CLOSING_ICON);
}
}
});
gbc.insets = new Insets(0, 0, 0, 0);
add(closingLabel, gbc);
}
}
static int count = 0;
/**
* For testing purposes.
*
*/
public static void main(String[] args) {
final JTabbedPane tabbedPane = new CloseableTabbedPane();
tabbedPane.addTab("test" + count, new JPanel());
count++;
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(tabbedPane, BorderLayout.CENTER);
JButton addButton = new JButton("Add tab");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test" + count, new JPanel());
count++;
}
});
mainPanel.add(addButton, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
frame.getContentPane().add(mainPanel);
frame.setVisible(true);
}
}
Here is one possible implementation using JLayer:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class CloseableTabbedPaneTest {
public JComponent makeUI() {
UIManager.put("TabbedPane.tabInsets", new Insets(2, 2, 2, 50));
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("aaaaaaaaaaaaaaaa", new JPanel());
tabbedPane.addTab("bbbbbbbb", new JPanel());
tabbedPane.addTab("ccc", new JPanel());
JPanel p = new JPanel(new BorderLayout());
p.add(new JLayer<JTabbedPane>(tabbedPane, new CloseableTabbedPaneLayerUI()));
p.add(new JButton(new AbstractAction("add tab") {
#Override public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test", new JPanel());
}
}), BorderLayout.SOUTH);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new CloseableTabbedPaneTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class CloseableTabbedPaneLayerUI extends LayerUI<JTabbedPane> {
private final JPanel p = new JPanel();
private final Point pt = new Point(-100, -100);
private final JButton button = new JButton("x") {
#Override public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
};
public CloseableTabbedPaneLayerUI() {
super();
button.setBorder(BorderFactory.createEmptyBorder());
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setRolloverEnabled(false);
}
#Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
JLayer jlayer = (JLayer) c;
JTabbedPane tabPane = (JTabbedPane) jlayer.getView();
for (int i = 0; i < tabPane.getTabCount(); i++) {
Rectangle rect = tabPane.getBoundsAt(i);
Dimension d = button.getPreferredSize();
int x = rect.x + rect.width - d.width - 2;
int y = rect.y + (rect.height - d.height) / 2;
Rectangle r = new Rectangle(x, y, d.width, d.height);
button.setForeground(r.contains(pt) ? Color.RED : Color.BLACK);
SwingUtilities.paintComponent(g, button, p, r);
}
}
}
#Override public void installUI(JComponent c) {
super.installUI(c);
((JLayer)c).setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
#Override public void uninstallUI(JComponent c) {
((JLayer)c).setLayerEventMask(0);
super.uninstallUI(c);
}
#Override protected void processMouseEvent(MouseEvent e, JLayer<? extends JTabbedPane> l) {
if (e.getID() == MouseEvent.MOUSE_CLICKED) {
pt.setLocation(e.getPoint());
JTabbedPane tabbedPane = (JTabbedPane) l.getView();
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
Rectangle rect = tabbedPane.getBoundsAt(index);
Dimension d = button.getPreferredSize();
int x = rect.x + rect.width - d.width - 2;
int y = rect.y + (rect.height - d.height) / 2;
Rectangle r = new Rectangle(x, y, d.width, d.height);
if (r.contains(pt)) {
tabbedPane.removeTabAt(index);
}
}
l.getView().repaint();
}
}
#Override protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends JTabbedPane> l) {
pt.setLocation(e.getPoint());
JTabbedPane tabbedPane = (JTabbedPane) l.getView();
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
tabbedPane.repaint(tabbedPane.getBoundsAt(index));
} else {
tabbedPane.repaint();
}
}
}
Edit:
Here is an example using a GlassPane(Note: this is NOT tested at all):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CloseableTabbedPaneTest2 {
public JComponent makeUI() {
UIManager.put("TabbedPane.tabInsets", new Insets(2, 2, 2, 50));
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("aaaaaaaaaaaaaaaa", new JPanel());
tabbedPane.addTab("bbbbbbbb", new JPanel());
tabbedPane.addTab("ccc", new JPanel());
JPanel p = new JPanel(new BorderLayout());
//p.setBorder(BorderFactory.createLineBorder(Color.RED, 10));
p.add(tabbedPane);
p.add(new JButton(new AbstractAction("add tab") {
#Override public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test", new JScrollPane(new JTree()));
}
}), BorderLayout.SOUTH);
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
JPanel gp = new CloseableTabbedPaneGlassPane(tabbedPane);
tabbedPane.getRootPane().setGlassPane(gp);
gp.setOpaque(false);
gp.setVisible(true);
}
});
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new CloseableTabbedPaneTest2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class CloseableTabbedPaneGlassPane extends JPanel {
private final Point pt = new Point(-100, -100);
private final JButton button = new JButton("x") {
#Override public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
};
private final JTabbedPane tabbedPane;
private final Rectangle buttonRect = new Rectangle(button.getPreferredSize());
public CloseableTabbedPaneGlassPane(JTabbedPane tabbedPane) {
super();
this.tabbedPane = tabbedPane;
MouseAdapter h = new Handler();
tabbedPane.addMouseListener(h);
tabbedPane.addMouseMotionListener(h);
button.setBorder(BorderFactory.createEmptyBorder());
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setRolloverEnabled(false);
}
#Override public void paintComponent(Graphics g) {
Point glassPt = SwingUtilities.convertPoint(tabbedPane, 0, 0, this);
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
Rectangle tabRect = tabbedPane.getBoundsAt(i);
int x = tabRect.x + tabRect.width - buttonRect.width - 2;
int y = tabRect.y + (tabRect.height - buttonRect.height) / 2;
buttonRect.setLocation(x, y);
button.setForeground(buttonRect.contains(pt) ? Color.RED : Color.BLACK);
buttonRect.translate(glassPt.x, glassPt.y);
SwingUtilities.paintComponent(g, button, this, buttonRect);
}
}
class Handler extends MouseAdapter {
#Override public void mouseClicked(MouseEvent e) {
pt.setLocation(e.getPoint());
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
Rectangle tabRect = tabbedPane.getBoundsAt(index);
int x = tabRect.x + tabRect.width - buttonRect.width - 2;
int y = tabRect.y + (tabRect.height - buttonRect.height) / 2;
buttonRect.setLocation(x, y);
if (buttonRect.contains(pt)) {
tabbedPane.removeTabAt(index);
}
}
tabbedPane.repaint();
}
#Override public void mouseMoved(MouseEvent e) {
pt.setLocation(e.getPoint());
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
tabbedPane.repaint(tabbedPane.getBoundsAt(index));
} else {
tabbedPane.repaint();
}
}
}
}
I'm using this one: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
The close button is painted by this itself so if can be placed anywhere.

Clicking on the search button in JFrame is not opening the JDialog

I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)

Creating a selectable jpanel of jpanels containing images

After saving some images from a site into an ArrayList i am trying to create a jpanel which will display all these images in seperate jpanels with a scrollpane so that i can add action events to each. The user will then be able to select a jpanel with the relevant picture and click a "copy" button to save this image to the clipboard.
The following code works fine to add one picture:
picHolder = new JPanel();
picHolder.setSize(50,450);
picHolder.setBackground(Color.white);
Icon testicon = new ImageIcon(imageList.get(0));
JPanel test = new JPanel();
JLabel testLabel = new JLabel();
testLabel.setIcon(testicon);
test.add(testLabel);
picHolder.add(test);
however when i try to create panels within panels by using the following loop:
panelArray = new JPanel[imageList.size()];
labelArray = new JLabel[imageList.size()];
imageArray = new ImageIcon[imageList.size()];
for (int x=0; x>imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
panelArray[x] = new JPanel();
panelArray[x].setBackground(Color.red);
labelArray[x] = new JLabel();
labelArray[x].setIcon(imageArray[x]);
panelArray[x].setLayout(new FlowLayout());
panelArray[x].add(labelArray[x]);
picHolder.add(panelArray[x]);
picHolder.validate();
picHolder.repaint();
}
I get only a blank screen. I have tried moving various elements around however i cannot see what i am doing wrong. If anyone has any suggestions or perhaps an alternative way of achieving my objective it would be greatly appreciated.
Edit
SSCCE
package scrollbartester;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.Selector;
import java.net.*;
import javax.imageio.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.Event;
import javax.swing.*;
public class ScrollBarTester {
ArrayList<Image> imageList = new ArrayList<Image>() ;
URL url;
public ArrayList ripPics() {
String fullST = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=fish&x=0&y=0";
try {
Document doc = Jsoup.connect(fullST).timeout(10*1000).get();
Elements jpgs = doc.select("img[src$=.jpg]");
Element pictest = jpgs.get((jpgs.size()-1));
System.out.println(pictest);
for (int countPics = 0; countPics < jpgs.size(); countPics++) {
Element currentPic = jpgs.get(countPics);
String currentPicString = currentPic.toString();
System.out.println(currentPicString);
int startofAddress = currentPicString.indexOf("http:");
int endofAddress = (currentPicString.indexOf(".jpg") + 4);
String urlOfImage = currentPicString.substring(startofAddress, endofAddress);
url = new URL(urlOfImage);
Image currentImage = ImageIO.read(url);
imageList.add(currentImage);
}
}catch (MalformedURLException e) {
} catch (Exception e) {
e.printStackTrace();
}
return imageList;
}
public static void main(String[] args) {
PicRipper ripper = new PicRipper();
ArrayList<Image> imageList = ripper.ripPics();
System.out.println(imageList.size());
JScrollPane scrollPane;
JFrame main = new JFrame();
main.setSize(50, 500);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
JPanel picHolder = new JPanel();
picHolder.setSize(450,450);
picHolder.setBackground(Color.white);
//Icon testicon = new ImageIcon(imageList.get(0));
//JPanel test = new JPanel();
//JLabel testLabel = new JLabel();
//testLabel.setIcon(testicon);
//test.add(testLabel);
//picHolder.add(test);
JPanel [] panelArray = new JPanel[imageList.size()];
JLabel [] labelArray = new JLabel[imageList.size()];
ImageIcon [] imageArray = new ImageIcon[imageList.size()];
for (int x=0; x>imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
panelArray[x] = new JPanel();
panelArray[x].setBackground(Color.red);
labelArray[x] = new JLabel();
labelArray[x].setIcon(imageArray[x]);
panelArray[x].setLayout(new FlowLayout());
panelArray[x].add(labelArray[x]);
picHolder.add(panelArray[x]);
picHolder.validate();
picHolder.repaint();
}
scrollPane = new JScrollPane(picHolder);
main.getContentPane().add(BorderLayout.CENTER, scrollPane);
main.setVisible(true);
}
}
For example a SSCCE that uses a JList -- which can hold ImageIcons:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PicStrip extends JPanel {
public static final String[] IMAGE_URLS = {
"http://upload.wikimedia.org/wikipedia/commons/6/63/Lagavulin_-_entrance.JPG",
"http://upload.wikimedia.org/wikipedia/commons/1/1d/Parliament-Ottawa_edit1.jpg",
"http://upload.wikimedia.org/wikipedia/commons/b/b0/100OLYMP1.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/17/Arpino_panorama.jpg",
"http://upload.wikimedia.org/wikipedia/commons/a/ad/Cegonha_alsaciana.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/18/Eau_transparente_naturelle.JPG",
"http://upload.wikimedia.org/wikipedia/commons/4/4d/FA-18F_Breaking_SoundBarrier.jpg",
"http://upload.wikimedia.org/wikipedia/commons/5/58/PuntadelEste.jpg",
"http://upload.wikimedia.org/wikipedia/commons/3/3c/Punta_Gorda_Belize-gm.jpg",
"http://upload.wikimedia.org/wikipedia/commons/6/64/Yungangshiku.JPG",
"http://upload.wikimedia.org/wikipedia/commons/e/e2/Wheel_of_Konark%2C_Orissa%2C_India.JPG",
"http://upload.wikimedia.org/wikipedia/commons/1/16/Muretto_a_secco.jpg",
"http://upload.wikimedia.org/wikipedia/commons/3/31/Mercedes_AMG_CLS_55_-_Demonstration_of_drifting_1a_1280x960.jpg",
"http://upload.wikimedia.org/wikipedia/commons/d/d3/Cascade_carieul_1280x960.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/17/Bobbahn_ep.jpg"
};
private ImageIcon[] icons = new ImageIcon[IMAGE_URLS.length];
private DefaultListModel iconListModel = new DefaultListModel();
private JList iconList = new JList(iconListModel);
private ImagePanel imagePanel = new ImagePanel();
public PicStrip() {
setLayout(new BorderLayout());
add(new JScrollPane(iconList), BorderLayout.LINE_START);
add(imagePanel, BorderLayout.CENTER);
new SwingWorker<Void, ImageIcon>() {
#Override
protected Void doInBackground() throws Exception {
for (String imageUrl : IMAGE_URLS) {
BufferedImage img = ImageIO.read(new URL(imageUrl));
img = ImageUtil.createScaledImage(img);
ImageIcon icon = new ImageIcon(img, imageUrl);
publish(icon);
}
return null;
}
protected void process(java.util.List<ImageIcon> chunks) {
for (ImageIcon icon : chunks) {
iconListModel.addElement(icon);
}
};
protected void done() {
Window win = SwingUtilities.getWindowAncestor(PicStrip.this);
win.pack();
};
}.execute();
iconList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
iconList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
ImageIcon icon = (ImageIcon)iconList.getSelectedValue();
final String imageUrl = icon.getDescription();
new SwingWorker<BufferedImage, Void>() {
protected BufferedImage doInBackground() throws Exception {
return ImageIO.read(new URL(imageUrl));
};
#Override
protected void done() {
try {
imagePanel.setImage(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
}
});
}
private static void createAndShowGui() {
PicStrip mainPanel = new PicStrip();
JFrame frame = new JFrame("PicStrip");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ImagePanel extends JPanel {
private static final int PREF_W = (3 * 1280) / 4;
private static final int PREF_H = (3 * 960) / 4;
private BufferedImage img = null;
public void setImage(BufferedImage img) {
this.img = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img == null) {
return;
}
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, PREF_W, PREF_H, null);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}
class ImageUtil {
public static final int DEST_WIDTH = 100;
public static final int DEST_HEIGHT = 75;
public static final double ASPECT_RATIO = (double) DEST_WIDTH / DEST_HEIGHT;
public static BufferedImage createScaledImage(BufferedImage original) {
double origAspectRatio = (double) original.getWidth()
/ original.getHeight();
double scale = origAspectRatio > ASPECT_RATIO ?
(double) DEST_WIDTH / original.getWidth() :
(double) DEST_HEIGHT / original.getHeight();
int newW = (int) (original.getWidth() * scale);
int newH = (int) (original.getHeight() * scale);
BufferedImage img = new BufferedImage(DEST_WIDTH, DEST_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(original, 0, 0, newW, newH, null);
g2.dispose();
return img;
}
}
Edit 1
I've checked your SSCCE -- thanks for posting it, and one problem I found was a faulty for-loop. Try changing this:
for (int x = 0; x > imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
//....
}
to this:
for (int x = 0; x < imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
//....
}
I'm not sure if this is a bug in your actual program or if it's just a bug in the SSCCE, but it is critical.

Categories