JFrame how should I do it (picture included)? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Currently I'm experincing with things that related to GUI making in Java and I want to try and make GUI that will look as follow :
How do you suggest to do it?
At first I though making class called "My Frame" it'll contain an array that holds the points of each polygon (so each polygon will be a separate frame).
But after rethinking a bit I thought of the purpose of those triangles, I want to make them buttons where each press on one of the button changes the content inside the Octagon, so it's more like the triangles are sort of buttons and the Octagon itself is the content pane, so how do you guys suggest me to achieve this?
Also another related question is that I want to make those triangles move with the Octagon, if the Octagon is being dragged by the mouse, the triangles will move with it as well so should I just parent them to the Octagon frame?
Another thing that I wanted to ask is since I set the frame to be undecorated for the purpose of changing it's shape I eliminated the option to resize the frame as well as I made the iconify and close buttons to disappear, so how can I add those features back, I searched the web but I didn't find any explanation to this.
EDITED DIALOG CLASS :
package rt;
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.ContainerListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
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.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public class MyDialog extends JDialog {
private int pointX;
private int pointY;
JLabel octagonLabel;
JLabel triangleAboutLabel;
MyMouseInputAdapter mmia;
public MyDialog() {
octagonLabel = createOctagonLabel();
triangleAboutLabel = createTriangleAboutLabel();
JTextField textField = createTextField();
setContentPane(octagonLabel);
add(textField);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
mmia = new MyMouseInputAdapter();
addMouseListener(mmia);
addMouseMotionListener(mmia);
setVisible(true);
}
private JTextField createTextField() {
final JTextField field = new JTextField(20);
field.setText("Type \"exit\" to terminate.");
field.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String text = field.getText();
if ("exit".equalsIgnoreCase(text)) {
System.exit(0);
}
}
});
return field;
}
private JLabel createOctagonLabel() {
Image image = null;
try {
image = ImageIO.read(Class.class.getResourceAsStream("/resources/gui/octagon.png"));
} catch (IOException ex) {
Logger.getLogger(MyDialog.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel(new ImageIcon(image));
label.setLayout(new GridBagLayout());
return label;
}
private JLabel createTriangleAboutLabel() {
Image image = null;
try {
image = ImageIO.read(Class.class.getResourceAsStream("/resources/gui/triangle_about.png"));
} catch (IOException ex) {
Logger.getLogger(MyDialog.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel(new ImageIcon(image));
label.setLayout(new GridBagLayout());
label.setLocation(octagonLabel.getLocation().x - 32, octagonLabel.getLocation().y - 32);
return label;
}
private class MyMouseInputAdapter extends MouseInputAdapter {
#Override
public void mouseDragged(MouseEvent e) {
MyDialog.this.setLocation(MyDialog.this.getLocation().x + e.getX() - pointX, MyDialog.this.getLocation().y + e.getY() - pointY);
}
#Override
public void mousePressed(MouseEvent e) {
pointX = e.getX();
pointY = e.getY();
}
}
}
LATEST EDIT :
#peeskillet sorry for not being here the last couple of days, family member was in hospital .. I tried to implement what you said I made different mouse listener for the corner triangles, but I came across a problem, the mouseEntered and MouseExited events get called when the mouse position is withing the BORDER of the label (not the polygon) so if I enter the mouse into the borders of the label (but the position of the mouse is still outside of the polygon) and then I decide to move the mouse (while I'm still inside the borders of the label) inside the polygon's borders it won't check if it's inside since mouseEntered have already been called and the check for the point inside of the polygon is taking place in that method (same issue for mouseExited) so I tried instead of overriding the mouseEntered and mouseExited doing my own methods just called them mouseEntered2 and mouseExited2 and I call them every time the mouse moves with mouseMoves event, but after doing it when i move the mouse it doesnt even get called the mouseMoved event and I don't know why.. here's the code :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Polygon;
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.util.HashMap;
import java.util.Map;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DragDialog extends JDialog {
private int pointX;
private int pointY;
public DragDialog() {
JTextField textField = createTextField();
setContentPane(createBackgroundPanel());
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel createBackgroundPanel() {
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(527, 527);
}
};
panel.setOpaque(false);
panel.setLayout(null);
String[] filePaths = getFilePaths();
Map<String, ImageIcon> imageMap = initImages(filePaths);
Map<String, Rectangle> rectMap = createRectangles();
Map <String, Polygon> polygonMap = createPolygons();
for (Map.Entry<String, Rectangle> entry: rectMap.entrySet()) {
JLabel label = new JLabel();
label.setOpaque(false);
String fullImageKey = entry.getKey() + "-default";
ImageIcon icon = imageMap.get(fullImageKey);
label.setIcon(icon);
label.setBounds(entry.getValue());
if (entry.getKey().equals("northwest") ||
entry.getKey().equals("northeast") ||
entry.getKey().equals("southwest") ||
entry.getKey().equals("southeast")) {
label.addMouseListener(new CornerLabelMouseListener(entry.getKey(), imageMap, polygonMap.get(entry.getKey())));
}
else {
label.addMouseListener(new SideLabelMouseListener(entry.getKey(), imageMap));
}
panel.add(label);
}
JLabel octagon = createOctagonLabel();
octagon.setBounds(85, 85, 357, 357);
panel.add(octagon);
return panel;
}
private Map<String, Rectangle> createRectangles() {
Map<String, Rectangle> rectMap = new HashMap<>();
rectMap.put("north", new Rectangle(191, 0, 145, 73));
rectMap.put("northwest", new Rectangle(74, 74, 103, 103));
rectMap.put("northeast", new Rectangle(348, 74, 103, 103));
rectMap.put("west", new Rectangle(0, 190, 73, 145));
rectMap.put("east", new Rectangle(453, 190, 73, 145));
rectMap.put("south", new Rectangle(190, 453, 145, 73));
rectMap.put("southwest", new Rectangle(74, 348, 103, 103));
rectMap.put("southeast", new Rectangle(349, 349, 103, 103));
return rectMap;
}
private Map <String, Polygon> createPolygons() {
Map <String, Polygon> polygonMap = new HashMap <> ();
int [] x = new int[3];
int [] y = new int [3];
x[0] = 0;
x[1] = 103;
x[2] = 0;
y[0] = 0;
y[1] = 0;
y[2] = 103;
polygonMap.put("northwest", new Polygon(x, y, 3));
x[2] = 103;
polygonMap.put("northeast", new Polygon(x, y, 3));
y[0] = 103;
polygonMap.put("southeast", new Polygon(x, y, 3));
x[1] = 0;
polygonMap.put("southwest", new Polygon(x, y, 3));
return polygonMap;
}
private class SideLabelMouseListener extends MouseAdapter {
private String position;
private Map<String, ImageIcon> imageMap;
public SideLabelMouseListener(String position, Map<String, ImageIcon> imageMap) {
this.imageMap = imageMap;
this.position = position;
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println(position + " pressed");
}
#Override
public void mouseEntered(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
String fullName = position + "-hovered";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
#Override
public void mouseExited(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
String fullName = position + "-default";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
}
private class CornerLabelMouseListener extends MouseAdapter{
private String position;
private Map <String, ImageIcon> imageMap;
private Polygon polygon;
public CornerLabelMouseListener(String position, Map <String, ImageIcon> imageMap, Polygon polygon) {
this.imageMap = imageMap;
this.position = position;
this.polygon= polygon;
}
#Override
public void mousePressed(MouseEvent e) {
if (polygon.contains(e.getPoint())) {
System.out.println(position + " pressed");
}
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("moving");
mouseEntered2(e);
mouseExited2(e);
}
//#Override
public void mouseEntered2(MouseEvent e) {
System.out.println("point = " +e.getPoint().toString());
if (polygon.contains(e.getPoint())) {
System.out.println("here");
JLabel label = (JLabel)e.getSource();
String fullName = position + "-hovered";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
}
//#Override
public void mouseExited2(MouseEvent e) {
if (!polygon.contains(e.getPoint())) {
JLabel label = (JLabel)e.getSource();
String fullName = position + "-default";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
}
}
private String[] getFilePaths() {
String[] paths = { "north-default.png", "north-hovered.png",
"northwest-default.png", "northwest-hovered.png",
"northeast-default.png", "northeast-hovered.png",
"west-default.png", "west-hovered.png", "east-default.png",
"east-hovered.png", "south-default.png", "south-hovered.png",
"southwest-default.png", "southwest-hovered.png",
"southeast-default.png", "southeast-hovered.png"
};
return paths;
}
private Map<String, ImageIcon> initImages(String[] paths) {
Map<String, ImageIcon> map = new HashMap<>();
for (String path: paths) {
ImageIcon icon = null;
try {
System.out.println(path);
icon = new ImageIcon(ImageIO.read(getClass().getResource("/octagonframe/" + path)));
} catch (IOException e) {
e.printStackTrace();
}
String prefix = path.split("\\.")[0];
map.put(prefix, icon);
}
return map;
}
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 createOctagonLabel() {
Image image = null;
try {
image = ImageIO.read(getClass().getResource("/octagonframe/octagon.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.add(createTextField());
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();
}
});
}

Just Use an image. From your last post you were trying to create the shape of the frame. But you can just use a transparent image.
Test the program.
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.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://i.stack.imgur.com/A9zlj.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();
}
});
}
}
Here's the image I used. (Just some simple Photoshop of your image
UPDATE
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Rectangle;
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.util.HashMap;
import java.util.Map;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DragDialog extends JDialog {
private int pointX;
private int pointY;
public DragDialog() {
JTextField textField = createTextField();
setContentPane(createBackgroundPanel());
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel createBackgroundPanel() {
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(527, 527);
}
};
panel.setOpaque(false);
panel.setLayout(null);
String[] filePaths = getFilePaths();
Map<String, ImageIcon> imageMap = initImages(filePaths);
Map<String, Rectangle> rectMap = createRectangles();
for (Map.Entry<String, Rectangle> entry: rectMap.entrySet()) {
JLabel label = new JLabel();
label.setOpaque(false);
String fullImageKey = entry.getKey() + "-default";
ImageIcon icon = imageMap.get(fullImageKey);
label.setIcon(icon);
label.setBounds(entry.getValue());
label.addMouseListener(new LabelMouseListener(entry.getKey(), imageMap));
panel.add(label);
}
JLabel octagon = createOctagonLabel();
octagon.setBounds(85, 85, 357, 357);
panel.add(octagon);
return panel;
}
private Map<String, Rectangle> createRectangles() {
Map<String, Rectangle> rectMap = new HashMap<>();
rectMap.put("north", new Rectangle(191, 0, 145, 73));
rectMap.put("northwest", new Rectangle(74, 74, 103, 103));
rectMap.put("northeast", new Rectangle(348, 74, 103, 103));
rectMap.put("west", new Rectangle(0, 190, 73, 145));
rectMap.put("east", new Rectangle(453, 190, 73, 145));
rectMap.put("south", new Rectangle(190, 453, 145, 73));
rectMap.put("southwest", new Rectangle(74, 348, 103, 103));
rectMap.put("southeast", new Rectangle(349, 349, 103, 103));
return rectMap;
}
private class LabelMouseListener extends MouseAdapter {
private String position;
private Map<String, ImageIcon> imageMap;
public LabelMouseListener(String position, Map<String, ImageIcon> imageMap) {
this.imageMap = imageMap;
this.position = position;
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println(position + " pressed");
}
#Override
public void mouseEntered(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
String fullName = position + "-hovered";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
#Override
public void mouseExited(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
String fullName = position + "-default";
ImageIcon icon = imageMap.get(fullName);
label.setIcon(icon);
}
}
private String[] getFilePaths() {
String[] paths = { "north-default.png", "north-hovered.png",
"northwest-default.png", "northwest-hovered.png",
"northeast-default.png", "northeast-hovered.png",
"west-default.png", "west-hovered.png", "east-default.png",
"east-hovered.png", "south-default.png", "south-hovered.png",
"southwest-default.png", "southwest-hovered.png",
"southeast-default.png", "southeast-hovered.png"
};
return paths;
}
private Map<String, ImageIcon> initImages(String[] paths) {
Map<String, ImageIcon> map = new HashMap<>();
for (String path: paths) {
ImageIcon icon = null;
try {
System.out.println(path);
icon = new ImageIcon(ImageIO.read(getClass().getResource("/octagonframe/" + path)));
} catch (IOException e) {
e.printStackTrace();
}
String prefix = path.split("\\.")[0];
map.put(prefix, icon);
}
return map;
}
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 createOctagonLabel() {
Image image = null;
try {
image = ImageIO.read(getClass().getResource("/octagonframe/octagon.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.add(createTextField());
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();
}
});
}
}

Related

How can I fill the Jtable with a complex json

I have this api:
https://api.openweathermap.org/data/2.5/weather?q=paris&appid=460b3f2acf469e5a496d8c019a2b364a&units=metric
I need to fill the JTable with the data in this API.
So I created the class (one of the classes im json in my api on the link:
package dataWeather;
public class Main {
private float temp;
private float pressure;
private float humidity;
private float temp_min;
private float temp_max;
// Getter Methods
public float getTemp() {
return temp;
}
public float getPressure() {
return pressure;
}
public float getHumidity() {
return humidity;
}
public float getTemp_min() {
return temp_min;
}
public float getTemp_max() {
return temp_max;
}
// Setter Methods
public void setTemp(float temp) {
this.temp = temp;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
public void setTemp_min(float temp_min) {
this.temp_min = temp_min;
}
public void setTemp_max(float temp_max) {
this.temp_max = temp_max;
}
}
And a table model:
package dataWeather;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class MainWeatherTableModel extends AbstractTableModel{
private List<Main> mainWeatherData = new ArrayList<Main>();
private String[] columnNames = {"temp", "pressure", "humidiry", "temp_min", "temp_max"};
public MainWeatherTableModel(List<Main> mainWeatherData)
{
this.mainWeatherData = mainWeatherData;
}
#Override
public String getColumnName(int column)
{
return columnNames[column];
}
#Override
public int getRowCount() {
return mainWeatherData.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object mainElementAttribute = null;
Main mainObject = mainWeatherData.get(rowIndex);
switch(columnIndex)
{
case 0: mainElementAttribute = mainObject.getTemp();break;
case 1: mainElementAttribute = mainObject.getPressure(); break;
case 2: mainElementAttribute = mainObject.getHumidity(); break;
case 3: mainElementAttribute = mainObject.getTemp_min(); break;
case 5: mainElementAttribute = mainObject.getTemp_max(); break;
default: break;
}
return mainElementAttribute;
}
}
And this is my MainFrame code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dataWeather.Main;
import dataWeather.MainWeatherTableModel;
public class MainFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel leftPanel = new JPanel();
private JPanel rightPanel = new JPanel();
private JPanel downPanel = new JPanel();
private JPanel centralPanel = new JPanel();
private JPanel weatherPanel = new JPanel();
private JMenuBar menuBar;
private JFileChooser fileChooser;
JScrollPane scrollPane = new JScrollPane();
private JTabbedPane tabbedPane = new JTabbedPane();
private JLabel imageBox = new JLabel();
private JLabel imageBox2 = new JLabel();
private JList<AppImage> imageList;
private MainWeatherTableModel mainModel;
private ObjectMapper objectMapper = new ObjectMapper();
private JTable mainTable;
private JButton buttonGo = new JButton("GO!");
private JTextArea downTextArea = new JTextArea();
public MainFrame () {
super("AppTask");
setLayout(new BorderLayout());
setMinimumSize(new Dimension(500, 400));
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addLeftPanel();
addRightPanel();
addDownPanel();
addCentralPanel();
addWeatherPanel();
menuBar = createMenuBar();
setJMenuBar(menuBar);
tabbedPane.addTab("Image", centralPanel);
tabbedPane.addTab("Weather", weatherPanel);
add(tabbedPane);
buttonGo.setAction(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
OnGoButtonClick(e);
}
});
buttonGo.setText("GOO");
downPanel.add(buttonGo);
downPanel.add(downTextArea);
}
void OnGoButtonClick(ActionEvent e) {
try
{
URL chosenUrl = new URL(imageList.getSelectedValue().getUrl());
HttpURLConnection connection = (HttpURLConnection)chosenUrl.openConnection();
connection.setRequestMethod("GET");
Integer responseCode = connection.getResponseCode();
downTextArea.append("Response: " + responseCode.toString());
String chosenUrlString = imageList.getSelectedValue().getUrl();
setImageUrl(chosenUrlString, imageBox);
}
catch (MalformedURLException ex) {
System.out.println("Malformed URL");
} catch (IOException iox) {
System.out.println("Can not load file");
}
}
public void addLeftPanel()
{
Dimension dim = getPreferredSize();
dim.width = 300;
leftPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("Choose an Image");
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
leftPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
add(leftPanel, BorderLayout.WEST);
imageList = new JList<>();
ArrayList<AppImage> images = new DataModel().getImages();
DefaultListModel<AppImage> imageListModel = new DefaultListModel<>();
for( AppImage item: images) {
imageListModel.addElement(item);
}
imageList.setModel(imageListModel);
imageList.setPreferredSize(new Dimension(110, 74));
imageList.setBorder(BorderFactory.createEtchedBorder());
imageList.setSelectedIndex(0);
leftPanel.setLayout(new BorderLayout());
leftPanel.add(imageList, BorderLayout.CENTER);
}
public void addRightPanel()
{
Dimension dim = getPreferredSize();
dim.width = 300;
rightPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("");
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
rightPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
add(rightPanel, BorderLayout.EAST);
}
public void addDownPanel() {
Dimension dim = getPreferredSize();
dim.height = 100;
downPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createEtchedBorder();
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
downPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
downPanel.setLayout(new GridLayout(1, 4, 40, 0));
add(downPanel, BorderLayout.SOUTH);
}
public void addMainTable() {
URL url = null;
Main mainWeather = null;
try {
url = new URL("https://api.openweathermap.org/data/2.5/weather?q=paris&appid=460b3f2acf469e5a496d8c019a2b364a&units=metric");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mainWeather = objectMapper.readValue(url, Main.class);
System.out.println(mainWeather.getHumidity());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Main> listMainWeather = new ArrayList<>();
listMainWeather.add(mainWeather);
mainModel = new MainWeatherTableModel(listMainWeather);
mainTable = new JTable(mainModel);
weatherPanel.add(mainTable);
}
public void addWeatherPanel()
{
weatherPanel.setLayout(new FlowLayout());
addMainTable();
}
public void addCentralPanel()
{
String imageUrl = "https://thumbs.dreamstime.com/z/welcome-to-summer-concept-written-sand-47585464.jpg";
setImageUrl(imageUrl, imageBox);
centralPanel.add(imageBox, BorderLayout.CENTER);
getContentPane().add(centralPanel, BorderLayout.CENTER);
pack();
}
private void setImageUrl(String imageUrl, JLabel imageBox) {
BufferedImage image = null;
URL url = null;
try {
url = new URL(imageUrl);
image = ImageIO.read(url);
} catch (MalformedURLException ex) {
System.out.println("Malformed URL");
} catch (IOException iox) {
System.out.println("Can not load file");
}
imageBox.setIcon(new ImageIcon(image));
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
JMenu fileMenu = new JMenu("File");
JMenuItem exportDataItem = new JMenuItem("Export Data...");
JMenuItem importDataItem = new JMenuItem("Import Data...");
JMenuItem exitItem = new JMenuItem("Exit");
menuBar.add(fileMenu);
menuBar.add(windowMenu);
fileMenu.add(importDataItem);
fileMenu.add(exportDataItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
JMenu showMenu = new JMenu("Show");
fileMenu.setMnemonic(KeyEvent.VK_F); //Alt+F opens the fileMenu
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
exitItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int action = JOptionPane.showConfirmDialog(MainFrame.this, "Do you really want to exit from application?",
"Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
if (action == JOptionPane.OK_OPTION)
{
System.exit(0);
}
}
});
exportDataItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) //MainFrame.this its a parent component
{
System.out.println(fileChooser.getSelectedFile());
}
}
});
importDataItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(fileChooser.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) //MainFrame.this its a parent component
{
System.out.println(fileChooser.getSelectedFile());
}
}
});
return menuBar;
}
}
I cant see what I'm doing wrong... Please help, dealing with it hours and can't make it work...
I'm very newbie in swing java, trying to understand what I have to do.
By default Swing components don't have a size/location.
It is the job of the layout manger to give components a size/location based on the rules of the layout manager.
The layout manager is invoked whenever you pack() a frame of use setVisible(true) on the frame.
You are making your frame visible BEFORE you add components to the frame, so I'm guessing your components still have a size of (0, 0) so there is nothing to paint.
Typically your would use:
panel.revalidate();
panel.repaint();
after you add components to a visible panel.
But in your case you appear to be creating all the panels after you make the frame visible so I think you just need to add
revalidate();
repaint();
at the end of your constructor.
weatherPanel.add(mainTable);
Also you need to display a JTable in a JScrollPane in order to see the table headers so the code should be:
//weatherPanel.add(mainTable);
JScrollPane scrollPane = new JScrollPane(mainTable);
weatherPanel.add( scrollPane );
I also question why you need the panel. You can add any component directly to a tabbed pane.

Change JLabel colour repeatedly each time when JButton pressed

I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
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();
}
});
}
}

Deleting images from JFrame

I created one JFrame. and set layout shown in below code
this.setLayout(new GridLayout());
JPanel panel=new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new PicturePanel1());
JTabbedPane jtp=new JTabbedPane();
jtp.addTab("show Images", panel);
jtp.addTab("Compare Image", new JButton());
this.add(jtp);
I created another class that draws Images from particular location.
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
int k = 20,y=10;
for (int j = 0; j <= listOfFiles.length - 1; j++) {
g2.drawImage(b[j], k, y, 100, 100, null);
// add(new javax.swing.JCheckBox());
k = k + 120;
if(k>=960)
{
k=20;
y=y+120;
}
}
Its working fine. I want to delete Images when user clicks on particular Image.
This is my output window. I want to delete Image from list.
Here is an example I made (bored and tired of studying :)). It is by no means the best just a quick thing to show you an example, click the image you want to delete and then press the delete button or DEL to remove and image from the panel:
When app starts up (orange just shows focused label for hovering):
Image to delete is selected by clicking on the Label (Border becomes green highlighted and will remain this way until another label is clicked):
After delete button or key is pressed:
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 JavaApplication5 {
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);
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
controlPanel.add(addLabelButton);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://icons.iconarchive.com/icons/deleket/sleek-xp-software/256/Yahoo-Messenger-icon.png")), 100, 100));
images.add(resize(ImageIO.read(new URL("https://upload.wikimedia.org/wikipedia/commons/6/64/Gnu_meditate_levitate.png")), 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;
}
}
class ImageViewPanel extends JPanel {
JLabel NO_IMAGES = new JLabel("No Images");
ArrayList<BufferedImage> images;
ArrayList<MyLabel> imageLabels;
public ImageViewPanel(ArrayList<BufferedImage> images) {
this.images = images;
imageLabels = new ArrayList<>();
for (BufferedImage bi : images) {
imageLabels.add(new MyLabel(new ImageIcon(bi), this));
}
layoutLabels();
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, true), "Delete pressed");
getActionMap().put("Delete pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
removeFocusedImageLabel();
}
});
}
void removeFocusedImageLabel() {
if (focusedLabel == null) {
return;
}
imageLabels.remove(focusedLabel);
remove(focusedLabel);
layoutLabels();
}
private void layoutLabels() {
if (imageLabels.isEmpty()) {
add(NO_IMAGES);
} else {
remove(NO_IMAGES);
for (JLabel il : imageLabels) {
add(il);
}
}
revalidate();
repaint();
}
private MyLabel focusedLabel;
void setFocusedLabel(MyLabel labelToFocus) {
if (focusedLabel != null) {
focusedLabel.setBorder(null);
focusedLabel.setClicked(false);
}
focusedLabel = labelToFocus;
focusedLabel.setBorder(new LineBorder(Color.GREEN));
}
}
class MyLabel extends JLabel {
private final ImageViewPanel imageViewPanel;
private boolean clicked = false;
public MyLabel(Icon image, ImageViewPanel imageViewPanel) {
super(image);
this.imageViewPanel = imageViewPanel;
initLabel();
}
public MyLabel(String text, ImageViewPanel imageViewPanel) {
super(text);
this.imageViewPanel = imageViewPanel;
initLabel();
}
private void initLabel() {
setFocusable(true);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
clicked = true;
imageViewPanel.setFocusedLabel(MyLabel.this);
}
#Override
public void mouseEntered(MouseEvent me) {
super.mouseEntered(me);
if (clicked) {
return;
}
setBorder(new LineBorder(Color.ORANGE));
//call for focus mouse is over this component
requestFocusInWindow();
}
});
addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
super.focusLost(e);
if (clicked) {
return;
}
setBorder(null);
}
});
}
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
public boolean isClicked() {
return clicked;
}
}
simply find the location (x, and y) and the size(width, and height) of image, then with the Graphics object (g2) fill a rectangle over the image drawn, like this
g2.setColor(this.getBackground());//set the color you want to clear the bound this point to JFrame/JPanel
g2.fillRect(x, y, width, height);
where x and y where is the location that images is located, and width and height are size of the picture

Drawing warning symbol during form validation in Swing

I have developed a swing form which validates entries as the focus is lost from JTextComponent
and if the entry is correct ,the background is painted green Otherwise it is painted red.
Here is the code :-
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class Form extends JFrame implements FocusListener{
JTextField fname,lname,phone,email,address;
BufferedImage img;
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new Form();}});
}
public Form()
{
super("Form with Validation Capability");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setLayout(new GridLayout(5,3));
try {
img=ImageIO.read(new File("src/warning.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
add(new JLabel("First Name :"));
add(fname=new JTextField(20));
add(new JLabel("Last Name :"));
add(lname=new JTextField(20));
add(new JLabel("Phone Number :"));
add(phone=new JTextField(10));
add(new JLabel("Email:"));
add(email=new JTextField(20));
add(new JLabel("Address :"));
add(address=new JTextField(20));
fname.addFocusListener(this);
lname.addFocusListener(this);
phone.addFocusListener(this);
email.addFocusListener(this);
address.addFocusListener(this);
setVisible(true);
}
public void focusGained(FocusEvent e)
{
((JTextComponent) e.getSource()).setBackground(Color.WHITE);
}
public void focusLost(FocusEvent e)
{
if(e.getSource().equals(fname))
{
validationForText(fname);
}
else if(e.getSource().equals(lname))
{
validationForText(lname);
}
else if(e.getSource().equals(email))
{
validationForEmail(email);
}
else if(e.getSource().equals(phone))
{
validationForNumber(phone);
}
else{
((JTextComponent) e.getSource()).setBackground(Color.GREEN);
}
}
public void validationForText(JTextComponent comp)
{
String temp=comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
comp.setBackground(Color.GREEN);
}
else
comp.setBackground(Color.RED);
}
public void validationForNumber(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("^[0-9]+$"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
public void validationForEmail(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("[^#]+#([^.]+\\.)+[^.]+"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
}
Here is the output to my simple app :
Now I also want to draw a warning symbol (buffered image) at the lower left corner of incorrect field.Can anyone help me how to do this as i am not understanding where to paint the image.
(I would like to do it using JLayeredPane as I am learning its application,any code snippet will really help).
Why not simply add a JLabel (using an appropriate LayoutManager to position it) with the inbuilt Swing warning icon UIManager.getIcon("OptionPane.warningIcon")
like so:
JLabel label=new JLabel(UIManager.getIcon("OptionPane.warningIcon"));
see here for more.
UPDATE:
As per your comment I would rather use GlassPane (and add JLabel to glasspane) for this as opposed too JLayeredPane. See here for more on RootPanes
Some suggestions:
Dont extend JFrame unnecessarily
Dont call setSize on JFrame. Use a correct LayoutManager and/or override getPreferredSize() where necessary and replace setSize call with pack() just before setting JFrame visible.
Dont implement FocusListener on the class unless you want to share the functionality with other classes.
Also get into the habit of using FocusAdapter vs FocusListener this applies to a few with appended Listener i.e MouseListener can be replaced for MouseAdapter. This allows us to only override the methods we want. In this case listener is correct as we do something on both overridden methods, but as I said more about the habit
Also always call super.XXX implementation of overridden methods i.e focusGained(FocusEvent fe) unless you are ignoring it for a reason
Here is code with above fixes including glasspane to show warning icon when field is red:
And removes it when is corrected:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
/**
*
* #author David
*/
public class GlassValidationPane extends JComponent {
private static JTextField fname, lname, phone, email, address;
private static GlassValidationPane gvp = new GlassValidationPane();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Form with Validation Capability");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.setResizable(false);
f.setLayout(new GridLayout(5, 3));
f.add(new JLabel("First Name :"));
f.add(fname = new JTextField(20));
f.add(new JLabel("Last Name :"));
f.add(lname = new JTextField(20));
f.add(new JLabel("Phone Number :"));
f.add(phone = new JTextField(10));
f.add(new JLabel("Email:"));
f.add(email = new JTextField(20));
f.add(new JLabel("Address :"));
f.add(address = new JTextField(20));
f.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent ce) {
super.componentResized(ce);
gvp.refreshLocations();
}
});
FocusAdapter fl = new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
((JTextComponent) fe.getSource()).setBackground(Color.WHITE);
}
#Override
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
if (fe.getSource().equals(fname)) {
validationForText(fname);
} else if (fe.getSource().equals(lname)) {
validationForText(lname);
} else if (fe.getSource().equals(email)) {
validationForEmail(email);
} else if (fe.getSource().equals(phone)) {
validationForNumber(phone);
} else {
gvp.removeWarningIcon(((Component) fe.getSource()));
((JTextComponent) fe.getSource()).setBackground(Color.GREEN);
}
}
};
fname.addFocusListener(fl);
lname.addFocusListener(fl);
phone.addFocusListener(fl);
email.addFocusListener(fl);
address.addFocusListener(fl);
f.setGlassPane(gvp);
f.pack();
f.setVisible(true);
gvp.setVisible(true);
}
public void validationForText(JTextComponent comp) {
String temp = comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForNumber(JTextComponent comp) {
String text = comp.getText();
if (text.matches("^[0-9]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForEmail(JTextComponent comp) {
String text = comp.getText();
if (text.matches("[^#]+#([^.]+\\.)+[^.]+")) {
setGreen(comp);
} else {
setRed(comp);
}
}
private void setRed(JTextComponent comp) {
comp.setBackground(Color.RED);
gvp.showWarningIcon(comp);
}
private void setGreen(JTextComponent comp) {
comp.setBackground(Color.GREEN);
gvp.removeWarningIcon(comp);
}
});
}
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
public GlassValidationPane() {
setLayout(null);//this is the exception to the rule case a layoutmanager might make setting Jlabel co-ords harder
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = ImageUtilities.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(ImageUtilities.resize(img, 24, 24));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
add(label);
label.setVisible(true);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
}
class ImageUtilities {
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;
}
public static BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}

Browse for image file and display it using Java Swing

My problem here is,
after clicking Browse button it displays all files in a directory to choose,
then the chosen image is displayed in GUI correctly. But When i click Browse button
for the second time, it shows the old image only instead of showing the new one. Please help me in this.
For reference, i uploaded the UI.
package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
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.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
#SuppressWarnings("serial")
public class MainAppFrame extends JFrame {
private JPanel contentPane;
File targetFile;
BufferedImage targetImg;
public JPanel panel,panel_1;
private static final int baseSize = 128;
private static final String basePath =
"C:\\Documents and Settings\\Administrator\\Desktop\\Images";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainAppFrame frame = new MainAppFrame();
frame.setVisible(true);
frame.setResizable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainAppFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
contentPane.add(panel, BorderLayout.WEST);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
JLabel lblSelectTargetPicture = new JLabel("Select target picture..");
JButton btnDetect = new JButton("Detect");
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAddDigit = new JButton("Add Digit");
btnAddDigit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton button = new JButton("Recognize");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblSelectTargetPicture)
.addGap(6)
.addComponent(btnBrowse))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(btnDetect)
.addGap(18)
.addComponent(btnAddDigit))))
.addGroup(gl_panel.createSequentialGroup()
.addGap(50)
.addComponent(button))
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(7)
.addComponent(lblSelectTargetPicture))
.addGroup(gl_panel.createSequentialGroup()
.addGap(3)
.addComponent(btnBrowse)))
.addGap(18)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
.addGap(22)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDetect)
.addComponent(btnAddDigit))
.addGap(18)
.addComponent(button)
.addContainerGap())
);
panel.setLayout(gl_panel);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
}
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
}
//JPEGImageFileFilter.java
package GUI;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/*
* This class implements a generic file name filter that allows the listing/selection
* of JPEG files.
*/
public class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}
Each time a new image is selected, you're creating components unnecessarily and in error here:
public void setTarget(File reference) {
//....
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));
Create an ImageViewer with method like ImageViewer.setImage(Image), display the image in a JLabel.
ImageViewer
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class ImageViewer {
JPanel gui;
/** Displays the image. */
JLabel imageCanvas;
/** Set the image as icon of the image canvas (display it). */
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public static Image getRandomImage(Random random) {
int w = 100 + random.nextInt(400);
int h = 50 + random.nextInt(200);
BufferedImage bi = new BufferedImage(
w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Image Viewer");
// TODO Fix kludge to kill the Timer
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageViewer viewer = new ImageViewer();
f.setContentPane(viewer.getGui());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener animate = new ActionListener() {
Random random = new Random();
#Override
public void actionPerformed(ActionEvent arg0) {
viewer.setImage(getRandomImage(random));
}
};
Timer timer = new Timer(1500,animate);
timer.start();
}
};
SwingUtilities.invokeLater(r);
}
}
I modified your code , I hope it will fulfill your requirement. I use MigLayout (it is a Layout manager) to arrange the component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class MyFileChooser
{
JFrame frame;
JPanel panel;
JButton btnBrowse;
JButton change;
JLabel imglabel;
File targetFile;
BufferedImage targetImg;
private static final int baseSize = 128;
private static final String basePath ="/images/fimage";
JPanel panel_1;
ImageIcon icon;
public MyFileChooser()
{
// TODO Auto-generated constructor stub
frame =new JFrame();
frame.setLayout(new MigLayout());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel(new MigLayout());
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(5, 5, 5), 1, true));
panel_1.setBackground(Color.pink);
btnBrowse=new JButton("browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
change=new JButton("Delete");
change.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
changeButtonActionPerformed(e);
}
private void changeButtonActionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
imglabel.revalidate(); //ADD THIS AS WELL
imglabel.repaint(); //ADD THIS AS WELL
imglabel.setIcon(null);
System.out.println("delete button activated");
}
});
imglabel=new JLabel("Image");
imglabel.setSize(100, 100);
imglabel.setBackground(Color.yellow);
frame.add(panel_1,"span,pushx,pushy,growx,growy");
frame.add(btnBrowse);
frame.add(change,"");
//frame.pack();
}
protected void browseButtonActionPerformed(ActionEvent e)
{
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
imglabel.setIcon(null);
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
// Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
icon=new ImageIcon(targetImg);
imglabel=new JLabel(icon);
panel_1.add(imglabel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new MyFileChooser();
}
});
}
}
JPEGImageFileFilter class , you can keep this class in same pakage
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class JPEGImageFileFilter extends FileFilter implements FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}

Categories

Resources