『壹』 求教用java實現如下圖形界面功能。
粗略地做了一個出來,閃爍的問題暫時無法解決,其他的還可以吧,先上代碼:
importjava.awt.Graphics;
importjava.awt.Image;
importjava.awt.event.MouseEvent;
importjava.awt.event.MouseListener;
importjava.awt.event.MouseMotionListener;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjavax.imageio.ImageIO;
importjavax.swing.JFrame;
public桐旁,MouseMotionListener{
privateImageoffScreenImage;
privateImagebackground,sprite;
privatestaticfinalintWIDTH=800;
privatestaticfinalintHEIGHT=600;
privateintx0=0,y0=0;
privateintx1,y1;
privateList<Bounds>bounds;
privateBoundsmCurrentBounds=null;
publicTestImage(){
super("繪圖");
bounds=newArrayList<Bounds>();
}
privatevoidlaunch(){
setSize(WIDTH,HEIGHT);
setResizable(false);
setVisible(true);
try{
background=ImageIO.read(TestImage.class.getResource("/res/clock.jpg"));
sprite=ImageIO.read(TestImage.class.getResource("/res/light_buble2.png"鏈槐));
}catch(IOExceptione){
e.printStackTrace();
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
newThread(newRepaint()).start();
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
publicvoipdate(Graphicsg){
if(null==offScreenImage){
offScreenImage=createImage(WIDTH,HEIGHT);
}
GraphicsgImage=offScreenImage.getGraphics();
gImage.clearRect(0,0,WIDTH,HEIGHT);
paint(gImage);
g.drawImage(offScreenImage,0,0,null);
}
@Override
publicvoidpaint(Graphicsg){
g.drawImage(background,0,0,WIDTH,HEIGHT,null);
for(Boundsbound:bounds)棚輪友{
g.drawImage(sprite,bound.x0,bound.y0,bound.x1-bound.x0,bound.y1-bound.y0,null);
}
if(null!=mCurrentBounds){
g.drawImage(sprite,mCurrentBounds.x0,mCurrentBounds.y0,
Math.abs(mCurrentBounds.x1-mCurrentBounds.x0),
Math.abs(mCurrentBounds.y1-mCurrentBounds.y0),null);
}
}
publicstaticvoidmain(String[]args){
newTestImage().launch();
}
@Override
publicvoidmouseClicked(MouseEvente){
}
@Override
publicvoidmouseEntered(MouseEvente){
}
@Override
publicvoidmouseExited(MouseEvente){
}
@Override
publicvoidmousePressed(MouseEvente){
x1=x0=e.getX();
y1=y0=e.getY();
mCurrentBounds=newBounds(x0,y0,x1,y1);
}
@Override
publicvoidmouseReleased(MouseEvente){
if(null!=mCurrentBounds){
bounds.add(mCurrentBounds);
}
mCurrentBounds=null;
}
@Override
publicvoidmouseDragged(MouseEvente){
if(null!=mCurrentBounds){
intx=e.getX();
inty=e.getY();
if(x>x0){
x1=x;
}else{
x0=x;
}
if(y>y0){
y1=y;
}else{
y0=y;
}
mCurrentBounds.setBounds(x0,x1,y0,y1);
}
}
@Override
publicvoidmouseMoved(MouseEvente){
}
{
@Override
publicvoidrun(){
while(true){
try{
Thread.sleep(30L);
repaint();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}
classBounds{
publicintx0;
publicinty0;
publicintx1;
publicinty1;
publicBounds(intx0,inty0,intx1,inty1){
this.x0=x0;
this.y0=y0;
this.x1=x1;
this.y1=y1;
}
publicvoidsetBounds(intx0,intx1,inty0,inty1){
this.x0=x0;
this.x1=x1;
this.y0=y0;
this.y1=y1;
}
}
運行時就是滑鼠點擊畫板並按住,然後拖拽就可以畫一個電燈出來。所需的圖片資源在附件內,根據代碼相信你應該能夠知道要放到哪個目錄下吧。運行效果也截一個圖給你。
『貳』 Java編寫一個圖形界面
我覺得還是我的好些螞虧。。。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileOutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class TestSwing extends JFrame{
private JLabel label1, label2, label3, label4,label5,label6,label7;
private JPanel panel,panel1,panel2;
private JTextField tField1,tField2,tField3,tField4,tField5,tField6,tField7,tField8,tField9;
private JButton button;
private String filepath="c:\\info.dat";
public TestSwing(){
init();
this.setSize(300, 280);
this.setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width - this
.getSize().width) /搏物塵基禪 2,
(Toolkit.getDefaultToolkit().getScreenSize().height - this
.getSize().height) / 2);
this.setResizable(false);
this.setVisible(true);
this.setTitle("info");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init(){
initPanel();
initLabel();
initTextField();
initButton();
initContent();
}
private void initContent(){
panel1.add(label1);
panel1.add(tField1);
panel1.add(label2);
panel1.add(tField2);
panel1.add(label3);
panel1.add(tField3);
panel1.add(label4);
panel1.add(tField4);
panel1.add(label5);
panel1.add(tField5);
panel1.add(label6);
panel1.add(tField6);
panel1.add(label7);
panel1.add(tField7);
panel1.add(tField8);
panel1.add(tField9);
panel2.add(button);
panel.add(panel1,BorderLayout.CENTER);
panel.add(panel2,BorderLayout.SOUTH);
getContentPane().add(panel);
}
private void initPanel(){
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(Color.WHITE);
panel1 = new JPanel();
GridLayout upLayout = new GridLayout(8, 2);
panel1.setLayout(upLayout);
panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
}
private void initLabel(){
label1 = new JLabel("IP地址", SwingConstants.LEFT);
label2 = new JLabel("埠", SwingConstants.LEFT);
label3 = new JLabel("訪問地址", SwingConstants.LEFT);
label4 = new JLabel("XXXXX", SwingConstants.LEFT);
label5 = new JLabel("XXXXX", SwingConstants.LEFT);
label6 = new JLabel("XXXXX", SwingConstants.LEFT);
label7 = new JLabel("XXXXX", SwingConstants.LEFT);
}
private void initTextField(){
tField1 = new JTextField(10);
tField2 = new JTextField(10);
tField3 = new JTextField(10);
tField4 = new JTextField(10);
tField5 = new JTextField(10);
tField6 = new JTextField(10);
tField7 = new JTextField(10);
tField8 = new JTextField(10);
tField9 = new JTextField(10);
}
private void initButton(){
button = new JButton("完成");
button.addMouseListener(new MouseAdapter(){
//左鍵點擊
public void mouseClicked(MouseEvent e) {
String ipv = tField1.getText().trim();
String portv = tField2.getText().trim();
String addrv = tField3.getText().trim();
String xx1v = tField4.getText().trim();
String xx2v = tField5.getText().trim();
String xx3v = tField6.getText().trim();
String xx4v = tField7.getText().trim();
String inputx = tField8.getText().trim();
String inputxv = tField9.getText().trim();
createFile(ipv, portv, addrv, xx1v, xx2v, xx3v, xx4v, inputx, inputxv);
JOptionPane.showMessageDialog(null, "保存成功");
tField1.setText("");
tField2.setText("");
tField3.setText("");
tField4.setText("");
tField5.setText("");
tField6.setText("");
tField7.setText("");
tField8.setText("");
tField9.setText("");
}
});
}
public static void main(String[]args){
new TestSwing();
}
private void createFile(String ipv,String portv ,String addrv,String xx1v,String xx2v,String xx3v,String xx4v,String inputx,String inputxv){
StringBuffer context = new StringBuffer();
context.append("ip=").append(ipv).append("\n");
context.append("port=").append(portv).append("\n");
context.append("addr=").append(addrv).append("\n");
context.append("xx1=").append(xx1v).append("\n");
context.append("xx2=").append(xx2v).append("\n");
context.append("xx3=").append(xx3v).append("\n");
context.append("xx4=").append(xx4v).append("\n");
context.append(inputx).append("=").append(inputxv).append("");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
fos.write(context.toString().getBytes());
} catch (Exception e) {
} finally {
if (fos != null)
try {
fos.close();
} catch (Exception e) {
}
}
}
}
『叄』 如何在Java中利用圖形界面技術設計一個能夠完成加、減、乘、除和取余運算的圖形用戶界面應用程序
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Z extends JFrame implements ActionListener, FocusListener {
private String[] total = { "1", "2", "3", "+", "4", "5", "6", "-", "7", "8", "9", "*", "0", ".", "=", "/" }; // 總數組
private String[] other = { "clear", "delete" }; // 其它功能數組
private String[] symbol = { "+", "-", "*", "/" }; // 符號數組
private String multinumber = "0", operator1 = "", exists = "", operator2 = null, s = "";
// multinumber(多位數) operator1(運算符) exists(存在的)
private double d1, d2 = 0;
private int Count = 0;
JPanel jptotal = new JPanel(); // 總面板
JTextField jtexternal = new JTextField("0"); // 外部文本框
JTextField jtinside = new JTextField(); // 內部文本框
JPanel jptop1 = new JPanel(); // 頂部面板1
JPanel jptop2 = new JPanel(); // 頂部面板2
JPanel jpmiddle = new JPanel(); // 中部面板
public Z() {
jptotal.setLayout(new BorderLayout());
// 使用邊界布局管理器
jptop1.setLayout(new GridLayout(2, 0));
jptop1.add(jtexternal);
jptop2.setLayout(new GridLayout(0, 2));
for (int i = 0; i < other.length; i++) {
JButton jbi = new JButton("" + other[i]);
jbi.setSize(100, 10);
jptop2.add(jbi);
jbi.addActionListener(this);
}
jpmiddle.setLayout(new GridLayout(4, 0));
for (int i = 0; i < total.length; i++) {
JButton jbi = new JButton("" + total[i]);
jpmiddle.add(jbi);
jbi.addActionListener(this);
}
jtexternal.addFocusListener(this);
jtexternal.add(jtinside);
jtinside.addFocusListener(this);
// 上面三行代碼的作用是讓文本框不可被選中
jptop1.add(jptop2);
jptotal.add(jptop1, "North");
// 以jp1為一個整體,讓jp1裡面的內容從最上面開始填充
jptotal.add(jpmiddle);
add(jptotal);
setVisible(true);
setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
// ctrl+/ :注釋
public void actionPerformed(ActionEvent e) throws ArithmeticException {
try {
String inputing = e.getActionCommand();
// 表示獲取當前輸入的內容
if (inputing.equals(".")) {
Count++;
}
exists = jtexternal.getText();
if (operator2 != null) {
int k = 0;
for (int i = 0; i < symbol.length; i++) {
if (operator2.equals(symbol[i])) {
k = k + 1;
}
if (inputing.equals(symbol[i])) {
k = k + 1;
}
if (k == 2) {
jtexternal.setText(exists.substring(0, exists.length() - 1) + inputing);
operator1 = inputing;
return;
}
// 實現四則運算符不可同時存在,新輸入的替換舊的
if (operator2.equals(symbol[i]) && inputing.equals(".")) {
return;
}
// 實現四則運算符和點不可挨著出現(點後面可以出現四則運算符,點前面不可出現)
}
}
if (exists.equals("0")) {
if (inputing.equals(".") || (inputing.equals("+")) || (inputing.equals("-")) || (inputing.equals("*"))
|| (inputing.equals("/"))) {
jtexternal.setText("0" + inputing);
} else {
jtexternal.setText(inputing);
}
} else {
jtexternal.setText(exists + inputing);
}
// 實現如果0前面沒有非0數字的話,那麼無論輸入多少次0,都只顯示一個0,如果輸入其它數字,0將會被替換
if ((d1 == 0.0 || d2 == 0.0) && inputing.equals("=") && !exists.substring(0, 1).equals("0")) {
return;
}
// 實現如果文本框內存在數字,那麼輸入等號,將列印其本身
if (inputing.equals("clear")) {
multinumber = "0";
exists = "";
operator1 = "";
jtexternal.setText("0");
operator2 = null;
d2 = 0;
s = "";
Count = 0;
d1 = 0.0;
// 實現,當點擊clear時,文本框內將被清空至0,所有數據都將還原至初始狀態
} else if (inputing.equals("delete")) {
if (exists.length() <= 1 || s.equals("=")) {
jtexternal.setText("0");
multinumber = "0";
exists = "";
operator1 = "";
operator2 = null;
d2 = 0;
s = "";
Count = 0;
d1 = 0;
// 實現,按delete刪除剛輸入的內容,如果將最後一個數字刪除,那麼效果同按clear
} else {
if (inputing.equals("+") || inputing.equals("-") || inputing.equals("*") || inputing.equals("/")) {
Count = 1;
}
jtexternal.setText(exists.substring(0, exists.length() - 1));
// 將operator2存儲上一次值
operator2 = exists.substring(exists.length() - 2, exists.length() - 1);
/*
* 實現如果四則運算符後面有數字的話
* 那麼如果此時按刪除鍵
* 刪除之後如果新輸入的還是四則運算符話
* 那麼將會將原來的四則運算符替換成新輸入的
*/
}
} else if (!inputing.equals("+") && !inputing.equals("-") && !inputing.equals("*") && !inputing.equals("/")
&& !inputing.equals("=")) {
// 判斷輸入是否為數字
if (s.equals("=")) {
if (exists.equals("除數不能為0") || new Double(exists) == d1) {
if (inputing.equals(".")) {
jtexternal.setText("0" + inputing);
} else {
jtexternal.setText(inputing);
}
}
s = "";
}
// 實現一次計算完成之後,可以進行新的運算
if (multinumber == null) { // 多位數計算
multinumber = inputing;
} else {
multinumber += inputing;
}
d1 = new Double(multinumber);
if (operator1.equals("+")) { // 進行四則運算
if (d2 == 0) {
if (operator1.equals("*") || operator1.equals("/")) {
d2 = 1;
}
}
// 實現,當四則運算符後面沒有數字時,那麼輸入等號後結果將為符號前面的結果,如果符號前面只有一個數字,那麼將列印自身
d1 = d1 + d2;
} else if (operator1.equals("-")) {
d1 = d2 - d1;
} else if (operator1.equals("*")) {
d1 = d1 * d2;
} else if (operator1.equals("/")) {
d1 = d2 / d1;
}
// 利用臨時變數f2,實現四則運算
operator2 = inputing;
} else if (!inputing.equals("=")) { // [四則運算符] 輸入等號後繼續進行計算
multinumber = "0";
operator1 = inputing;
d2 = d1;
operator2 = inputing;
s = "";
Count = 0;
// 實現小數運算
} else { // 就是 [=] 得出最終結果
jtexternal.setText("" + d1);
Count = 0;
s = "=";
multinumber = "0";
if (operator2.equals("0") && "/".equals(operator1)) {
operator2 = null;
d1 = 0;// 將非法運算值替換成正確值
throw new ArithmeticException();// 指定拋出異常的條件
//賦值計算不拋算數異常,如果想讓其拋出,必須指定條件重新拋出異常
} else {
operator1 = inputing;
operator2 = null;
d2 = 0;
} // 計算結果
if (inputing.equals("=") && (d1 == 0.0 || d2 == 0.0)) {
return;
}
// 實現等號不可重復輸入
}
} catch (ArithmeticException e1) {
jtexternal.setText("除數不能為0");
// 指定拋出異常內容
}
}
public static void main(String[] args) {
new Z();
}
public void focusGained(FocusEvent e) {
jtinside.requestFocus();
// 讓焦點聚焦到內部文本框,實現外部文本框的不可聚焦功能
}
public void focusLost(FocusEvent e) {
}
}
『肆』 java 如何在圖形界面顯示程序運行結果
如果只是一些文本要顯示,可以在上面加個JTextArea,JTextField之類的組件,用這些組件的對象調用setText("")方法(括弧里是字元串)來顯示文本
比如:
importjava.awt.FlowLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.HashMap;
importjava.util.Map;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JScrollPane;
importjavax.swing.JTextArea;
/**文本區域
*
*@authorAdministrator
*
*/
{
=2306597749734227012L;
privateJButtonb1=newJButton("AddData"),b2=newJButton("ClearData");
privateJTextAreatext=newJTextArea(20,40);
privateMap<String,String>map=
newHashMap<String,String>();
public跡信TextArea(){
//Useupallthedata:
map.put("a","1");
map.put("b","2");
b1.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
//TODOAuto-generatedmethodstub
for(@SuppressWarnings("rawtypes")Map.Entryme:map.entrySet()){
text.append(me.getKey()+":"+me.getValue()+" ");
}
}
});
b2.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
//TODOAuto-generatedmethodstub
text.setText("");
}
});
setLayout(newFlowLayout());
add(newJScrollPane(text));
add(b1);
add(b2);
租核
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
GUItools.SwingConsole.run(newTextArea(),475,475);
}
}
JTextField和這差不多,只不過是顯示單行的。
如果要顯示其他字體的,可以用HTML格式,如下:
importjava.awt.FlowLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
/**Swing組件上的HTML
*
*@authorAdministrator
*
*/
@SuppressWarnings("serial")
{
privateJButtonb=newJButton(
"<html><b>姿型輪<fontsize=+2>"+
"<center>Hello!<br><i>Pressmenow!");
//必須使文本以"<html>"標記開始。
publicHTMLButton(){
//TODOAuto-generatedconstructorstub
b.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
//TODOAuto-generatedmethodstub
add(newJLabel("<html>"+"<i><fontsize=+4>Kapow!"));
//Forceare-layouttoincludethenewlabel:
validate();
}
});
setLayout(newFlowLayout());
add(b);
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
GUItools.SwingConsole.run(newHTMLButton(),200,500);
}
}
『伍』 怎樣用java編寫圖形界面的Application程序
java編寫圖形界面需要用到swing等組件,可以在eclipse中安裝windowbuilder來開發窗體,自動生成窗體代碼租碰,然後自己再根據需要修改,如:
package mainFrame;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame。