我的程序基本上是一个带有三个按钮的 JPanel,我想使用其中一个按钮在 JPanel 上绘制线条。我有两个类,一个扩展 JPanel (Panel.class),另一个扩展 JFrame (frame.class)
该按钮在 frame.class 中,它调用 panel.class 中的一个方法,称为抽屉();按钮事件向其传递 xy 坐标,然后抽屉将这些坐标传递给 panel.class 中的四个 int var 并调用 repaint();但没有画线。
Panel.class 代码:
package my.jpanel;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;
public class Panel extends javax.swing.JPanel {
//draws using the initial (x1, y1) co-ordiantes of the previous i in the array
private int x1, y1, x2, y2;
ArrayList linex1 = new ArrayList();
ArrayList linex2 = new ArrayList();
ArrayList liney1 = new ArrayList();
ArrayList liney2 = new ArrayList();
public int fx1, fy1, fx2, fy2;
public void drawer(int fx1i, int fy1i, int fx2i, int fy2i){
fx1 = fx1i;
fy1 = fy1i;
fx2 = fx2i;
fy2 = fy2i;
repaint();
}
public Panel() {
addMouseListener( new MouseAdapter(){
public void mousePressed (MouseEvent e){
x1 = e.getX();
y1 = e.getY();
int z = linex1.size();
System.out.println("z: "+z);
if (z!=0){
linex1.add(linex2.get(z-1));
liney1.add(liney2.get(z-1));}
else{
linex1.add(x1);
liney1.add(y1);
System.out.println("x1:"+x1);}
}
public void mouseReleased( MouseEvent e){
x2 = e.getX();
y2 = e.getY();
linex2.add(x2);
liney2.add(y2);
System.out.println("x1:"+x1+" x2:"+x2+" y1: "+y1+" y2: "+y2);
double slope = ((((double)y2)-((double)y1))/(((double)x2)-((double)x1)));
System.out.println("Slope of line: "+slope);
repaint();
}
});
addMouseMotionListener ( new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
repaint();
}
});
}
public Dimension getPreferredSize(){
return new Dimension(250, 150);
}
public void paintComponent( Graphics g ){
super.paintComponent(g);
// g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
g.drawLine(fx1, fy1, fx2, fy2);
g.drawLine(x1, y1, x2, y2);
int lx1 = linex1.size();
int lx2 = linex2.size();
int ly1 = liney1.size();
int ly2 = liney2.size();
System.out.println("lx1: "+lx1);
System.out.println("lx2: "+lx2);
System.out.println("ly1: "+ly1);
System.out.println("ly2: "+ly2);
System.out.println("-------------");
if ((lx1 != 0 && lx2 != 0 && ly1 != 0 && ly2 != 0) && (lx1 != 1 && ly1 != 1 && !(lx2 < (lx1)) && !(ly2 < (ly1)))){
for (int i=0; i<lx1; ++i){
int x1x = ((int) (linex1.get(i)));
int x2x = ((int) (linex2.get(i)));
int y1y = ((int) (liney1.get(i)));
int y2y = ((int) (liney2.get(i)));
g.drawLine(x1x,y1y,x2x, y2y);}
if ((lx1 != 0 && lx2 != 0 && ly1 != 0 && ly2 != 0) && (lx1 != 1 && ly1 != 1 && lx2<lx1 && ly2<ly1)){
for (int x1=0, x2=0; x1<linex1.size() && x2<linex2.size()-1; ++x1, ++x2){
int x1x = ((int) (linex1.get(x1)));
int x2x = ((int) (linex2.get(x2)));
int y1y = ((int) (liney1.get(y1)));
int y2y = ((int) (liney2.get(y2)));
g.drawLine(x1x,y1y,x2x, y2y);}
}
}
}
public void Panelint() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setBackground(new java.awt.Color(153, 204, 255));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
frame.class 代码如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package my.jpanel;
import java.awt.Graphics;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
// }
public class frame extends javax.swing.JFrame {
ArrayList<Integer> drawnpattern = new ArrayList<Integer>();
ArrayList<Integer> filepattern = new ArrayList<Integer>();
public frame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel1 = new my.jpanel.Panel();
btn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jta = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButtondraw = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panel1.setBackground(new java.awt.Color(153, 204, 255));
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 250, Short.MAX_VALUE)
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 150, Short.MAX_VALUE)
);
btn.setText("Print Co-ordinate and Save File");
btn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnActionPerformed(evt);
}
});
jta.setColumns(20);
jta.setRows(5);
jScrollPane1.setViewportView(jta);
jButton1.setText("Match patterns");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButtondraw.setText("Draw Both line");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(btn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addComponent(jButtondraw)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(24, 24, 24))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(107, 107, 107))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn)
.addComponent(jButton1)
.addComponent(jButtondraw))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String axis = null;
for (int i=0; i<(panel1.linex1.size()); ++i ){
axis = ("Line "+i+": "+" x1: "+panel1.linex1.get(i)+" y1: "+panel1.liney1.get(i)+" x2: "+panel1.linex2.get(i)+" y2: "+panel1.liney2.get(i)+".");
jta.append(axis);
jta.append("\n");
}
try {
File file = new File("I:/Programming/linedata.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true); // append=true so that we don't overwrite the whole file
BufferedWriter bw = new BufferedWriter(fw); // buffer writing
for (int i=0; i<(panel1.linex1.size()); ++i ){
bw.write("x1:"+panel1.linex1.get(i));
bw.write("y1:"+panel1.liney1.get(i));
bw.write("x2:"+panel1.linex2.get(i));
bw.write("y2:"+panel1.liney2.get(i));
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void jButtondrawActionPerformed(java.awt.event.ActionEvent evt){
//for (int i=0; i<((filepattern.size())/4); i++){
filepattern.add(26);
filepattern.add(50);
filepattern.add(36);
filepattern.add(130);
filepattern.add(36);
filepattern.add(130);
filepattern.add(64);
filepattern.add(97);
filepattern.add(64);
filepattern.add(97);
filepattern.add(81);
filepattern.add(127);
filepattern.add(81);
filepattern.add(127);
filepattern.add(100);
filepattern.add(96);
filepattern.add(100);
filepattern.add(96);
filepattern.add(122);
filepattern.add(128);
filepattern.add(122);
filepattern.add(128);
filepattern.add(127);
filepattern.add(57);
int fx1 = filepattern.get(0);
int fy1 = filepattern.get(1);
int fx2 = filepattern.get(2);
int fy2 = filepattern.get(3);
panel1.drawer(fx1, fy1, fx2, fy2);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String axis = null;
// add into array current drawn pattern
for (int i=0; i<(panel1.linex1.size()); ++i ){
drawnpattern.add((int)panel1.linex1.get(i));
drawnpattern.add((int)panel1.liney1.get(i));
drawnpattern.add((int)panel1.linex2.get(i));
drawnpattern.add((int)panel1.liney2.get(i));
// append current drawn pattern line data
axis = ("Line "+i+": "+" x1: "+panel1.linex1.get(i)+" y1: "+panel1.liney1.get(i)+" x2: "+panel1.linex2.get(i)+" y2: "+panel1.liney2.get(i)+".");
jta.append(axis);
jta.append("\n");
// read file and append file data to filepattern array
filepattern.add(26);
filepattern.add(50);
filepattern.add(36);
filepattern.add(130);
filepattern.add(36);
filepattern.add(130);
filepattern.add(64);
filepattern.add(97);
filepattern.add(64);
filepattern.add(97);
filepattern.add(81);
filepattern.add(127);
filepattern.add(81);
filepattern.add(127);
filepattern.add(100);
filepattern.add(96);
filepattern.add(100);
filepattern.add(96);
filepattern.add(122);
filepattern.add(128);
filepattern.add(122);
filepattern.add(128);
filepattern.add(127);
filepattern.add(57);
// after adding original data then we need to calculate the values of original data and also the incoming data.
// then we need to use our formula to compare
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtondraw;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jta;
private my.jpanel.Panel panel1;
// End of variables declaration
}