java Swing Image输出

[code="java"]
package com.hello.model;

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class NewImage {

public static void main(String[] args) throws IOException 
{
    JFrame frame = new JFrame();
    Image image = new ImageIcon("icon/baidu2.gif").getImage().getScaledInstance(33, -1, Image.SCALE_DEFAULT);
    MyPanel canvas = new MyPanel(image);

    frame.add(new JScrollPane(canvas));
    frame.pack();
    frame.setVisible(true); 
}

}

class MyPanel extends JPanel
{
Image image ;
final int ICON_WIDTH = 23;
final int ICON_HEIGHT = 22;

public MyPanel(Image image)
{
    this.image = image;
}
public void paint(Graphics g)
{
    //g.drawImage( image,(getWidth() - ICON_WIDTH)/2,(getHeight() - ICON_WIDTH)/2,null);  // 1
            g.drawImage( new ImageIcon("icon/baidu2.gif").getImage().getScaledInstance(33, -1,Image.SCALE_DEFAULT),(getWidth() - ICON_WIDTH)/2,(getHeight() - ICON_WIDTH)/2,null);               // 2

}

}
[/code]

为什么2 处代码没有输出,1处代码却可以输出图片?
两处的代码是完全一样的啊。。。。

4个回答

使用ImageIO这个能够保证图片被正确加载。

你用DEBUG方式启动,然后再在这里设置个断点,就会明白为什么 产生两个不同的结果

[code="java"]g.drawImage( new ImageIcon("icon/baidu2.gif").getImage().getScaledInstance(33, -1, Image.SCALE_DEFAULT),(getWidth() - ICON_WIDTH)/2,(getHeight() - ICON_WIDTH)/2,null); [/code]

MyPanel类下的paint会被多次执行,放在里面的代码new的话,就会多次被创建新对像了

因为图像数据还未完全加载
[code="java"] public void paint(Graphics g) {
// g.drawImage(image, (getWidth() - ICON_WIDTH) / 2, (getHeight() -
// ICON_WIDTH) / 2, null); // 1
Image image = new ImageIcon("d:/1.gif").getImage().getScaledInstance(33, -1, Image.SCALE_DEFAULT);
waitForImage(this,image);
g.drawImage(image, (getWidth() - ICON_WIDTH) / 2, (getHeight() - ICON_WIDTH) / 2, null); // 2

}

/**
 * Wait for loading all image data into memory.
 */
public static void waitForImage(Component component, Image img) {
    MediaTracker tracker = new MediaTracker(component);
    try {
        tracker.addImage(img, 0);
        tracker.waitForID(0);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}[/code]

[code="java"]
//g.drawImage( image,(getWidth() - ICON_WIDTH)/2,(getHeight() - ICON_WIDTH)/2,null); // 1

g.drawImage( new ImageIcon("icon/baidu2.gif").getImage().getScaledInstance(33, -1,Image.SCALE_DEFAULT),(getWidth() - ICON_WIDTH)/2,(getHeight() - ICON_WIDTH)/2,null); // 2

[/code]

1和2在这里是有区别的。
1在这里使用的是image这个实例不管你拉伸,收缩界面时,图像再次绘制时。都是这个对象。
2 在这里是给定了一个行的图片对象。

看上去你的代码逻辑确实没有问题。你的写法不是很好!

正确的写法:
[code="java"]
public void paint(Graphics g)

    {   
        try {
            this.image = ImageIO.read(new File("C:\\tmp\\liuqing.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } ;
        g.drawImage(image ,(getWidth() - ICON_WIDTH)/2,
                                (getHeight() - ICON_WIDTH)/2,null);                  

    }  

[/code]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java jtextfield文本输出

大家好,我在jtextfield写的文本,怎么随时打印出来?用jtextfield.gettext(),弄不出来!

在用java swing 时遇到关于设置背景图片的问题

public class LoginPanel extends JPanel { protected ImageIcon icon;//protected的访问权限是同一个包的类即可访问它 public int width,height; public LoginPanel(){ super();//调用父类的构造方法,此处可以不显示调用,系统会自动隐式调用 icon=new ImageIcon("res/login.jpg"); width=icon.getIconWidth(); height=icon.getIconHeight(); setSize(width,height);//调用继承自父类JPanel中 的setSize()方法设置面板的大小因为是继承来的是自己的了所以在类内可以不用实例对象去调用 //this.setSize(width,height); } //想要将这张图片作为背景图片,是不能直接使用add()方法添加该icon对象的;在LoginPanel类中重写paintComponent()方法,并在该方法中调用Graphics类的drawImage()方法绘制该图片 //重写paintComponent()方法 protected void paintComponent(Graphics g){ super.paintComponent(g);//调用父类的paintComponent()方法 Image img = icon.getImage(); g.drawImage(img,100,100,this);//在当前面板中绘制该Image文件 img;this参数表示图片绘制在哪里 System.out.println("执行了paintComponent()方法"); } 为什么在主类中使用new LoginPanel()实现一个实例对象时,函数会执行重写的paintComponent(Graphics g)方法(输出了执行了paintComponent()方法);原则上这个方法LoginPanel中的实例方法,,在实例化类的时候不应该会执行的啊? 请问为什么这里会被执行,或者说实例化 对象时类中的哪些部分会被执行哪些不被执行,求大神帮忙总结一下 附测试用的主函数代码 public class test { public static void main(String[] args) { // TODO Auto-generated method stub JFrame.setDefaultLookAndFeelDecorated(true); JFrame jf = new JFrame(); jf.add(new LoginPanel()); jf.setVisible(true); jf.setSize(800,800); jf.setLocationRelativeTo(null); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

JAVA中在JPanel里调用Graphics实现循环产生动画的问题。

想要实现用JAVA绘制简单的动画效果,大致就是先建一个JFrame对象,在里面添加一个JPanel,然后在JPanel里面用Graphics来进行画图,重复进行绘制一个与背景相同颜色的一张图像,在绘制一张其他的图像,经过一段时间之后重复进行。效果就是在一个背景中图像像右方移动。 在Graphics里面添加for语句在JFrame里面可以实现的。但是放到了JPanel里面就不行了,只会显示循环结束之后的图像,希望能够知道这个是什么原因造成的,能够用什么方法解决,望高手指教。 代码如下: package Jpg_2; import javax.swing.*; import java.awt.*; public class jpg_2 { public static void main(String[] args) { frame f=new frame(); } } class frame extends JFrame { CJPanel c; frame() { super("图片"); setSize(500,500); c=new CJPanel(); this.add(c); c.repaint(); setVisible(true); } class CJPanel extends JPanel { ImageIcon icon=new ImageIcon("f:/3.png"); ImageIcon icon2=new ImageIcon("f:/4.png"); Image image=icon.getImage(); Image image2=icon2.getImage(); public void paint(Graphics g) { g.drawImage(image,20,20,this); g.setColor(Color.red); g.fillRect(0,0,500,500); for (int i=20;i<180;i++) { g.drawImage(image2,i,20,this); g.drawImage(image,i+1,20,this); try { Thread.sleep(10); } catch(InterruptedException e){} } } } }

学了一天线程动画的java新丁求助一个问题

我好奇按照网上的教程写了一段java线程动画,但是repaint()这个地方只能执行一次, 请问下高手这是怎么回事呢?从输出结果看,repaint()只运行了一次,但是 PaintThread却每隔40毫秒就执行一次,对照了好几遍,都没发现是哪错了,请高手指点下 ``` package study; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import javax.management.timer.Timer; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextField; public class swing extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { swing frame = new swing(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public swing() {//布局 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); } int x = 120; int y = 120; public void paint(Graphics g){//绘制线图 Image img = GameUtil.getImage("images/小车.jpg"); g.setColor(Color.BLUE); g.fillRect (200, 0, 50, 300); g.fillRect (0, 120, 450, 50); g.drawImage(img, x, y,null); new PaintThread().start(); x+=3; y+=3; System.out.println(1); } } class PaintThread extends Thread{//PaintThread int x = 120; int y = 120; public void run(){//run swing paint = new swing(); while(true){//while try {//try paint.repaint(); System.out.println(2); Thread.sleep(40);//40毫秒,相当于每秒25帧 } catch (InterruptedException e) {//catchtry // TODO Auto-generated catch block e.printStackTrace(); }//catch }//while }//run }//PaintThread ```

java 以下代码想要实现从硬盘中拿一张图片然后放在面板上,为什么不行呢?

import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.imageio.stream.FileImageInputStream; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.filechooser.FileNameExtensionFilter; public class FunctionChangeBack extends JPanel { JMenuBar bar ; JMenu menu ; JMenuItem openFile ; JFrame frame ; public FunctionChangeBack () { panelSet () ; barSet () ; frameSet () ; } public void paintComponent (Graphics g) { super.paintComponent(g) ; } public void panelSet () { } public void frameSet () { frame = new JFrame () ; frame.setLayout(null) ; frame.add(bar) ; frame.add(this) ; frame.setVisible(true) ; frame.setSize(1024, 768) ; } public void barSet () { bar = new JMenuBar () ; menu = new JMenu ("打开") ; openFile = new JMenuItem ("文件") ; openFile.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser ("src\\game2\\image") ; int rs = jfc.showOpenDialog(FunctionChangeBack.this) ; FileNameExtensionFilter fnef = new FileNameExtensionFilter ("JPGFile","jpg") ; jfc.addChoosableFileFilter(fnef) ; if(rs == JFileChooser.APPROVE_OPTION) { try { File file = jfc.getSelectedFile() ; FileImageInputStream fiis = new FileImageInputStream (file) ; FileInputStream fis = new FileInputStream (file) ; byte[] by = new byte[fis.available()] ; while(fiis.read(by) != -1) { fiis.flush() ; } fiis.close() ; fis.close() ; FunctionChangeBack.this.getImage(by) ; } catch (IOException e1) { e1.printStackTrace(); } } } }); menu.add(openFile) ; bar.add(menu) ; bar.setBounds(0, 0, 1024, 50) ; } public void getImage(byte[] by) { System.out.println(by.length) ; ImageIcon icon = new ImageIcon (by) ; Image image = this.createImage(1024,768) ; Graphics gg = image.getGraphics() ; Graphics g = this.getGraphics() ; System.out.println(icon.getIconWidth()+" "+icon.getIconHeight()) ; gg.drawImage(icon.getImage(), 0, 0, 1024, 768, this) ; g.drawImage(image, 0, 0, 1024, 768, this) ; } public static void main (String [] args) { new FunctionChangeBack () ; } } 我已经从硬盘里面拿到了一张图片了,由我自己写的getimage方法里面的两个println语句可以看出我可以输出这张图片的宽和高,但是为什么画出的图没有显示在面板上呢?多谢各位解答!

Java frame中调用了setContentPane(new Panel());方法,但不显示Panel

代码如下: **PanelGame类:** package ui; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JPanel; public class PanelGame extends JPanel{ //创建一个对象数组,存储各个边框 private Lay[] lays=null; //TODO 【硬编码】是非常不好的开发习惯 //TODO 尽量将数字货字符串定义为常量,或写入配置文件 public PanelGame() { this.setVisible(true); lays = new Lay[]{ new LayDataBase(40,32,334,279), new LayDisk(40,343,334,279), new LayGame(414,32,334,590), new LayButton(788,32,334,124), new LayNext(788,188,176,148), new LayLevel(964,188,158,148), new LayPoint(788,368,334,200) }; } public void pointComponent(Graphics g){ //test g.fillRect(32, 32, 32, 32); //循环刷新游戏画面 for(int i=0;i<lays.length;i++){ //刷新每一个边框 lays[i].paint(g); } } } FrameGame类: package ui; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import javax.swing.ImageIcon; import javax.swing.JFrame; public class FrameGame extends JFrame{ public FrameGame() { //设置标题 this.setTitle("Tetris by 柴源"); //设置窗口关闭 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口大小 this.setSize(1200, 700); //设置 不允许用户改变窗口大小 this.setResizable(false); //设置窗口位置 Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screen = toolkit.getScreenSize(); int x = (screen.width-this.getWidth())/2; int y = (screen.height-this.getHeight())/2-32; //此处用-32,因为Y轴正方向向下 this.setLocation(x,y); //设置默认Panel this.setContentPane(new PanelGame()); } } **Lay类(抽象类):** package ui; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; /* * 抽象类LAY,用于实现各个子窗体的绘制, * */ public abstract class Lay { //定义几个静态变量,供绘制方法createWindow使用 private static final int SIZE=7; private static Image WINDOW_IMG=new ImageIcon("graphics/window/Window.png").getImage(); private static int WINDOW_W=WINDOW_IMG.getWidth(null); private static int WINDOW_H=WINDOW_IMG.getHeight(null); //定义属性,窗口左上角坐标(x,y)以及窗口宽W高H private int x; private int y; private int w; private int h; //构造器,赋予窗体左上角位置(X,Y) 以及宽W高H public Lay(int x,int y, int w, int h) { // TODO Auto-generated constructor stub this.x=x; this.y=y; this.w=w; this.h=h; } //绘制窗口方法 绘制的方法必须有Graphics g参数,类似画笔 public void createWindow(Graphics g){ //原函数:g.drawImage(img,x1,y1,x2,y2,x3,y3,x4,y4,observer); //左上角 g.drawImage(WINDOW_IMG, x, y,x+SIZE,y+SIZE, 0, 0, SIZE, SIZE, null); //右上角 g.drawImage(WINDOW_IMG, x+w-SIZE, y,x+w,y+SIZE, WINDOW_W-SIZE, 0, WINDOW_W, SIZE, null); //左下角 g.drawImage(WINDOW_IMG, x, y+h-SIZE,x+SIZE,y+h, 0, WINDOW_H-SIZE, SIZE, WINDOW_H, null); //右下角 g.drawImage(WINDOW_IMG, x+w-SIZE, y+h-SIZE,x+w,y+h, WINDOW_W-SIZE, WINDOW_H-SIZE, WINDOW_W, WINDOW_H, null); //上边 g.drawImage(WINDOW_IMG, x+SIZE, y, x+w-SIZE, y, SIZE,0, WINDOW_W-SIZE, 0, null); //下边 g.drawImage(WINDOW_IMG, x+SIZE, y+h, x+w-SIZE, y+h, SIZE,WINDOW_H, WINDOW_W-SIZE, WINDOW_H, null); //左边 g.drawImage(WINDOW_IMG, x, y+SIZE, x, y+h-SIZE, 0,SIZE, 0, WINDOW_H-SIZE, null); //右边 g.drawImage(WINDOW_IMG, x+w, y+SIZE, x+w, y+h-SIZE, WINDOW_W , SIZE , WINDOW_W ,WINDOW_H-SIZE, null); } abstract public void paint(Graphics g); } 实现Lay类的子类代码我就不贴了... 问题主要在于: 已经在FrameGame类里头用了this.setContentPane(new PanelGame()); 希望通过PanelGame里输出了一些图片(通过创建Lay对象输出图片) 但是Run以后,貌似连Panel都不显示...图片路径检查了应该没问题。 求指点,谢了!

JAVA图片浏览器的音乐播放,在切换下一首歌的时候,当前的歌还在播放,怎么解决?

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; public class HOME extends JFrame implements ActionListener, ListSelectionListener { double height; JLabel imageview = new JLabel(); JButton b1 = new JButton(); JButton profile_photo = new JButton(); JButton switch1 = new JButton("<"); JButton switch2 = new JButton(">"); JButton First = new JButton("首张"); JButton Last = new JButton("末张"); ImageIcon icon1 = null; ImageIcon icon2 = null; JPanel North = new JPanel(); JPanel South = new JPanel(); JPanel Center = new JPanel(); JPanel West = new JPanel(); JPanel East = new JPanel(); JFileChooser chooser = new JFileChooser(); JMenuBar menuBar = new JMenuBar(); JTextArea phototext = new JTextArea(); String photo_name; // 文件列表 String Path = "./image"; File file = new File(Path); File[] list = file.listFiles(); int index = 0; /// 音乐播放 //音乐文件列表 String musicPath = "./music"; File musicfile = new File(musicPath); File[] musiclist = musicfile.listFiles(); int index_music = 0; JButton play = new JButton("播放"); JButton stop = new JButton("停止"); JButton playlast = new JButton("|<"); JButton playnext = new JButton(">|"); boolean isPlaying = false; boolean isRestart = false; Audio audio = new Audio(); // 菜单项 JMenuItem choosephoto = new JMenuItem("打开图片"); //图片列表 private String[] lists = { "111","222","333","444","555","666","777","888","999"}; JList photolist = new JList(list); public HOME() { // 框架设置 setTitle("图片浏览器"); setLocation(300, 100); setSize(1300, 900); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); setLayout(new BorderLayout()); //图片列表 photolist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollpane = new JScrollPane(photolist); scrollpane .setPreferredSize(new Dimension(100,500)); //滚动条的大小即可调整列表长宽,如果想再加入一条横向滚动条,可设置列表的preferredSize // 组件添加 North.setLayout(new BorderLayout()); // 此处没有设置South的布局,因为设置后再将South面板放入框架中时,发现三个按钮无法全部加入,只能加入最后一个 Center.setLayout(new BorderLayout()); North.add(menuBar); add(North, BorderLayout.NORTH); Center.add(imageview); add(Center, BorderLayout.CENTER); West.add(scrollpane); //此处只需加入滚动条即可。不需要再加入photolist South.add(play); South.add(stop); South.add(playlast); South.add(playnext); South.add(switch1); South.add(switch2); South.add(First); South.add(Last); add(South, BorderLayout.SOUTH); add(East, BorderLayout.EAST); add(West, BorderLayout.WEST); // 监听器添加 switch1.addActionListener(this); switch2.addActionListener(this); First.addActionListener(this); Last.addActionListener(this); play.addActionListener(this); stop.addActionListener(this); playlast.addActionListener(this); playnext.addActionListener(this); photolist.addListSelectionListener(this); // 图像设置 // 头像/ ImageIcon image_local1 = new ImageIcon("./image/头像.jpg"); Image imageget1 = image_local1.getImage(); Image finalimage1 = imageget1.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING); icon1 = new ImageIcon(finalimage1); // 图片/ // 组件设置 lb1.setFont(new Font("宋体", Font.BOLD, 20)); b1.setIcon(icon1); switch1.setVisible(true); switch2.setVisible(true); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); phototext.setFont(new Font("宋体", Font.BOLD, 20)); phototext.setEditable(false); Menu(); // 线程启动 audio.start(); isPlaying = true; } public void Menu() { this.add(menuBar, BorderLayout.NORTH); this.setJMenuBar(menuBar); JMenu file = new JMenu("文件"); JMenuItem photolist = new JMenuItem("图片列表"); menuBar.add(file); menuBar.add(photolist); menuBar.add(phototext); menuBar.add(b1); file.add(choosephoto); setVisible(true); // 文件选择 chooser.setCurrentDirectory(new File("./image")); choosephoto.addActionListener(this); } @Override public void valueChanged(ListSelectionEvent e) { if(e.getSource() == photolist) { int index = photolist.getLeadSelectionIndex(); phototext.setText(""); photo_name = list[index].getPath(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(),Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(list[index].getName()); String filename = file.getName(); double size = (file.length() / 1024.00); System.out.print(file.length()); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); } } private final Set<Long> THREADS = new HashSet<>(); public void someMethod () { if (THREADS.contains(Thread.currentThread().getId())) { throw new RuntimeException("该线程不能再调用这个方法"); } THREADS.add(Thread.currentThread().getId()); // 方法内容 } public void actionPerformed(ActionEvent e) { Runnable action = () ->{ if (e.getSource() == switch1) { while (index <= list.length) { if (index == 0) { JOptionPane.showMessageDialog(West, "已经是第一张图", "提示", JOptionPane.WARNING_MESSAGE); break; } index--; phototext.setText(""); photo_name = list[index].getPath(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(), Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(list[index].getName()); String filename = file.getName(); double size = (file.length() / 1024.00); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); break; } } if (e.getSource() == switch2) { while (index <= list.length) { if (index == list.length) { JOptionPane.showMessageDialog(West, "已经是最后一张图", "提示", JOptionPane.WARNING_MESSAGE); } phototext.setText(""); photo_name = list[index].getPath(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(), Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(list[index].getName()); String filename = file.getName(); double size = (file.length() / 1024.00); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); index++; break; } } if(e.getSource() == First) { index=0; phototext.setText(""); photo_name = list[index].getPath(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(), Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(list[index].getName()); String filename = file.getName(); double size = (file.length() / 1024.00); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); } if(e.getSource() == Last) { index=list.length-1; phototext.setText(""); photo_name = list[index].getPath(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(), Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(list[index].getName()); String filename = file.getName(); double size = (file.length() / 1024.00); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); } if (e.getActionCommand() == "打开图片") { int choose = chooser.showOpenDialog(null); if (choose == JFileChooser.APPROVE_OPTION) { phototext.setText(""); photo_name = chooser.getSelectedFile().getName(); ImageIcon image_local2 = new ImageIcon(photo_name); Image imageget2 = image_local2.getImage(); Image finalimage2 = imageget2.getScaledInstance(Center.getWidth(), Center.getHeight(), Image.SCALE_AREA_AVERAGING); icon2 = new ImageIcon(finalimage2); imageview.setIcon(icon2); imageview.setBounds(50, 50, 500, 500); File file = new File(chooser.getSelectedFile().getName()); String filename = file.getName(); double size = (file.length() / 1024.00); phototext.setText(filename + " (" + String.valueOf(size) + "KB)"); } } if (e.getActionCommand() == "播放") { String filePath = "./music"; try { System.out.print("运行了"); Runnable play = ( ) ->{ audio.run(); }; Thread t1 = new Thread(play); t1.start(); isPlaying = true; } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } if (e.getSource() == stop) { try { System.out.print("停止了"); isPlaying = false; isRestart = false; } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } if (e.getSource() == playnext) { try { System.out.print("下一个"); isPlaying = false; Runnable r =() ->{ try { someMethod(); index_music++; isRestart = true; audio.restart(); } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }; Thread t = new Thread(r); t.start(); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } if (e.getSource() == playlast) { try { if(index_music == 0) { JOptionPane.showMessageDialog(West, "已经是第一首背景音乐", "提示", JOptionPane.WARNING_MESSAGE); } isPlaying = false; isRestart = true; } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }; Thread act = new Thread(action); act.start(); } public class Audio extends Thread { public Audio() { } public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println(e.toString()); } if (isPlaying) { try { System.out.print("启动了"); player(); } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { e.printStackTrace(); } } } public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException { if(isRestart) { System.out.print("测试了~?"); isPlaying =true; player(); } } // 取得文件输入流 private void player() throws UnsupportedAudioFileException, IOException, LineUnavailableException { AudioInputStream audioInputStream;// 文件流 AudioFormat audioFormat;// 文件格式 SourceDataLine sourceDataLine;// 输出设备 String musicname = musiclist[index_music].getName(); File file = new File("./music/"+musicname); audioInputStream = AudioSystem.getAudioInputStream(file); audioFormat = audioInputStream.getFormat(); // 转换文件编码 if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels() * 2, audioFormat.getSampleRate(), false); audioInputStream = AudioSystem.getAudioInputStream(audioFormat, audioInputStream); } // 打开输出设备 DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat, AudioSystem.NOT_SPECIFIED); sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceDataLine.open(audioFormat); // 打开具有指定格式的行,这样可以使行获得所有所需的系统资源并变得可操作 sourceDataLine.start(); // 允许某一数据行执行数据I/O byte tempBuffer[] = new byte[320]; try { int cnt; // 读取数据到缓存区 // 从音频流读取指定的最大数量的数据字节,并将其放入给定的字节数组中。 // return: 读入缓冲区的总字节数;如果因为已经到达流末尾而不再有更多数据,则返回-1 while ((cnt = audioInputStream.read(tempBuffer, 0,tempBuffer.length)) != -1 &&isPlaying) { if (cnt > 0) { // 写入缓存数据 sourceDataLine.write(tempBuffer, 0, cnt); // 通过此源数据行将音频数据写入混频器 } } // Block等待临时数据被输出为空 // 通过在清空数据行的内部缓冲区之前继续数据I/O,排空数据行中的列队数据 sourceDataLine.drain(); // 关闭行,指示可以释放的该行使用的所有系统资源。如果此操作成功,则将行标记为 closed,并给行的侦听器指派一个 CLOSE 事件。 sourceDataLine.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } public static void main(String[] args) { Runnable h = () ->{ HOME home = new HOME(); }; Thread t = new Thread(h); t.start(); } } ``` ```playnext那一部分是切下一首歌,但是切了后当前的歌曲仍在播放,怎么解决

java 实现 sparksql 时,mysql数据库查询结果只有表头没有数据

这两天尝试用java实现sparksql连接mysql数据库,经过调试可以成功连接到数据库,但奇怪的是只能够查询出表头和表结构却看不到表里面数据 代码如下 import java.util.Hashtable; import java.util.Properties; import javax.swing.JFrame; import org.apache.avro.hadoop.io.AvroKeyValue.Iterator; import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolServerSideTranslatorPB; import org.apache.hadoop.hive.ql.exec.vector.expressions.IsNull; import org.apache.log4j.Logger; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.DataFrameReader; import org.apache.spark.sql.DataFrameWriter; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.SparkSession.Builder; import org.apache.spark.sql.jdbc.JdbcDialect; import org.datanucleus.store.rdbms.identifier.IdentifierFactory; import antlr.collections.List; import scala.Enumeration.Val; public class Demo_Mysql3 { private static Logger logger = Logger.getLogger(Demo_Mysql3.class); public static void main(String[] args) { SparkConf sparkConf = new SparkConf(); sparkConf.setAppName("Demo_Mysql3"); sparkConf.setMaster("local[5]"); sparkConf.setSparkHome("F:\\DownLoad\\spark\\spark-2.0.0-bin-hadoop2.7"); sparkConf.set("spark.sql.warehouse.dir","F:\\DownLoad\\spark\\spark-2.0.0-bin-hadoop2.7"); SparkContext sc0=null; try { sc0=new SparkContext(sparkConf); SparkSession sparkSession=new SparkSession(sc0); SQLContext sqlContext = new SQLContext(sparkSession); // 一个条件表示一个分区 String[] predicates = new String[] { "1=1 order by id limit 400000,50000", "1=1 order by id limit 450000,50000", "1=1 order by id limit 500000,50000", "1=1 order by id limit 550000,50000", "1=1 order by id limit 600000,50000" }; String url = "jdbc:mysql://localhost:3306/clone"; String table = "image"; Properties connectionProperties = new Properties(); connectionProperties.setProperty("dbtable", table);// 设置表 connectionProperties.setProperty("user", "root");// 设置用户名 connectionProperties.setProperty("password", "root");// 设置密码 // 读取数据 DataFrameReader jread = sqlContext.read(); //Dataset<Row> jdbcDs=jread.jdbc(url, table, predicates, connectionProperties); sqlContext.read().jdbc(url, table, predicates, connectionProperties).select("*").show(); } catch (Exception e) { logger.error("|main|exception error", e); } finally { if (sc0 != null) { sc0.stop(); } } } } 控制台输出如下: ![图片说明](https://img-ask.csdn.net/upload/201707/22/1500708689_839040.png)

ImageIo.write()保存图片,保存后的图片是漆黑的

@Override public void actionPerformed(ActionEvent e) { BufferedImage bufferImage = new BufferedImage(im.getWidth(SaveImageFrame.this), im.getHeight(SaveImageFrame.this), BufferedImage.TYPE_INT_RGB); g = (Graphics2D)bufferImage.getGraphics(); try { ImageIO.write(bufferImage, "jpg", new File("d:/"+iname+".jpg")); } catch (IOException e1) { e1.printStackTrace(); } } 保存在d盘的图片是漆黑的

注入资源依赖关系失败

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paiMaiSerDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dlsp.service.PaiMaiSerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)} at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dlsp.service.PaiMaiSerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303) ... 22 more 二月 24, 2017 11:03:25 上午 org.apache.catalina.core.StandardContext startInternal 严重: One or more listeners failed to start. Full details will be found in the appropriate container log file 二月 24, 2017 11:03:25 上午 org.apache.catalina.core.StandardContext startInternal 严重: Context [/ZuoYeXiangMu_3] startup failed due to previous errors 二月 24, 2017 11:03:25 上午 org.apache.catalina.core.ApplicationContext log 信息: Closing Spring root WebApplicationContext 二月 24, 2017 11:03:25 上午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc 警告: The web application [ZuoYeXiangMu_3] registered the JDBC driver [oracle.jdbc.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 二月 24, 2017 11:03:25 上午 org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks 严重: The web application [ZuoYeXiangMu_3] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@41376b06]) and a value of type [java.lang.Class] (value [class oracle.sql.AnyDataFactory]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak. 二月 24, 2017 11:03:25 上午 org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks 严重: The web application [ZuoYeXiangMu_3] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@7b5d1ae6]) and a value of type [java.lang.Class] (value [class oracle.sql.TypeDescriptorFactory]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak. 二月 24, 2017 11:03:25 上午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-nio-8080"] 二月 24, 2017 11:03:25 上午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["ajp-nio-8009"] 二月 24, 2017 11:03:25 上午 org.apache.catalina.startup.Catalina start 信息: Server startup in 4212 ms package com.dlsp.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.dlsp.dao.UserLoginDao; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; import com.dlsp.service.PaiMaiSerDao; import com.dlsp.service.UserLoginSerDao; import com.dlsp.service.impl.PaiMaiSerDaoImpl; import com.sun.java.swing.plaf.motif.resources.motif; import com.sun.org.apache.regexp.internal.recompile; @Controller public class PaiMaicontroler { @Resource private PaiMaiSerDao paimai; //获得随机颜色 Color getRandColor(int fc, int bc){ Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } //验证码 @RequestMapping("yanzheng.action") public void yanzhengn(HttpServletRequest request,HttpServletResponse response,HttpSession session){ //设置页面不缓存 session=request.getSession(); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 在内存中创建图象 int width = 60, height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); //设定字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //画边框 //g.setColor(new Color()); //g.drawRect(0,0,width-1,height-1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码(4位数字) String sRand = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(random.nextInt(10)); sRand += rand; // 将认证码显示到图象中 g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand, 13 * i + 6, 16); } // 将认证码存入SESSION session.setAttribute("numrand", sRand); // 图象生效 g.dispose(); // 输出图象到页面 try { ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //out.clear(); //out = PageContext.pushBody(); } @RequestMapping("saleinfo.action") public String getsuoyou(Model mo) { List<Saleinfo> jihe = paimai.getall(); mo.addAttribute("jihe", jihe); return "saleinfo"; } @RequestMapping("addinfo.action") public String addinfo(Saleinfo sale, Model mo) { if (paimai.insertsale(sale) > 0) { mo.addAttribute("cheng", 1); } else { mo.addAttribute("cheng", 2); } return "redirect:saleinfo.action"; } @RequestMapping("update.action") public String updateinfo(Saleinfo sale,Model mo){ if (paimai.updatedale(sale)>0) { mo.addAttribute("gai", 1); }else{ mo.addAttribute("gai", 2); } return "redirect:saleinfo.action"; } @RequestMapping("sahn.action") public String deleteinfo(int id,Model mo){ if (paimai.deletesale(id)>0) { mo.addAttribute("shan", 1); }else{ mo.addAttribute("shan", 2); } return "redirect:saleinfo.action"; } } package com.dlsp.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.dlsp.dao.UserLoginDao; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; import com.dlsp.service.PaiMaiSerDao; import com.dlsp.service.UserLoginSerDao; import com.dlsp.service.impl.PaiMaiSerDaoImpl; import com.sun.java.swing.plaf.motif.resources.motif; import com.sun.org.apache.regexp.internal.recompile; @Controller public class PaiMaicontroler { @Resource private PaiMaiSerDao paimai; //获得随机颜色 Color getRandColor(int fc, int bc){ Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } //验证码 @RequestMapping("yanzheng.action") public void yanzhengn(HttpServletRequest request,HttpServletResponse response,HttpSession session){ //设置页面不缓存 session=request.getSession(); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 在内存中创建图象 int width = 60, height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); //设定字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //画边框 //g.setColor(new Color()); //g.drawRect(0,0,width-1,height-1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码(4位数字) String sRand = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(random.nextInt(10)); sRand += rand; // 将认证码显示到图象中 g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand, 13 * i + 6, 16); } // 将认证码存入SESSION session.setAttribute("numrand", sRand); // 图象生效 g.dispose(); // 输出图象到页面 try { ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //out.clear(); //out = PageContext.pushBody(); } @RequestMapping("saleinfo.action") public String getsuoyou(Model mo) { List<Saleinfo> jihe = paimai.getall(); mo.addAttribute("jihe", jihe); return "saleinfo"; } @RequestMapping("addinfo.action") public String addinfo(Saleinfo sale, Model mo) { if (paimai.insertsale(sale) > 0) { mo.addAttribute("cheng", 1); } else { mo.addAttribute("cheng", 2); } return "redirect:saleinfo.action"; } @RequestMapping("update.action") public String updateinfo(Saleinfo sale,Model mo){ if (paimai.updatedale(sale)>0) { mo.addAttribute("gai", 1); }else{ mo.addAttribute("gai", 2); } return "redirect:saleinfo.action"; } @RequestMapping("sahn.action") public String deleteinfo(int id,Model mo){ if (paimai.deletesale(id)>0) { mo.addAttribute("shan", 1); }else{ mo.addAttribute("shan", 2); } return "redirect:saleinfo.action"; } } package com.dlsp.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.dlsp.dao.UserLoginDao; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; import com.dlsp.service.PaiMaiSerDao; import com.dlsp.service.UserLoginSerDao; import com.dlsp.service.impl.PaiMaiSerDaoImpl; import com.dlsp.service.impl.UserLoginService; import com.sun.java.swing.plaf.motif.resources.motif; import com.sun.org.apache.regexp.internal.recompile; @Controller public class UserLogincontroler { @Resource private UserLoginSerDao login; @RequestMapping("admin.action") public String asdsa(){ return "admin"; } //普通登陆判断 @RequestMapping("dengdeng.action") public String denglu(Manage ma,Model mo,String checkbox){ ma=login.loginman(ma); if (!ma.equals("")) { if (ma.getAdmin()==1) { mo.addAttribute("user", ma); if (!checkbox.equals("")) { Cookie co=new Cookie("username", ma.getManame()); } return "saleinfo"; } return "admin"; } return "admin"; } //转换管理员登陆界面 @RequestMapping("denglu.action") public String denglupan(Model mo){ mo.addAttribute("admin", "123123"); return "admin"; } //转换普通用户登陆界面 @RequestMapping("dengluq.action") public String denglupantwo(Model mo){ mo.addAttribute("admin", null); return "admin"; } } package com.dlsp.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.dlsp.dao.UserLoginDao; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; import com.dlsp.service.PaiMaiSerDao; import com.dlsp.service.UserLoginSerDao; import com.dlsp.service.impl.PaiMaiSerDaoImpl; import com.dlsp.service.impl.UserLoginService; import com.sun.java.swing.plaf.motif.resources.motif; import com.sun.org.apache.regexp.internal.recompile; @Controller public class UserLogincontroler { @Resource private UserLoginSerDao login; @RequestMapping("admin.action") public String asdsa(){ return "admin"; } //普通登陆判断 @RequestMapping("dengdeng.action") public String denglu(Manage ma,Model mo,String checkbox){ ma=login.loginman(ma); if (!ma.equals("")) { if (ma.getAdmin()==1) { mo.addAttribute("user", ma); if (!checkbox.equals("")) { Cookie co=new Cookie("username", ma.getManame()); } return "saleinfo"; } return "admin"; } return "admin"; } //转换管理员登陆界面 @RequestMapping("denglu.action") public String denglupan(Model mo){ mo.addAttribute("admin", "123123"); return "admin"; } //转换普通用户登陆界面 @RequestMapping("dengluq.action") public String denglupantwo(Model mo){ mo.addAttribute("admin", null); return "admin"; } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dlsp.dao.PaiMaiDao"> <sql id="sale"> said,saname,startmoney,endmondey,starttime,endtime,panduan,remark </sql> <sql id="man"> id,maname,password,cardnum,tell, dizhi,youzheng,admin </sql> <!-- 基本的用户信息 --> <resultMap id="paimaiMP" type="com.dlsp.domain.Saleinfo"> <id property="said" column="said" /> <result property="saname" column="saname" /> <result property="startmoney" column="startmoney" /> <result property="endmondey" column="endmondey" /> <result property="starttime" column="starttime" /> <result property="endtime" column="endtime" /> <result property="panduan" column="panduan" /> <result property="remark" column="remark" /> </resultMap> <resultMap type="com.dlsp.domain.Manage" id="manageMP"> <id property="id" column="id" /> <result property="maname" column="maname" /> <result property="password" column="password" /> <result property="cardnum" column="cardnum" /> <result property="tell" column="tell" /> <result property="dizhi" column="dizhi" /> <result property="youzheng" column="youzheng" /> <result property="admin" column="admin" /> </resultMap> <select id="getall" resultMap="paimaiMP" > select <include refid="sale"/> from saleinfo </select> <select id="loginman" resultMap="manageMP"> select <include refid="man"/> from manage </select> </mapper> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dlsp.dao.UserLoginDao"> <sql id="man"> id,maname,password,cardnum,tell, dizhi,youzheng,admin </sql> <resultMap type="com.dlsp.domain.Manage" id="manageMP"> <id property="id" column="id" /> <result property="maname" column="maname" /> <result property="password" column="password" /> <result property="cardnum" column="cardnum" /> <result property="tell" column="tell" /> <result property="dizhi" column="dizhi" /> <result property="youzheng" column="youzheng" /> <result property="admin" column="admin" /> </resultMap> <select id="loginman" parameterType="com.dlsp.domain.Manage" resultType="com.dlsp.domain.Manage"> select <include refid="man"/> from manage where maname=#{maname} and password=#{password} </select> </mapper> package com.dlsp.service; import java.util.List; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; public interface PaiMaiSerDao { //查 List<Saleinfo> getall(); //增 int insertsale(Saleinfo sale); //删 int deletesale(int id); //改 int updatedale(Saleinfo sale); } package com.dlsp.service; import com.dlsp.domain.Manage; public interface UserLoginSerDao { //登陆 Manage loginman(Manage manage); } package com.dlsp.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dlsp.dao.PaiMaiDao; import com.dlsp.domain.Manage; import com.dlsp.domain.Saleinfo; import com.dlsp.service.PaiMaiSerDao; @Service public class PaiMaiSerDaoImpl implements PaiMaiSerDao {// 设置依赖的类 @Resource private PaiMaiSerDao dao; @Override public List<Saleinfo> getall() { return dao.getall(); } @Override public int insertsale(Saleinfo sale) { return dao.insertsale(sale); } @Override public int deletesale(int id) { return dao.deletesale(id); } @Override public int updatedale(Saleinfo sale) { return dao.updatedale(sale); } } package com.dlsp.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dlsp.dao.PaiMaiDao; import com.dlsp.dao.UserLoginDao; import com.dlsp.domain.Manage; import com.dlsp.service.UserLoginSerDao; @Service public class UserLoginService implements UserLoginSerDao { @Resource private UserLoginSerDao dao; @Override public Manage loginman(Manage manage) { return dao.loginman(manage); } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" > <!-- 1.包扫描 service dao (注解方式) --> <context:component-scan base-package="com.dlsp.dao,com.dlsp.service"/> <!-- 2. jdbc.properties 属性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 3.数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverclass}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 4.sqlsessionfactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 怎么和mybatis整合,关联Mybatis,关联映射文件 --> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> <property name="mapperLocations" value="classpath:com/dlsp/dao/*.xml"/> </bean> <!-- 5.事务 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="find*" read-only="true"/> <tx:method name="get*" read-only="true"/> <tx:method name="list*" read-only="true"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.dlsp.service.*.*(..))" id="txPointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>

applet中画出的图形如何保存为jpg格式的图片

<pre name="code" class="java">import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class DragApplet extends Applet { private static final long serialVersionUID = 1L; private Image image; Point pressed = new Point(); Point lastTranslate = new Point(); public void init() { image = getImage(getDocumentBase(), "1.jpg");// 这里是加载图片的 try { MediaTracker mt = new MediaTracker(this); mt.addImage(image, 0); mt.waitForID(0); } catch (InterruptedException e) { e.printStackTrace(); } addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { Point Ioc = e.getPoint(); pressed.x = Ioc.x - lastTranslate.x; pressed.y = Ioc.y - lastTranslate.y; } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Point Ioc = e.getPoint(); Point translate = new Point(Ioc.x - pressed.x, Ioc.y - pressed.y); Graphics g = getGraphics(); try { g.clearRect(0, 0, getSize().width, getSize().height); g.translate(translate.x, translate.y); showStatus("Translating Graphics:" + translate); g.drawImage(image, 0, 0, DragApplet.this); } finally { g.dispose(); } lastTranslate = translate; } }); } public void update(Graphics g)// 我已经进行了消除闪动了??? { paint(g); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } } </pre> <p> </p> <p>我如何才能将applet中的东西保存为jpg格式的图片呢?</p> <p> </p> <p>我知道这个方法:</p> <p>BufferedImage    bufImg = ImageIO.read(new File("e:\\4.jpg"));</p> <p> </p> <p>输出方法:</p> <p> ImageIO.write(bufImg, ".JPEG", new File("e:\\2.jpg"));</p> <p> </p> <p>但现在不清楚。。。如何把applet中画出的图形保存为一张图片呢?</p><br /><strong>问题补充:</strong><br />该问题已经解决,在此谢谢热心帮助我的朋友们! <br /><pre name="code" class="java"> import java.applet.Applet; import java.awt.Button; import java.awt.Canvas; import java.awt.Color; import java.awt.FileDialog; import java.awt.Frame; import java.awt.Graphics; import java.awt.HeadlessException; import java.awt.Image; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class SaveApplet extends Applet implements ActionListener { private static final long serialVersionUID = 1L; public SaveApplet() throws HeadlessException { super(); } BufferedImage bi; Graphics gg = null; Panel panel = null; Button button1 = null; Button button2 = null; Image tempImage = null; Canvas mycanvas = null; public void init() { bi = new BufferedImage(1024, 800, BufferedImage.TYPE_INT_RGB); gg = bi.getGraphics(); panel = new Panel(); button1 = new Button("open"); button2 = new Button("save"); panel.add(button1); panel.add(button2); add(panel); button1.addActionListener(this); button2.addActionListener(this); } public void paint(Graphics g) { gg.setColor(Color.red); gg.drawRect(10, 10, 50, 50); // 红色画矩形 gg.setColor(Color.blue); gg.fillOval(50, 50, 80, 80); // 蓝色圆形 gg.dispose(); g.drawImage(bi, 0, 0, this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { Frame f = new fileDialog("File Dialog Demo!"); f.setVisible(false); f.setSize(100, 100); FileDialog fd1 = new FileDialog(f, "File Dialog", FileDialog.LOAD); fd1.setVisible(true); try { File f2 = new File(fd1.getDirectory(), fd1.getFile()); FileInputStream readfile = new FileInputStream(f2); tempImage = ImageIO.read(new File(fd1.getDirectory(), fd1 .getFile())); mycanvas = new Canvas(); mycanvas.setBounds(400, 300, 100, 100); add(mycanvas); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource() == button2) { Frame f = new fileDialog("File Dialog Demo!"); f.setVisible(false); f.setSize(100, 100); FileDialog fd = new FileDialog(f, "File Dialog", FileDialog.SAVE); fd.setVisible(true); try { // File f1 = new File(fd.getDirectory(), fd.getFile()); // FileOutputStream out = new FileOutputStream(f1); // // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // JPEGEncodeParam param = // encoder.getDefaultJPEGEncodeParam(bi); // param.setQuality(1.0f, false); // encoder.setJPEGEncodeParam(param); // encoder.encode(bi); // out.close(); if (fd.getFile() != null) { String pathStr = fd.getDirectory(); pathStr = pathStr.replace("\\", "\\\\"); String path = pathStr + fd.getFile(); ImageIO.write(bi, "JPEG", new File(path)); } } catch (IOException e2) { e2.printStackTrace(); } } } class fileDialog extends Frame { private static final long serialVersionUID = 1L; fileDialog(String title) { super(title); MyWindowAdapter adapter = new MyWindowAdapter(this); addWindowListener(adapter); } } class MyWindowAdapter extends WindowAdapter { fileDialog sf; public MyWindowAdapter(fileDialog sfr) { this.sf = sfr; } public void windowClosing(WindowEvent we) { sf.setVisible(false); } } } </pre>

串口和串口轉usb的區別

圖一: ![知道串口轉usb](https://img-ask.csdn.net/upload/201811/22/1542851006_844269.png) 圖二: ![這是串口的](https://img-ask.csdn.net/upload/201811/22/1542851037_642924.png) # **提問:圖一圖二可不可以都用下面的代碼獲取數據:(圖二可以用下面的代碼獲取數據,但是圖一不知道行不行,請各位大佬路過看看)** ``` package com.lyf.test2; import java.awt.Button; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Label; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; import com.lyf.test2.SerialTool; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import serialException.ExceptionWriter; import serialException.NoSuchPort; import serialException.NotASerialPort; import serialException.PortInUse; import serialException.ReadDataFromSerialPortFailure; import serialException.SendDataToSerialPortFailure; import serialException.SerialPortInputStreamCloseFailure; import serialException.SerialPortOutputStreamCloseFailure; import serialException.SerialPortParameterFailure; import serialException.TooManyListeners; /** * 主程序 * @author zhong * */ public class Client extends Frame{ private static final long serialVersionUID = 1L; /** * 程序界面宽度 */ public static final int WIDTH = 800; /** * 程序界面高度 */ public static final int HEIGHT = 620; /** * 程序界面出现位置(横坐标) */ public static final int LOC_X = 200; /** * 程序界面出现位置(纵坐标) */ public static final int LOC_Y = 70; private static SerialPort serialPort = null; //保存串口对象 private Font font = new Font("微软雅黑", Font.BOLD, 25);//文本框字體 private Label weight = new Label("暫無數據", Label.CENTER); //重量 private Button saveButton = new Button("保存");//设置button按钮 Image offScreen = null; //用于双缓冲 //设置window的icon(这里我自定义了一下Windows窗口的icon图标,因为实在觉得哪个小咖啡图标不好看 = =) Toolkit toolKit = getToolkit();//返回此窗体的工具包 Image icon = toolKit.getImage(Client.class.getResource("computer.png"));//獲取當前類所在的包下面的圖片 /** * 主方法 * @param args * @throws SerialPortOutputStreamCloseFailure * @throws SendDataToSerialPortFailure * @throws PortInUse * @throws NoSuchPort * @throws NotASerialPort * @throws SerialPortParameterFailure */ public static void main(String[] args) throws SendDataToSerialPortFailure, SerialPortOutputStreamCloseFailure, SerialPortParameterFailure, NotASerialPort, NoSuchPort, PortInUse { new Client().launchFrame(); } /** * 主菜单窗口显示; * 添加Label、按钮、下拉条及相关事件监听; */ public void launchFrame() { this.setBounds(LOC_X, LOC_Y, WIDTH, HEIGHT); this.setTitle("CDIO工程项目"); this.setIconImage(icon); this.setBackground(Color.white); this.setLayout(null); //改變按鈕的事件监听 this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { if (serialPort != null) { //程序退出时关闭串口释放资源 SerialTool.closePort(serialPort); } System.exit(0); } }); //设置文本框位置、背景颜色、是否粗体、字体颜色 weight.setBounds(140, 103, 225, 50); weight.setBackground(Color.black); weight.setFont(font); weight.setForeground(Color.white); add(weight); //添加保存按钮 saveButton.setBounds(250, 490, 300, 50); saveButton.setBackground(Color.lightGray); saveButton.setFont(new Font("微软雅黑", Font.BOLD, 20)); saveButton.setForeground(Color.darkGray); add(saveButton); //添加打开串口按钮的事件监听 try { //指定端口名及波特率的串口对象 serialPort = SerialTool.openPort("COM1", 4800); //在该串口对象上添加监听器 SerialTool.addListener(serialPort, new SerialListener()); } catch (SerialPortParameterFailure | NotASerialPort | NoSuchPort | PortInUse | TooManyListeners e1) { //发生错误时使用一个Dialog提示具体的错误信息 JOptionPane.showMessageDialog(null, e1, "错误", JOptionPane.INFORMATION_MESSAGE); } this.setResizable(false);//设置此框架是否可由用户调整大小。 this.setVisible(true); //显示窗口 new Thread(new RepaintThread()).start(); //启动重画线程 } /** * 画出主界面组件元素 * 设置button的字体颜色、设置字体样式 是否粗体 字体大小、文本、位置 */ public void paint(Graphics g) { g.setColor(Color.black); g.setFont(new Font("微软雅黑", Font.BOLD, 25)); g.drawString(" 重量: ", 45, 130); } /** * 双缓冲方式重画界面各元素组件 */ public void update(Graphics g) { if (offScreen == null) offScreen = this.createImage(WIDTH, HEIGHT); Graphics gOffScreen = offScreen.getGraphics(); Color c = gOffScreen.getColor(); gOffScreen.setColor(Color.white); gOffScreen.fillRect(0, 0, WIDTH, HEIGHT); //重画背景画布 this.paint(gOffScreen); //重画界面元素 gOffScreen.setColor(c); g.drawImage(offScreen, 0, 0, null); //将新画好的画布“贴”在原画布上 } /** * 以内部类形式创建一个串口监听类 * @author zhong * */ private class SerialListener implements SerialPortEventListener { /** * 处理监控到的串口事件 */ public void serialEvent(SerialPortEvent serialPortEvent) { try { // 等待1秒钟让串口把数据全部接收后在处理 Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } switch (serialPortEvent.getEventType()) { case SerialPortEvent.BI: // 10 通讯中断 JOptionPane.showMessageDialog(null, "与串口设备通讯中断", "错误", JOptionPane.INFORMATION_MESSAGE); break; case SerialPortEvent.OE: // 7 溢位(溢出)错误 case SerialPortEvent.FE: // 9 帧错误 case SerialPortEvent.PE: // 8 奇偶校验错误 case SerialPortEvent.CD: // 6 载波检测 case SerialPortEvent.CTS: // 3 清除待发送数据 case SerialPortEvent.DSR: // 4 待发送数据准备好了 case SerialPortEvent.RI: // 5 振铃指示 case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 输出缓冲区已清空 break; case SerialPortEvent.DATA_AVAILABLE: // 1 串口存在可用数据 byte[] data = null; try { if (serialPort == null) {//判断串口对象是否为空 JOptionPane.showMessageDialog(null, "串口对象为空!监听失败!", "错误", JOptionPane.INFORMATION_MESSAGE); }else { data = SerialTool.readFromPort(serialPort); //读取数据,存入字节数组 //System.out.println(new String(data)); //自定义解析过程 if (data != null && data.length > 1) { //检查数据是否读取正确 try { weight.setText(new String(data) + " g"); } catch (ArrayIndexOutOfBoundsException e) { JOptionPane.showMessageDialog(null, "数据解析过程出错,更新界面数据失败!请检查设备或程序!", "错误", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }else { JOptionPane.showMessageDialog(null, "读取数据过程中未获取到有效数据!请检查设备或程序!", "错误", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } catch (ReadDataFromSerialPortFailure | SerialPortInputStreamCloseFailure e) { JOptionPane.showMessageDialog(null, e, "错误", JOptionPane.INFORMATION_MESSAGE); System.exit(0); //发生读取错误时显示错误信息后退出系统 } break; } } } /** * 重画线程(每隔30毫秒重画一次) */ private class RepaintThread implements Runnable { public void run() { while(true) { //调用重画方法 repaint(); try { Thread.sleep(30); } catch (InterruptedException e) { String err = ExceptionWriter.getErrorInfoFromException(e); JOptionPane.showMessageDialog(null, err, "错误", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } } } ``` ``` package com.lyf.test2; import java.io.IOException; import java.io.InputStream; import java.util.TooManyListenersException; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import serialException.*; /** * 串口服务类,提供打开、关闭串口,读取、发送串口数据等服务(采用单例设计模式) * @author zhong * */ public class SerialTool { private static SerialTool serialTool = null; static { //在该类被ClassLoader加载时就初始化一个SerialTool对象 if (serialTool == null) { serialTool = new SerialTool(); } } //私有化SerialTool类的构造方法,不允许其他类生成SerialTool对象 private SerialTool() {} /** * 获取提供服务的SerialTool对象 * @return serialTool */ public static SerialTool getSerialTool() { if (serialTool == null) { serialTool = new SerialTool(); } return serialTool; } /** * 打开串口 * @param portName 端口名称 * @param baudrate 波特率 * @return 串口对象 * @throws SerialPortParameterFailure 设置串口参数失败 * @throws NotASerialPort 端口指向设备不是串口类型 * @throws NoSuchPort 没有该端口对应的串口设备 * @throws PortInUse 端口已被占用 */ public static final SerialPort openPort(String portName, int baudrate) throws SerialPortParameterFailure, NotASerialPort, NoSuchPort, PortInUse { try { //通过端口名识别端口 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); //打开端口,并给端口名字和一个timeout(打开操作的超时时间) CommPort commPort = portIdentifier.open(portName, 2000); //判断是不是串口 if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; try { //设置一下串口的波特率等参数 serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { throw new SerialPortParameterFailure(); } //System.out.println("Open " + portName + " sucessfully !"); return serialPort; } else { //不是串口 throw new NotASerialPort(); } } catch (NoSuchPortException e1) { throw new NoSuchPort(); } catch (PortInUseException e2) { throw new PortInUse(); } } /** * 关闭串口 * @param serialport 待关闭的串口对象 */ public static void closePort(SerialPort serialPort) { if (serialPort != null) { serialPort.close(); serialPort = null; } } /** * 从串口读取数据 * @param serialPort 当前已建立连接的SerialPort对象 * @return 读取到的数据 * @throws ReadDataFromSerialPortFailure 从串口读取数据时出错 * @throws SerialPortInputStreamCloseFailure 关闭串口对象输入流出错 */ public static byte[] readFromPort(SerialPort serialPort) throws ReadDataFromSerialPortFailure, SerialPortInputStreamCloseFailure { InputStream in = null; byte[] bytes = null; try { in = serialPort.getInputStream();//取入数据 int bufflenth = in.available(); //获取buffer里的数据长度 while (bufflenth != 0) { bytes = new byte[bufflenth]; //初始化byte数组为buffer中数据的长度 in.read(bytes); bufflenth = in.available(); } } catch (IOException e) { throw new ReadDataFromSerialPortFailure(); } finally { try { if (in != null) { in.close(); in = null; } } catch(IOException e) { throw new SerialPortInputStreamCloseFailure(); } } return bytes; } /** * 添加监听器 * @param port 串口对象 * @param listener 串口监听器 * @throws TooManyListeners 监听类对象过多 */ public static void addListener(SerialPort port, SerialPortEventListener listener) throws TooManyListeners { try { //给串口添加监听器 port.addEventListener(listener); //设置当有数据到达时唤醒监听接收线程 port.notifyOnDataAvailable(true); //设置当通信中断时唤醒中断线程 port.notifyOnBreakInterrupt(true); } catch (TooManyListenersException e) { throw new TooManyListeners(); } } } ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

2020春招面试了10多家大厂,我把问烂了的数据库事务知识点总结了一下

2020年截止目前,我面试了阿里巴巴、腾讯、美团、拼多多、京东、快手等互联网大厂。我发现数据库事务在面试中出现的次数非常多。

程序员如何与产品经理优雅的干架

早前,平安产险科技一名外包程序员和一名外包产品经理干架的视频几乎在互联网圈都传遍了,因为产品提了一个需求:要求用户App的主题颜色能根据手机壳自动调整。 首先说这个需求对于应用开发工程师来说,确实是有点奇葩,当然并非不能实现。这块涉及图形图像处理,用机器学习和人工智能来提取图像颜色,这是基本图像识别过程,对于采集图像,可以提示对着镜子自拍一张,上传图片,通过大量的训练数据,来识别手机体颜色。当然并...

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

在拼多多上班,是一种什么样的体验?我心态崩了呀!

之前有很多读者咨询我:武哥,在拼多多上班是一种什么样的体验?由于一直很忙,没抽出时间来和大家分享。上周末特地花点时间来写了一篇文章,跟大家分享一下拼多多的日常。 1. 倒时差的作息 可能很多小伙伴都听说了,拼多多加班很严重。这怎么说呢?作息上确实和其他公司有点区别,大家知道 996,那么自然也就能理解拼多多的“11 11 6”了。 所以当很多小伙伴早上出门时,他们是这样的: 我们是这样的: 当...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

太狠了,疫情期间面试,一个问题砍了我5000!

疫情期间找工作确实有点难度,想拿到满意的薪资,确实要点实力啊!面试官:Spring中的@Value用过么,介绍一下我:@Value可以标注在字段上面,可以将外部配置文件中的数据,比如可以...

立即提问
相关内容推荐