У меня есть этот API: https://api.openweathermap.org/data/2.5/weather?q=paris&appid=460b3f2acf469e5a496d8c019a2b364a&units=metric Мне нужно заполнить JTable данными в этом API.Поэтому я создал класс (один из классов im json в моем API по ссылке: 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;
}
}
И модель таблицы:
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;
}
}
И это мой MainFrameкод:
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;
}
}
Я не вижу, что я делаю не так ... Пожалуйста, помогите, разобраться с этим часами и не могу заставить его работать ... Я очень новичок в свинг Java, пытаюсьчтобы понять, что я должен делать.