I am trying to make a button change its position once clicked. I have read that in order to set my components' positions manually. Thus I declared the default layout manager of my Frame as null. However my button's remains the same although the debugger tell me I am getting new (x, y) each time the button is clicked. Here is my source code :
Class GameUI.java :
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import de.tk1.g4.ta1.model.Player;
public class GameUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private String header[] = new String[]{"Player", "Score"};
private JTable table = new JTable();
private DefaultTableModel model = (DefaultTableModel) table.getModel();
private JPanel sidePanel = new JPanel();
private ImagePanel bodyPanel = new ImagePanel();
public GameUI() {
model.setColumnIdentifiers(header);
table.setEnabled(false);
getContentPane().setLayout(null);
getContentPane().add(sidePanel);
getContentPane().add(bodyPanel);
sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS));
sidePanel.add(table);
sidePanel.add(Box.createHorizontalStrut(10));
sidePanel.setBounds(0, 0, 300, 500);
bodyPanel.setBounds(300, 0, 700, 500);
setMaximumSize(new Dimension(700 + 300, 500));
setPreferredSize(new Dimension(700 + 300, 500));
setResizable(false);
super.paintComponents(getGraphics());
this.pack();
}
public void addPlayerToList (Player thePlayer) {
model.addRow(new Object[]{thePlayer.getName(), thePlayer.getScore()});
super.paintComponents(getGraphics());
}
public void clearPlayersTable() {
while(model.getRowCount() > 0)
{
model.removeRow(0);
}
}
public void setPokemonLocation (int x, int y) {
bodyPanel.getBtnPokemon().setLocation(x, y);
//repaint();
}
public JButton getPokButton () {
return bodyPanel.getBtnPokemon();
}
public ImagePanel getBodyPanel() {
return bodyPanel;
}
public void setBodyPanel(ImagePanel bodyPanel) {
this.bodyPanel = bodyPanel;
}
public void setImage(String path) throws IOException {
try {
FileInputStream fis = new FileInputStream(new File(path));
Image img = ImageIO.read(fis);
bodyPanel.getBtnPokemon().setIcon(new ImageIcon(img));
}catch(IOException e){
e.printStackTrace();
System.out.println(path);
}
}
public void setPokButton(int x,int y,String path) {
bodyPanel.setImage(path);
bodyPanel.getBtnPokemon().setLocation(x, y);
}
public void addPokemonListener(ActionListener listenForPokemon) {
bodyPanel.getBtnPokemon().addActionListener(listenForPokemon);
}
#Override
public void actionPerformed(ActionEvent e) {
super.paintComponents(getGraphics());
}
}
Class ImagePanel.java :
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private JButton btnPokemon = new JButton("");
private BufferedImage image;
public ImagePanel() {
super();
this.setBorder(BorderFactory.createTitledBorder(""));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setMaximumSize(new Dimension(700, 450));
this.setMinimumSize(new Dimension(700, 450));
this.add(btnPokemon);
}
#Override
public void paintComponent(Graphics g) {
if (g != null && image != null) {
super.paintComponent(g);
g.drawImage(image, btnPokemon.getX(), btnPokemon.getY(), null);
}
}
#Override
public void actionPerformed(ActionEvent e) {
super.paintComponents(getGraphics());
}
public void setImage(String path) {
try {
this.image = ImageIO.read(new File(path));
btnPokemon.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
}
}
public JButton getBtnPokemon() {
return btnPokemon;
}
public void setBtnPokemon(JButton btnPokemon) {
this.btnPokemon = btnPokemon;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
}
Although my controller calls this.gameUI.revalidate(); and this.gameUI.repaint();.
Any hints what I did miss in my source code please.
Related
Trying to add a keyListener to this component, however I am getting no response. I want it to be respond whenever the component is displayed in the scroll Panel. I've been able to get it to work when adding it to JPanels. Is there something I should be doing differently for my component?
This the the Component I seek to implement Keylistener on.
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.event.MouseInputListener;
import java.awt.FontMetrics;
import java.awt.event.MouseEvent;
import java.awt.Point;
import java.util.ArrayList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class PhotoComponent extends JComponent implements MouseInputListener{
private ImageIcon pic;
Boolean checkVac=false;
Boolean checkSchool=false;
Boolean checkFam= false;
Boolean checkWork = false;
Boolean flipped = false;
Boolean penButton=false;
boolean textButton=false;
public PhotoComponent(){
}
public PhotoComponent(ImageIcon p){
pic=p;
setRequestFocusEnabled(true);
requestFocus();
addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
System.out.println("hello");
}
});
}
#Override
public Dimension getPreferredSize(){
if(pic==null){
return new Dimension(0,0);
}
return new Dimension(pic.getIconWidth(), pic.getIconHeight());
}
#Override
protected void paintComponent(Graphics g){
pic.paintIcon(this, g, 0, 0);
}
}
This is the program I am calling it on.
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.MouseInputListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.io.*;
public class Base extends JFrame {
private JPanel statusContainer;
private JScrollPane scrollPane;
private JMenuBar jmb;
private JMenu file;
private JMenuItem importbutton;
private ArrayList<PhotoComponent> picList;
private int picIndex;
public static void main(String[] args) {
new Base();
}
public Base(){
setTitle("Placeholder");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setResizable(true);
mainProgram();
pack();
setVisible(true);
}
public void mainProgram(){
jmb = new JMenuBar();
setJMenuBar(jmb);
file=new JMenu("File");
statusContainer = new JPanel();
add(statusContainer, BorderLayout.SOUTH);
jmb.add(file);
importbutton = new JMenuItem("Import");
//currentPic= new PhotoComponent();
picList= new ArrayList<PhotoComponent>(5);
picIndex = 0;
scrollPane = new JScrollPane();
add(scrollPane);
importbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent fo){
JFileChooser chooser= new JFileChooser("");
FileFilter filter = new FileNameExtensionFilter("Graphics", "jpg","jpeg","png");
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);
int response = chooser.showOpenDialog(null);
if(response == JFileChooser.APPROVE_OPTION){
File[] chosen = chooser.getSelectedFiles();
for (File f:chosen) {
if(f.isDirectory()){
File[] temp=f.listFiles();
for (File x:temp){;
ImageIcon ii =new ImageIcon(x.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
else{
ImageIcon ii =new ImageIcon(f.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
scrollPane.setViewportView(picList.get(picIndex));
///mainScroll.addMouseListener(picList.get(pos));
scrollPane.setVisible(true);
validate();
}
else {
JOptionPane.showInputDialog("oops somethings wrong");
}
}
});
file.add(importbutton);
}
}
Ther're many ways how to solve this problem. One of them use KeyEventDispatcher if you need some global key mappings.
Another way is to add KeyListener to you parent JFrame to catch key pressed event and delegate it to the current component. Check this out!
P.S. I am not saying that this is an optimal solution, but I have checked it - it works. You can use it or it can be a start point for your own solution.
public class Base extends JFrame implements ActionListener, KeyListener {
private final JPanel statusContainer = new JPanel();
private final JScrollPane scrollPane = new JScrollPane();
private final JMenuBar menubar = new JMenuBar();
private final JMenu file = new JMenu("File");
private final JMenuItem importButton = new JMenuItem("Import");
private List<PhotoComponent> pictures = Collections.emptyList();
private int pictureIndex = -1;
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new Base().setVisible(true));
}
public Base() {
init();
}
private void init() {
setTitle("Placeholder");
setJMenuBar(menubar);
add(statusContainer, BorderLayout.SOUTH);
add(scrollPane);
file.add(importButton);
menubar.add(file);
setResizable(true);
importButton.addActionListener(this);
addKeyListener(this);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == importButton)
onImportButton();
}
private void onImportButton() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Graphics", "jpg", "jpeg", "png"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setMultiSelectionEnabled(true);
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
pictures = getPictures(fileChooser);
pictureIndex = pictures.isEmpty() ? -1 : 0;
scrollPane.setViewportView(pictureIndex == -1 ? null : pictures.get(pictureIndex));
scrollPane.setVisible(true);
validate();
} else
JOptionPane.showInputDialog("oops somethings wrong");
}
private static List<PhotoComponent> getPictures(JFileChooser fileChooser) {
List<PhotoComponent> pictures = new ArrayList<>();
for (File fileOrDir : fileChooser.getSelectedFiles())
for (File file : getFiles(fileOrDir))
pictures.add(new PhotoComponent(new ImageIcon(file.getAbsolutePath())));
return pictures;
}
private static List<File> getFiles(File fileOrDir) {
if (fileOrDir.isDirectory())
return Arrays.asList(Objects.requireNonNull(fileOrDir.listFiles()));
return Collections.singletonList(fileOrDir);
}
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
if (pictureIndex != -1)
pictures.get(pictureIndex).keyPressed(event);
}
#Override
public void keyReleased(KeyEvent event) {
}
}
public class PhotoComponent extends JComponent {
private final ImageIcon picture;
public PhotoComponent(ImageIcon picture) {
this.picture = picture;
}
public void keyPressed(KeyEvent event) {
System.out.println("keyPressed: " + event.getKeyCode());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(picture.getIconWidth(), picture.getIconHeight());
}
#Override
protected void paintComponent(Graphics g) {
picture.paintIcon(this, g, 0, 0);
}
}
I want to fill a panel with a BufferedImage (striped, see link below) and print it on a printer. The thing is that the pattern doesn't print, but it is visible as wanted on the panel. If I use a color instead of the striped image this gets printed.
You see two comments in the paintComponent-method below. Any ideas why I don't see the BufferedImage when I print?
Thanks!
You can find the image used here: http://imgur.com/sSlVUzK
package printbufferedimagepanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO;
public class PrintBufferedImagePanel {
JFrame mainFrame;
JPanel mainPanel;
Buff printMe;
JButton printButton;
BufferedImage bf;
public PrintBufferedImagePanel() {
prepareGUI();
}
public static void main(String[] args) {
PrintBufferedImagePanel bip = new PrintBufferedImagePanel();
}
private void prepareGUI() {
mainFrame = new JFrame();
mainFrame.setLayout(new FlowLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
printMe = new Buff();
printButton = new JButton("Print");
mainPanel.setSize(400, 150);
mainPanel.add(printMe);
mainFrame.add(mainPanel);
mainFrame.add(printButton);
mainFrame.setSize(400, 250);
mainFrame.setVisible(true);
printButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(printMe);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException de) {
System.err.println("Oops!");
}
}
}
});
}
class Buff extends JPanel implements Printable {
#Override
public Dimension getPreferredSize() {
return new Dimension(400,150);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage bImage = null;
TexturePaint tp = null;
try {
bImage = ImageIO.read(new File("src/printbufferedimagepanel/blueStripes.jpg"));
tp = new TexturePaint(bImage, new Rectangle(0,0,bImage.getWidth(),bImage.getHeight()));
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(tp); //<-- doesn't show at print, Why?
//g2.setColor(Color.CYAN); //<-- does show at print
g2.fillRect(0, 0, 400, 150);
} catch (Exception e) {
System.out.println("oops");
}
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
this.printAll(graphics);
return PAGE_EXISTS;
}
}
}
I have a problem with the code that I wrote when I run it on Ubuntu. I want to create a transparent JFrame and add an image as a border. When I run the program on Windows is working properly, but when I run it on ubuntu not only the JFrame but also the image is transparent.
I'd like the program to work in both os. I tried with this code setOpacity(0.0f); too. But the outcame is the same.
Help me please T_T
Sorry but I don't have enough reputation to post images so I put them as links...
This is what i see on Ubuntu: http://oi57.tinypic.com/wgymag.jpg
and this is on Windows:http://oi60.tinypic.com/5o5if4.jpg
and this is the link to the frameImage: oi58.tinypic.com/2j2xrwy.jpg
Here are the two classes that I used:
MainClass:
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Window extends JFrame {
private final int width, height;
private ContainerPanel container;
public Window() {
this.width = 1024;
this.height = 688;
this.setSize(width, height);
this.setMaximumSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setResizable(false);
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0));
container = new ContainerPanel(Window.this, 1024, 688);
this.setContentPane(container);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
try {
} catch (Exception e1) {
System.exit(0);
e1.printStackTrace();
}
}
});
this.setVisible(true);
this.pack();
}
public static void main(String[] args) {
System.out.println("TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT));
System.out.println("PERPIXEL_TRANSPARENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSPARENT));
System.out.println("PERPIXEL_TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSLUCENT));
new Window();
}
}
and this is the class with the background image:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ContainerPanel extends JPanel {
private final Window window;
private JLabel label;
private Point mouseDownCompCoords, currentLocationOnScreen;
private final int windowWidth, windowHeight;
private int closeButtonPosX, closeButtonPosY;
private BufferedImage frameImg;
public ContainerPanel(Window window, int windowWidth, int windowHeight) {
this.window = window;
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
this.closeButtonPosX = 900;
this.closeButtonPosY = 19;
this.setLayout(null);
this.setOpaque(false);
this.setSize(this.windowWidth, this.windowHeight);
this.setMaximumSize(new Dimension(this.windowWidth, this.windowHeight));
this.setMinimumSize(new Dimension(this.windowWidth, this.windowHeight));
crateLabel();
try {
createButton();
frameImg = ImageIO.read(new File("Images/Frame/frame.png"));
} catch (IOException ex) {
Logger.getLogger(ContainerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.setVisible(true);
}
private void crateLabel() {
label = new JLabel();
final int labelHeight = 45;
label.setSize(windowWidth, labelHeight);
label.setMaximumSize(new Dimension(windowWidth, labelHeight));
label.setMinimumSize(new Dimension(windowWidth, labelHeight));
label.setLocation(0, 0);
label.setOpaque(false);
label.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
});
label.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
currentLocationOnScreen = e.getLocationOnScreen();
ContainerPanel.this.window.setLocation(currentLocationOnScreen.x - mouseDownCompCoords.x, currentLocationOnScreen.y - mouseDownCompCoords.y);
}
#Override
public void mouseMoved(MouseEvent e) {
//do nothing
}
});
label.setVisible(true);
this.add(label);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.drawImage(frameImg, 0, 0, windowWidth, windowHeight, null);
}
private void createButton() {
JButton close = new JButton("close");
close.setLocation(this.closeButtonPosX , this.closeButtonPosY);
close.setSize(100, 30);
close.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
label.add(close);
}
}
you can check this -> https://today.java.net/pub/a/today/2008/03/18/translucent-and-shaped-swing-windows.html by Kirill Grouchnikov.
I have created shaped JDialog by adding transparency effect by
setBackground(new Color(0, 0, 0, 0); but it also adding drag listener to the dialog internally, problem is, when we drag by any other component in the dialog such as JTextfield, JList etc,. still the complete window is able to drag. so need to avoid adding internal drag listener to the jdialog. please anybody help me regarding this, here is my code.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow extends JDialog {
private static final long serialVersionUID = 1L;
public MyWindow() {
JTextField text = new JTextField();
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("background.png"));
} catch (IOException e) {
}
JLabel label = new JLabel(new ImageIcon(myPicture));
setUndecorated(true);
setResizable(false);
setBackground(new Color(0, 0, 0, 0)); // creating issue
setSize(243, 474);
text.setBounds(18, 64, 212, 368);
add(text);
add(label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow win = new MyWindow();
win.setVisible(true);
}
});
}
}
Thanks in advance,
Regards,
Bharath SR
Not sure if I fully understand your requirements or even your problem, but it sounds like you want a draggable dialog with no frame, just a background image and a component, and you don't want the components to trigger the drag event.
Give this a try. Hopefully it's what you're looking for. Feel free to ask questions.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DragDialog extends JDialog {
private int pointX;
private int pointY;
public DragDialog() {
JLabel backgroundLabel = createBackgroundLabel();
JTextField textField = createTextField();
setContentPane(backgroundLabel);
add(textField);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private JTextField createTextField() {
final JTextField field = new JTextField(20);
field.setText("Type \"exit\" to terminate.");
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text = field.getText();
if ("exit".equalsIgnoreCase(text)) {
System.exit(0);
}
}
});
return field;
}
private JLabel createBackgroundLabel() {
Image image = null;
try {
image = ImageIO.read(new URL("http://satyajit.ranjeev.in/images/icons/stackoverflow.png"));
} catch (IOException ex) {
Logger.getLogger(DragDialog.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel(new ImageIcon(image));
label.setLayout(new GridBagLayout());
label.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
DragDialog.this.setLocation(DragDialog.this.getLocation().x + e.getX() - pointX,
DragDialog.this.getLocation().y + e.getY() - pointY);
}
});
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointX = e.getX();
pointY = e.getY();
}
});
return label;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DragDialog();
}
});
}
}
I want to achieve following functionality :
Eg :
When user selects "Profile Pic"item from JComboBox releted images from "Profile Pic" folder should be loaded on same frame.
Again when user selects "Product Img" item related images from "Product Img" folder should be loaded replacing previous images.
Following is code snippet , please suggest any changes
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NewClass1 {
public static void main(String[] args) {
createAndShowJFrame();
}
public static void createAndShowJFrame() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = createJFrame();
frame.setVisible(true);
}
});
}
private static JFrame createJFrame() {
JFrame frame = new JFrame();
//frame.setResizable(false);//make it un-resizeable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
ArrayList<BufferedImage> images = null;
try {
images = getImagesArrayList();
} catch (Exception ex) {
ex.printStackTrace();
}
final ImageViewPanel imageViewPanel = new ImageViewPanel(images);
JScrollPane jsp = new JScrollPane(imageViewPanel);
jsp.setPreferredSize(new Dimension(400, 400));
frame.add(jsp);
final javax.swing.JComboBox filter = new javax.swing.JComboBox<>();
filter.addItem("All");
filter.addItem("Profile Pic");
filter.addItem("Company Logo");
filter.addItem("Product Img");
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
JLabel label =new JLabel("Filter By :");
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
controlPanel.add(addLabelButton);
controlPanel.add(label);
controlPanel.add(filter);
frame.add(controlPanel, BorderLayout.NORTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList(String cat) throws Exception {
System.out.println(cat);
ArrayList<BufferedImage> images = new ArrayList<>();
if(cat.equals("Profile Pic"))
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProfilePic/1.jpg")), 100, 100));
else if(cat.equals("Product Img"))
{
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProductImg/2.jpg")), 100, 100));
}
return images;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/a.jpg")), 100, 100));
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/b.jpg")), 100, 100));
return images;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
I would urge you to have another look at the code I posted (which you seem to be using) Deleting images from JFrame.
However:
In your code I see:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
I cannot even find the method createJFrame(String cat);?
As far as I see you should be doing this:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
ArrayList<BufferedImage> images=getImagesArrayList(cat);//get the new images for the selected item in combo
//refresh the layout by removing old pics and itertating the new array and adding pics to the panel as you iterate
layoutLabels(images);
}
});
....
private JLabel NO_IMAGES=new JLabel("No Images");
private void layoutLabels(ArrayList<BufferedImage> images) {
removeAll();//remove all components from our panel (the panel should only have the images on if not use setActionCommand("Image") on your images/JLabels and than use getComponents of JPanel and iterate through them looking for getActionCommand.equals("Image")
if (images.isEmpty()) {//if the list is empty
add(NO_IMAGES);//add Jlabel to show message of no images
} else {
remove(NO_IMAGES);
for (BufferedImage i : images) {//iterate through ArrayList of images
add(new JLabel(new ImageIcon(i)));//add each to the panel using JLabel as container for image
}
}
revalidate();
repaint();
}