扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
import java.util.Scanner;
专注于为中小企业提供做网站、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业襄汾免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
import java.awt.*;
import java.awt.event.*;
public class Test extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "clear", "0", "=", "/", "close" };
static double a;
static String s, str;// 定义变量 创建对像
public static void main(String args[]) {
(new Test()).frame();
}
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i = 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i = 15; i++) {
p2.add(b[i]);
} // 创建按钮 并添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i = 16; i++) {
b[i].addActionListener(new buttonlistener());// 添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);// 都是些窗中设置 添加相关组件和监听器
}
public void windowClosing(WindowEvent e) {
System.exit(0);// 退出系统
}
class buttonlistener implements ActionListener {// 编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "clear")
txt.setText("");
}
}
public void jisuan() {// 编写具体计算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {// 退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
要在java中调用c语言的库,需要使用Java提供了JNI。
举例说明
在c语言中定义一个 void sayHello()函数(打印Hello World);然后在Java中调用这个函数显示Hello Word.
现在分别从Java和C语言两部分说明:
1. Java 部分
首先定义一个HelloNative,在其中申明sayHello函数,函数要申明为Native 类型的.如下:
public class HelloNative {
public native void sayHello();
}
编译这个类,生成class文件:
javac HelloWorld.java
利用javah生成需要的h文件
javah HelloNative
生成的 h文件大概如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include jni.h
/* Header for class HelloNative */
#ifndef _Included_HelloNative
#define _Included_HelloNative
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloNative
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloNative_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
可以看一下上面自动生成的程序,程序include了jni.h,这个头文件在 $JAVA_HOME下的include文件夹下. 还可以发现生成的函数名是在之前的函数名前面加上了Java_HelloNative。
2. C语言部分
根据上面生成的h文件编写相应的代码实现,建立一个 HelloNative.cpp用来实现显示Hello World的函数.如下:
#include stdio.h
#include "HelloNative.h"
JNIEXPORT void JNICALL Java_HelloNative_sayHello(JNIEnv *, jobject)
{
printf("Hello World!\n");
}
代码编写完成之后,我们再用gcc编译成库文件,命令如下;
gcc -fPIC -I/usr/lib/jvm/java-7-openjdk-i386/include -I/usr/lib/jvm/java-7-openjdk-i386/include/linux -shared -o libHelloNative.so HelloNative.cpp
这样就会在当前目录下生成一个libHelloNative.so的库文件.这时需要的库已经生成,在C语言下的工作已经完成了.
接下来需要在Java中编写一个程序测试一下.在程序前,需要将我们的库载入进去.载入的方法是调用Java的 System.loadLibrary("HelloNative");
public class TestNative
{
static {
try {
System.loadLibrary("HelloNative");
}
catch(UnsatisfiedLinkError e) {
System.out.println( "Cannot load hello library:\n " + e.toString() );
}
}
public static void main(String[] args) {
HelloNative test = new HelloNative();
test.sayHello();
}
}
但是再编译后,运行的时候,问题又出现了.
Cannot load hello library:
java.lang.UnsatisfiedLinkError: no HelloNative in java.library.path
Exception in thread "main" java.lang.UnsatisfiedLinkError: HelloNative.sayHello()V
at HelloNative.sayHello(Native Method)
at TestNative.main(TestNative.java:13)
载入库失败,但是库明明就是放在当前文件夹下的,怎么会载入失败呢?
用System.getProperty("java.library.path")查看,发现java.library.path中并不u存在当前的目录.主要有以下的几个解决办法:
1) 将生成的库复制到java.library.path有的路径中去,当然这样不是很好
2) 设置环境变量export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ,将当前的目录加入到LD_LIBRARY_PATH中
3) 设置java 的选项,将当前的目录加入到其中 .java -Djava.library.path=. $LD_LIBRARY_PATH
这样之后程序就能够成功的运行了.可以看见显示的"Hello World!"了
搞定了
package com.monubia;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Txt extends javax.swing.JFrame {
private JButton jButton_open;
private JTextArea jTextArea1;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Txt inst = new Txt();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public Txt() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
jButton_open = new JButton();
getContentPane().add(jButton_open);
jButton_open.setText("Open");
jButton_open.setBounds(155, 114, 92, 49);
jButton_open.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
jButton_openMouseClicked(evt);
}
});
}
{
jTextArea1 = new JTextArea();
getContentPane().add(jTextArea1);
jTextArea1.setBounds(0, 0, 384, 262);
}
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
private void jButton_openMouseClicked(MouseEvent evt) {
//点击了打开
JFileChooser open=new JFileChooser();
FileNameExtensionFilter txt= new FileNameExtensionFilter("Txt File", "txt");
open.setFileFilter(txt);
int ret=open.showOpenDialog(this);
if(ret==JFileChooser.APPROVE_OPTION)
{
jButton_open.setOpaque(false);
jButton_open.setVisible(false);
System.out.println(open.getSelectedFile().getAbsolutePath());
try {
BufferedReader br=new BufferedReader(new FileReader(open.getSelectedFile().getAbsolutePath()));
String line=null;
while((line=br.readLine())!=null)
{
jTextArea1.append(line+"\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class YFileChooser implements ActionListener{
JFrame frame=new JFrame("文件选择器实例");
JTabbedPane tabPane=new JTabbedPane();//选项卡布局
Container con=new Container();//布局1
Container con1=new Container();//布局2
JLabel label1=new JLabel("选择目录");
JLabel label2=new JLabel("选择文件");
JTextField text1=new JTextField();
JTextField text2=new JTextField();
JButton button1=new JButton("...");
JButton button2=new JButton("...");
JFileChooser jfc=new JFileChooser();//文件选择器
YFileChooser(){
jfc.setCurrentDirectory(new File("d:\\"));//文件选择器的初始目录定为d盘
//下面两行是取得屏幕的高度和宽度
double lx=Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly=Toolkit.getDefaultToolkit().getScreenSize().getHeight();
frame.setLocation(new Point((int)(lx/2)-150,(int)(ly/2)-150));//设定窗口出现位置
frame.setSize(300,150);//设定窗口大小
frame.setContentPane(tabPane);//设置布局
//下面设定标签等的出现位置和高宽
label1.setBounds(10,10,70,20);
label2.setBounds(10,30,100,20);
text1.setBounds(80,10,120,20);
text2.setBounds(80,30,120,20);
button1.setBounds(210,10,50,20);
button2.setBounds(210,30,50,20);
button1.addActionListener(this);//添加事件处理
button2.addActionListener(this);//添加事件处理
con.add(label1);
con.add(label2);
con.add(text1);
con.add(text2);
con.add(button1);
con.add(button2);
con.add(jfc);
tabPane.add("目录/文件选择",con);//添加布局1
tabPane.add("暂无内容",con1);//添加布局2
frame.setVisible(true);//窗口可见
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//使能关闭窗口,结束程序
}
public void actionPerformed(ActionEvent e){//事件处理
if(e.getSource().equals(button1)){//判断触发方法的按钮是哪个
jfc.setFileSelectionMode(1);//设定只能选择到文件夹
int state=jfc.showOpenDialog(null);//此句是打开文件选择器界面的触发语句
if(state==1){
return;//撤销则返回
}
else{
File f=jfc.getSelectedFile();//f为选择到的目录
text1.setText(f.getAbsolutePath());
}
}
if(e.getSource().equals(button2)){
jfc.setFileSelectionMode(0);//设定只能选择到文件
int state=jfc.showOpenDialog(null);//此句是打开文件选择器界面的触发语句
if(state==1){
return;//撤销则返回
}
else{
File f=jfc.getSelectedFile();//f为选择到的文件
text2.setText(f.getAbsolutePath());
}
}
}
public static void main(String[] args) {
new YFileChooser();
}
}
不用谢~请叫我雷锋
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流