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.
Related
So, my program is a user adding buttons during runtime. When he/she clicks on the 'save' button the program is saved to a file. But when I run it again, the buttons are gone. I tried to serialize my buttons using XMLEncoder and XMLDecoder, but when I ran my program, it didn't save anything, it started all over again. How would I serialize this correctly so that when I start my program, the buttons are there? Any help would be appreciated.
Here is a snippet of my code:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = JOptionPane.showInputDialog("What is the name of the new button?");
JButton b = new JButton(str);
frame.add(b);
try
{
XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
encdr.writeObject(new JButton(str));
encdr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
try
{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
Object result = d.readObject();
d.close();
}
catch (IOException decoder)
{
decoder.printStackTrace();
}
}
}
Once you decode the object, you need to cast the object appropriately and then add the component to the container.
This is pretty basic example which generates a random number of buttons on a panel each time you click the Random button. When you click Save, the panel is saved to disk and when you click Load, it loads the panel from disk and reapplies it the container
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RandomButtonPane pane;
public TestPane() {
setLayout(new BorderLayout());
JPanel actions = new JPanel();
JButton random = new JButton("Random");
JButton save = new JButton("Save");
JButton load = new JButton("Load");
actions.add(random);
actions.add(save);
actions.add(load);
add(actions, BorderLayout.SOUTH);
random.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
}
pane = new RandomButtonPane();
pane.randomise();
add(pane);
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
try (OutputStream os = new FileOutputStream(new File("Save.dat"))) {
try (XMLEncoder encoder = new XMLEncoder(os)) {
encoder.writeObject(pane);
remove(pane);
pane = null;
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
pane = null;
}
try (InputStream is = new FileInputStream(new File("Save.dat"))) {
try (XMLDecoder decoder = new XMLDecoder(is)) {
Object value = decoder.readObject();
if (value instanceof RandomButtonPane) {
pane = (RandomButtonPane)value;
pane.revalidate();
add(pane);
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
}
}
public static class RandomButtonPane extends JPanel {
public RandomButtonPane() {
setLayout(new GridBagLayout());
}
public void randomise() {
int count = ((int) (Math.random() * 100)) + 1;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < count; index++) {
if (index % 10 == 0) {
gbc.gridx = 0;
gbc.gridy++;
}
add(new JButton(Integer.toString(index)), gbc);
gbc.gridx++;
}
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to dispose of my frame and create a new one. The new one gets created but the old one persists. I end up having two frames on my desktop. What am I missing? Thanks.
package org.rockislandschools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DisplayStatus extends JFrame {
public void buildFrame(String ipAdd, String status){
JFrame frame = new JFrame("Host Status");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setVisible(true);
}
}
package org.rockislandschools;
import java.io.IOException;
import java.net.InetAddress;
public class HostStatus {
public String IsReachableReturnString(String ip){
String canBeReachedReturnString = "Down";
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReachedReturnString = "Up";
} catch (IOException e) {
e.printStackTrace();
}
return canBeReachedReturnString;
}
public boolean IsReachable(String ip){
boolean canBeReached = false;
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReached = true;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(canBeReached);
return canBeReached;
}
}
package org.rockislandschools;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
if(args.length == 0)
{
System.out.println("Please specify IP Address.");
System.exit(0);
}
String address = args[0];
HostStatus status = new HostStatus();
String currentState = status.IsReachableReturnString(address);
DisplayStatus statusFrame = new DisplayStatus();
statusFrame.buildFrame(address, currentState);
//String newState = status.IsReachableReturnString(address);
while (true){
String newState = status.IsReachableReturnString(address);
if (newState.equals(currentState)){
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null, ex);
}
System.out.println("Nothing has changed");
}
else {
statusFrame.setVisible(false);
statusFrame.dispose();
System.out.println("Building a new frame");
currentState = newState;
statusFrame.buildFrame(address, currentState);
}
}
}
}
I am not sure what I need in regards to more details. I can tell you that I am just starting with attempting to learn Java. I live in Iowa and like to spend my free time not being hassled by red arrow boxes that criticize my posts.
When you were calling statusFrame.dispose(); you were calling that on a JFrame that did not exist. I fixed the code and here are each of the files:
EDIT: I have a version of this with system tray and GUI for selecting the IP on my github: https://github.com/ArgonBird18/HostStatus
Main.java
package org.rockislandschools;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
if(args.length == 0)
{
System.out.println("Please specify IP Address.");
System.exit(0);
}
String address = args[0];
HostStatus status = new HostStatus();
String currentState = status.IsReachableReturnString(address);
JFrame statusFrame = new JFrame();
statusFrame = DisplayStatus.buildFrame(address, currentState);
//String newState = status.IsReachableReturnString(address);
while (true){
String newState = status.IsReachableReturnString(address);
if (newState.equals(currentState)){
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("Nothing has changed, Time is " + timeStamp );
} else {
//statusFrame.setVisible(false);
statusFrame.dispose();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("Building a new frame, Time is " + timeStamp);
currentState = newState;
statusFrame = DisplayStatus.buildFrame(address, currentState);
}
}
}
}
HostStatus.java
package org.rockislandschools;
import java.io.IOException;
import java.net.InetAddress;
public class HostStatus {
public String IsReachableReturnString(String ip){
String canBeReachedReturnString = "Down";
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReachedReturnString = "Up";
} catch (IOException e) {
e.printStackTrace();
}
return canBeReachedReturnString;
}
public boolean IsReachable(String ip){
boolean canBeReached = false;
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReached = true;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(canBeReached);
return canBeReached;
}
}
DisplayStatus.java
package org.rockislandschools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DisplayStatus {
public static JFrame buildFrame(String ipAdd, String status){
JFrame frame = new JFrame("Host Status");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setVisible(true);
return frame;
}
public static void editFrame(JFrame frame,String status,String ipAdd){
frame.setContentPane(new JPanel());
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
}
}
Good luck with your host status program!
I am new to using cardlayout and I have a few questions on how to implement it. I first would like to know the best way to implement cardlayout so that I can switch from panel to panel. My main question is how to use buttons inside the constructors of my panels to switch from panel to panel. I just started working on this project today so you will see some code that is not finished or that does not make sense. I first tried to make all my classes to extend JFrame but that led to multiple unwanted windows. If I can get some sort of example on how to effectively use cardlayout and how to switch panels using the buttons within my other panel constructors. My attempts on using cardlayout only worked for buttons that I created in my gui class however that is not the result I want. Please help if you can and thanks in advance.
This is my main class.
public class controller{
public static void main(String[] args){
new Gui();
}
}
This is my gui class.
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Gui extends JFrame{
homePage home = new homePage();
public JPanel loginPanel = new textEmailLog(),
registerPanel = new Register(),
homePanel = new homePage(), viewPanel = new emailView(),
loadPanel = new loadEmail(), contentPanel = new JPanel(new CardLayout());
CardLayout cardLayout = new CardLayout();
public Gui(){
super("Email Database Program");
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPanel.setLayout(cardLayout);
contentPanel.add(loginPanel, "Login");
contentPanel.add(registerPanel, "Register");
contentPanel.add(homePanel, "Home");
contentPanel.add(viewPanel, "View");
contentPanel.add(loadPanel, "Load");
this.setContentPane(contentPanel);
cardLayout.show(contentPanel, "Login");
setVisible(true);
}
My Login Panel class
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
//panel has been added
public class textEmailLog extends JPanel{
JPanel logGui = null;
JButton registerBut, logBut;
JTextField Login;
public textEmailLog(){
//default characteristics
setSize(700,700);
setName("Email Database");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Labels for username and password
JLabel userLab = new JLabel("Username");
JLabel pwLab = new JLabel("Password");
//textfields for username and password
Login = new JTextField("", 15);
JPasswordField Password = new JPasswordField("", 15);
Password.setEchoChar('*');
//login button that confirms username and password
logBut = new JButton("Login");
logBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//needs regex checks prior to logging in
if(e.getSource() == logBut){
/* Change the panel to the homepage
if(Login.getText().equals() && Password.getText().equals()){
}
*/
new homePage();
}
}
});
registerBut = new JButton("Register");
registerBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == registerBut){
//Change the panel to the register panel
}
}
});
//Box layout for organization of jcomponents
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
//add to panel
verticalContainer.add(Box.createVerticalStrut(300));//begin relative to the center
verticalContainer.add(userLab);//Login label and text
verticalContainer.add(Login);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(pwLab);//password label and text
verticalContainer.add(Password);
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(registerBut);//register button
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(logBut);//login button
//combines both the vertical and horizontal container
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
//this.add(logGui);
setVisible(true);
}
}
My Register panel class
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
//No Panel addition
public class Register extends JPanel{
JButton submit, previous;
JLabel firstLab, lastLab, userLab, passwordLab, repassLab, address, emailAdd, errorLabel;
JTextField firstText, lastText, userText, addText, emailAddText;
JPasswordField passwordText, repassText;
public Register(){
setSize(700,700);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//register values and their labels and textfields
firstLab = new JLabel("First Name: ");
firstText = new JTextField("", 25);
lastLab = new JLabel("Last Name: ");
lastText = new JTextField("", 40);
userLab = new JLabel("Username: ");
userText = new JTextField("", 25);
passwordLab = new JLabel("Password: ");
passwordText = new JPasswordField("", 25);
passwordText.setEchoChar('*');
repassLab = new JLabel("Confirm Password");
repassText = new JPasswordField("", 25);
repassText.setEchoChar('*');
address = new JLabel("Address: ");
addText = new JTextField("", 50);
emailAdd = new JLabel("Email Address: ");
emailAddText = new JTextField("", 50);
//error message for reigstration issues
errorLabel = new JLabel();
errorLabel.setForeground(Color.red);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener(){
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == submit){
//confirm with regex methods and if statements that have been created and need to be created
if(firstText.getText().length() == 0){
errorLabel.setText("*You have not entered a first name!");
}else
if(lastText.getText().length() == 0){
errorLabel.setText("*You have not entered a last name!");
}else
if(userText.getText().length() == 0){
errorLabel.setText("*You have not entered a username!");
}else
if(passwordText.toString().length() == 0){
errorLabel.setText("*You have not entered a Password!");
}else
if(repassText.toString().length() == 0){
errorLabel.setText("*You have not matched your password!");
}
if(addText.getText().length() == 0){
errorLabel.setText("*You have not entered an address!");
}else
if(emailAddText.getText().length() == 0){
errorLabel.setText("*You have not entered an Email address!");
}else
if(userText.getText().length() < 8){
errorLabel.setText("*Username is too short!");
}
else
if(!(passwordText.toString().matches(repassText.toString()))){
errorLabel.setText("Passwords do not match!");
}
else
if(!isValidEmailAddress(emailAddText.getText())){
errorLabel.setText("*Invalid Email!");
}
else
if(!isValidAddress(addText.getText())){
errorLabel.setText("*Invalid Address!");
}
}
}
});
//returns to the previous page
previous = new JButton("Previous Page");
previous.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == previous){
//card.show(login panel);
}
}
});
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
verticalContainer.add(Box.createVerticalStrut(150));
verticalContainer.add(firstLab);
verticalContainer.add(firstText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(lastLab);
verticalContainer.add(lastText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(userLab);
verticalContainer.add(userText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(passwordLab);
verticalContainer.add(passwordText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(repassLab);
verticalContainer.add(repassText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(address);
verticalContainer.add(addText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailAdd);
verticalContainer.add(emailAddText);
verticalContainer.add(Box.createVerticalStrut(5));
//horizontal
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(submit);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(previous);
//merger
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
setVisible(true);
}
//regex check for valid Email
public boolean isValidEmailAddress(String email){
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[A-Za-z0-9._\\%-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}");
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
//regex check for valid Address
public boolean isValidAddress(String address){
java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\d{1,3}.?\\d{0,3}\\s[a-zA-Z]{2,30}\\s[a-zA-Z]{2,15}");
java.util.regex.Matcher m = p.matcher(address);
return m.matches();
}
}
Homepage panel class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
//NO Panel Yet
#SuppressWarnings("serial")
public class homePage extends JPanel{
JButton uploadEmail, viewEmail;
public homePage(){
setSize(700,700);
uploadEmail = new JButton("Upload Your Email");
uploadEmail.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == uploadEmail){
new loadEmail();
}
}
});
viewEmail = new JButton("View An Email");
viewEmail.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == viewEmail){
new emailView();
}
}
});
add(uploadEmail);
add(viewEmail);
setVisible(true);
}
}
My View Email Panel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class emailView extends JPanel{
JPanel viewPanel;
JButton logout, delete, homepage;
JTable emailList;
//Cannot be edited or may be in a new panel
/*
JLabel fileLab, toLab, fromLab, subjectLab,topicLab, emailLab, notesLab, attachLab;
JTextField fileText, toText, fromText, subjectText, topicText;
JTextArea emailText, notesText, attachText;
*/
public emailView(){
setSize(700,700);
setVisible(true);
emailList = new JTable();
logout = new JButton("Logout");
logout.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == logout){
new textEmailLog();
}
}
});
delete = new JButton("Delete");
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == delete){
}
}
});
homepage = new JButton("HomePage");
homepage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == homepage){
new homePage();
}
}
});
Box horizontalContainer = Box.createHorizontalBox();
Box verticalContainer = Box.createVerticalBox();
Box mergerContainer = Box.createVerticalBox();
horizontalContainer.add(logout);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(homepage);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(delete);
horizontalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailList);
mergerContainer.add(horizontalContainer);
mergerContainer.add(verticalContainer);
add(mergerContainer);
setVisible(true);
}
}
My upload Email Panel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class loadEmail extends JPanel{
JPanel loadPanel;
JLabel fileLab, toLab, fromLab, subjectLab, topicLab, emailLab, notesLab, attachLab;
JTextField fileText, toText, fromText, subjectText, topicText;
JTextArea emailText, notesText, attachText; //attachment text will be changed
JButton cancel, complete, enter;//enter may not be necessary
public loadEmail(){
setSize(700,700);
fileLab = new JLabel("Enter a new File: ");
fileText = new JTextField();
enter = new JButton("Enter");
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == enter){
//opens file directory window
}
}
});
toLab = new JLabel("To: ");
toText = new JTextField();
toText.setSize(5, 30);
fromLab = new JLabel("From: ");
fromText = new JTextField();
subjectLab = new JLabel("Subject: ");
subjectText = new JTextField();
topicLab = new JLabel("Topic: ");
topicText = new JTextField();
emailLab = new JLabel("Email Content: ");
emailText = new JTextArea();
notesLab = new JLabel("Comments: ");
notesText = new JTextArea();
attachLab = new JLabel("Attachments");
attachText = new JTextArea();
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == cancel){
//dispose page
}
}
});
complete = new JButton("Complete");
complete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == complete){
//store in database, prompt user for new email to enter in other wise return to homepage
}
}
});
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
verticalContainer.add(fileLab);
verticalContainer.add(fileText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(Box.createHorizontalStrut(50));
verticalContainer.add(enter);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(toLab);
verticalContainer.add(toText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(fromLab);
verticalContainer.add(fromText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(subjectLab);
verticalContainer.add(subjectText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(topicLab);
verticalContainer.add(topicText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailLab);
verticalContainer.add(emailText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(notesLab);
verticalContainer.add(notesText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(attachLab);
verticalContainer.add(attachText);
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(cancel);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(complete);
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
setVisible(true);
}
}
The short answer is don't. The reasons for this is you'll end having to expose the parent container and CardLayout to ALL your sub components, which not only exposes portions of your application to potential mistreatment, it tightly couples the navigation making it difficult to add/remove steps in the future...
A better solution would be to devise some kind of controller interface, which defines what each view could do (for example showHome, nextView, previousView), you would then pass an implementation of this interface to each view. Each view would then use this interface to request a change as the needed to.
The controller would know things like, the current view, the home view and how to move between certain views (next/previous) as required.
Updated with simple example
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AllYouViewBelongToMe {
public static void main(String[] args) {
new AllYouViewBelongToMe();
}
public AllYouViewBelongToMe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface ViewContoller {
public void goHome();
public void nextView();
public void previousView();
}
public static class DefaultViewController implements ViewContoller {
public static final String HOME = "home";
private Component currentView = null;
private List<Component> views;
private Map<Component, String> mapNames;
private Container parent;
private CardLayout cardLayout;
public DefaultViewController(Container parent, CardLayout cardLayout) {
this.parent = parent;
this.cardLayout = cardLayout;
views = new ArrayList<>(25);
mapNames = new HashMap<>(25);
}
public CardLayout getCardLayout() {
return cardLayout;
}
public Container getParent() {
return parent;
}
public void addView(Component comp, String name) {
if (!HOME.equals(name)) {
views.add(comp);
}
mapNames.put(comp, name);
getParent().add(comp, name);
}
public void removeView(Component comp, String name) {
views.remove(comp);
mapNames.remove(comp);
getParent().remove(comp);
}
#Override
public void goHome() {
currentView = null;
getCardLayout().show(getParent(), HOME);
}
#Override
public void nextView() {
if (views.size() > 0) {
String name = null;
if (currentView == null) {
currentView = views.get(0);
name = mapNames.get(currentView);
} else {
int index = views.indexOf(currentView);
index++;
if (index >= views.size()) {
index = 0;
}
currentView = views.get(index);
name = mapNames.get(currentView);
}
getCardLayout().show(getParent(), name);
}
}
#Override
public void previousView() {
if (views.size() > 0) {
String name = null;
if (currentView == null) {
currentView = views.get(views.size() - 1);
name = mapNames.get(currentView);
} else {
int index = views.indexOf(currentView);
index--;
if (index < 0) {
index = views.size() - 1;
}
currentView = views.get(index);
name = mapNames.get(currentView);
}
getCardLayout().show(getParent(), name);
}
}
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
CardLayout cardLayout = new CardLayout();
JPanel view = new JPanel(cardLayout);
final DefaultViewController controller = new DefaultViewController(view, cardLayout);
controller.addView(createPane("home"), DefaultViewController.HOME);
controller.addView(createPane("Page #1"), "View1");
controller.addView(createPane("Page #2"), "View2");
controller.addView(createPane("Page #3"), "View3");
controller.addView(createPane("Page #4"), "View4");
controller.goHome();
JPanel controls = new JPanel();
JButton btnPrev = new JButton("<");
JButton btnHome = new JButton("Home");
JButton btnNext = new JButton(">");
controls.add(btnPrev);
controls.add(btnHome);
controls.add(btnNext);
btnNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.nextView();
}
});
btnPrev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.previousView();
}
});
btnHome.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.goHome();
}
});
add(view);
add(controls, BorderLayout.SOUTH);
}
protected JPanel createPane(String name) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel(name));
return panel;
}
}
}
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();
}
});
}
}
I have created a program in which a window opens which says click to start.When we press start button it opens another window and make it fullscreen. I have add keylistener to this fullscreen window to move an image.But its not working. If you wanna see the code please ask me .
public g1(){
panel = new JPanel();
cake = new ImageIcon("G:\\naman1.jpg").getImage();
start = new JButton("Start");
restart = new JButton("Restart");
exit = new JButton("EXIT");
panel.add(start);
panel.setFocusable(true);
start.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new g1().run(); //this method is from superclass it calls init }
}
);
panel.setBackground(Color.GRAY);
}
public void init(){
super.init(); //it makes the window fullscreen
Window w = s.getFullScreenWindow();
w.setFocusable(true);
w.addKeyListener(this);}
Try this:
The MainFrame
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JButton startBtn;
public MainFrame() {
this.setTitle("Moving Images");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(initComponents());
this.setSize(new Dimension(1024, 768));
this.setVisible(true);
}
private JPanel initComponents() {
JPanel jPanel = new JPanel();
startBtn = new JButton("start");
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final ImageWindow imageWindow = new ImageWindow();
}
});
jPanel.add(startBtn);
return jPanel;
}
}
This is the ImageWindow
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ImageWindow extends JFrame {
public ImageWindow() {
this.add(new JLabel("Window"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
final ImagePanel imagePanel = new ImagePanel();
this.getContentPane().add(imagePanel);
this.setVisible(true);
}
class ImagePanel extends JPanel {
URL url;
int panelX;
int panelY;
boolean isDragged;
ImagePanel() {
this.panelX = this.getWidth();
this.panelY = this.getHeight();
try {
this.url = new URL("http://i.stack.imgur.com/XZ4V5.jpg");
final ImageIcon icon = new ImageIcon(url);
final JLabel imageLabel = new JLabel(icon);
Action moveLeft = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getX() - 1 > 0)
imageLabel.setLocation(imageLabel.getX()-1, imageLabel.getY());
}
};
Action moveUp = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getY() - 1 > 0) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()-1);
}
}
};
Action moveDown = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getHeight()-icon.getIconHeight() > imageLabel.getY() + 1) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()+1);
}
}
};
Action moveRight = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getWidth()-icon.getIconWidth() > imageLabel.getX()+1) {
imageLabel.setLocation(imageLabel.getX()+1, imageLabel.getY());
}
}
};
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("A"), "moveLeft");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("W"), "moveUp");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("S"), "moveDown");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("D"), "moveRight");
imageLabel.getActionMap().put("moveLeft", moveLeft);
imageLabel.getActionMap().put("moveUp", moveUp);
imageLabel.getActionMap().put("moveDown", moveDown);
imageLabel.getActionMap().put("moveRight", moveRight);
this.add(imageLabel);
} catch (MalformedURLException ex) {
Logger.getLogger(ImageWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Start the App
package moveimages;
import javax.swing.SwingUtilities;
public class MoveImages {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainFrame frame = new MainFrame();
});
}
}
Maybe it helps you to refactor your current app.