Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 未在JLabel中的图像上绘制Swing图形对象_Java_Swing_Graphics2d_Swingworker - Fatal编程技术网

Java 未在JLabel中的图像上绘制Swing图形对象

Java 未在JLabel中的图像上绘制Swing图形对象,java,swing,graphics2d,swingworker,Java,Swing,Graphics2d,Swingworker,我正在创建一个Java程序,该程序通过TCP套接字连接在地图的2D图像上接收并绘制GPS坐标。构造函数创建JFrame和图形组件,然后启动SwingWorker线程来处理从套接字获取坐标,然后绘制一个椭圆形来表示地图上的修复 我能够始终通过连接接收数据,但程序无法可靠地在图像上绘制点 任何建议,谢谢 import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.io.File; import

我正在创建一个Java程序,该程序通过TCP套接字连接在地图的2D图像上接收并绘制GPS坐标。构造函数创建JFrame和图形组件,然后启动SwingWorker线程来处理从套接字获取坐标,然后绘制一个椭圆形来表示地图上的修复

我能够始终通过连接接收数据,但程序无法可靠地在图像上绘制点

任何建议,谢谢

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

import connectivity.TelitSocketServer;
import calculations.PlottingMath;
import objects.ElephantFix;

@SuppressWarnings("serial")
public class Gui 
{
    protected JFrame mainWindow;

    protected JPanel mapArea = new JPanel();

    private ReceiveFix rfix;

    public Gui()
    {
        // TODO Auto-generated constructor stub

        mainWindow =  new JFrame();

        // Load map image
        Image map = null;
        try
        {
            File mapImage = new File("map_images/AWE_PLOT.JPG");
            map = ImageIO.read(mapImage);

        } catch (Exception e)
        {
            System.out.println(e.toString());
        }



        JLabel label = new JLabel(new ImageIcon(map));
        mapArea.add(label);


        // Map Image Dimensions

        mainWindow.getContentPane().add(mapArea, "Center");

        mainWindow.setSize(471, 670);
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setTitle("ElePlotter");
        mainWindow.setVisible(true);

        rfix = new ReceiveFix();
        rfix.execute();

}

public static void main(String args[])
{   
    new Gui(); 

}

private class ReceiveFix extends SwingWorker<Void, ElephantFix>
{

    @Override
    protected Void doInBackground()
    {
        // Start the server
        String fix = "";

        TelitSocketServer currentConnection = new TelitSocketServer();
        try
        {
            // Wait for client to connect
            currentConnection.intializeConnection();

            while (true)
            {
                // Parse and convert received GPS fix into arc radians  
                fix = currentConnection.readLine();

                String[] split = fix.split(" ");


                double latWholeDegrees = Double.parseDouble(split[0]
                        .substring(0, 3));
                double longWholeDegrees = Double.parseDouble(split[1]
                        .substring(0, 3));

                double latMinutes = Double.parseDouble(split[0]
                        .substring(3)) * .166667;
                double longMinutes = Double.parseDouble(split[1]
                        .substring(3)) * .166667;


                double lat = latWholeDegrees - latMinutes / 10;
                double lon = longWholeDegrees + longMinutes / 10;

                publish(new ElephantFix(lat, lon));
            }

        } catch (Exception e)
        {

            e.printStackTrace();
        }

        // Return null if somehow unable to publish node data
        return null;

    }


    @Override
    protected void process(List<ElephantFix> fixes)
    {
        int x, y;
        // Get the most recently published node
        ElephantFix aFix = fixes.get(fixes.size() - 1);



        // Translate lat/long into map X/Y pixel
        x = PlottingMath.getCurrentPixelX(aFix.getLatitude(),
                aFix.getLongitude());
        y = PlottingMath.getCurrentPixelY(aFix.getLatitude(),
                aFix.getLongitude());


        // Plot on image
        Graphics g = mapArea.getGraphics();

        g.setColor(Color.RED);

        g.fillOval(x, y, 15, 15);

        // mapArea.validate();
        //
        // mapArea.repaint();
        //
        // Gui.this.repaint();

    }
}

}
导入java.awt.Color;
导入java.awt.Graphics;
导入java.awt.Image;
导入java.io.File;
导入java.util.List;
导入javax.imageio.imageio;
导入javax.swing.ImageIcon;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.SwingWorker;
导入connectivity.TelitSocketServer;
导入计算。绘图数学;
导入objects.ElephantFix;
@抑制警告(“串行”)
公共类Gui
{
受保护的JFrame主窗口;
受保护的JPanel mapArea=新的JPanel();
私有ReceiveFix rfix;
公共图形用户界面()
{
//TODO自动生成的构造函数存根
mainWindow=新的JFrame();
//加载地图图像
图像映射=空;
尝试
{
文件mapImage=新文件(“map_images/AWE_PLOT.JPG”);
map=ImageIO.read(mapImage);
}捕获(例外e)
{
System.out.println(例如toString());
}
JLabel标签=新JLabel(新图像图标(地图));
mapArea.add(标签);
//地图图像尺寸
mainWindow.getContentPane().add(映射区域,“中心”);
主窗口。设置大小(471670);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
主窗口.setTitle(“绘图仪”);
mainWindow.setVisible(true);
rfix=新的ReceiveFix();
rfix.execute();
}
公共静态void main(字符串参数[])
{   
新Gui();
}
私有类ReceiveFix扩展SwingWorker
{
@凌驾
受保护的Void doInBackground()
{
//启动服务器
字符串fix=“”;
TelitSocketServer currentConnection=新建TelitSocketServer();
尝试
{
//等待客户端连接
currentConnection.intializeConnection();
while(true)
{
//解析并将接收到的GPS定位转换为弧度
fix=currentConnection.readLine();
String[]split=fix.split(“”);
双latWholeDegrees=double.parseDouble(拆分[0]
.子串(0,3));
double longWholeDegrees=double.parseDouble(拆分[1]
.子串(0,3));
double latMinutes=double.parseDouble(拆分[0]
.子串(3))*.166667;
double longments=double.parseDouble(拆分[1]
.子串(3))*.166667;
双lat=latWholeDegrees-latMinutes/10;
双lon=长全方位角度+长分钟/10;
出版(新ElephantFix(lat,lon));
}
}捕获(例外e)
{
e、 printStackTrace();
}
//如果无法发布节点数据,则返回null
返回null;
}
@凌驾
受保护的无效进程(列表修复)
{
int x,y;
//获取最近发布的节点
ElephantFix aFix=fixes.get(fixes.size()-1);
//将横向/纵向转换为贴图X/Y像素
x=PlottingMath.getCurrentPixelX(aFix.getLatitude(),
aFix.getLongitude());
y=PlottingMath.getCurrentPixelY(aFix.getLatitude(),
aFix.getLongitude());
//在图像上绘图
Graphics g=mapArea.getGraphics();
g、 setColor(Color.RED);
g、 椭圆形(x,y,15,15);
//mapArea.validate();
//
//mapArea.repaint();
//
//Gui.this.repaint();
}
}
}
mapArea.getGraphics()不是Swing中自定义绘制的方式

首先看一看,了解更多细节

将组件添加到容器可确保子组件始终绘制在容器上

JLabel label = new JLabel(new ImageIcon(map));
mapArea.add(label);
你把它倒过来了。最好将
标签
映射区域
添加到同一个容器中

您需要克服的下一个问题是,您需要使绘制组件位于标签顶部

为此,你可以

  • 使用
  • 使用
  • 使用
使用示例更新

有许多方法可以实现这一点,您可以使用多个组件作为层,您可以添加其他组件或执行自定义绘制

这并不像听起来那么容易。大多数布局管理器不考虑两个组件共享相同的空间。您还必须管理层之间的连接,因此如果贴图位于最底层的中心,但可用空间大于或小于贴图,偏移开始漂移…混乱

一个更简单的解决方案是使用单个组件并将所有内容呈现到其中,例如

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestMap {

    public static void main(String[] args) {
        new TestMap();
    }

    public TestMap() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                MapPane pane = new MapPane();
                pane.dropPinAt(174, 147);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(pane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MapPane extends JPanel {

        private BufferedImage img;
        private BufferedImage pin;
        private List<Point> pins;

        public MapPane() {
            pins = new ArrayList<>(25);
            try {
                img = ImageIO.read(getClass().getResource("/Map.jpg"));
                pin = ImageIO.read(getClass().getResource("/Pin.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();

                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;

                g2d.drawImage(img, x, y, this);

                for (Point p : pins) {
                    // Offset the pin x/y
                    // to allow the point to land on the desired location
                    p.x -= 6;
                    p.y -= 64;
                    System.out.println(p);
                    g2d.drawImage(pin, p.x, p.y, this);

                }

                g2d.dispose();
            }
        }

        protected void dropPinAt(int x, int y) {
            pins.add(new Point(x, y));
        }
    }

}

导入java.awt.BorderLayout;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Point;
导入java.awt.image.buffereImage;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.List;
导入javax.imageio.imageio;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
公共类测试图{
公共静态void main(字符串[]args){
新的TestMap();
}
公共测试图(){
invokeLater(新的Runnable(){
@凌驾
公共v