Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> JFree Chart Interactive (Mouse Editable), enabling JFree Chart mouse dragging 
V
    Опции темы
mole_84
Дата 19.4.2007, 19:43 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



If someone has already written a chart that listens to mouse events and enables mouse drag please show your code. 

Thanks in advance
PM MAIL   Вверх
powerOn
Дата 19.4.2007, 21:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


software saboteur
****


Профиль
Группа: Участник
Сообщений: 4367
Регистрация: 7.10.2005

Репутация: 31
Всего: 159



If I understand you correctly, you can draw your chart directly on JPanel and add listeners to it. For example:

Код

import java.awt.Graphics;
import java.awt.Graphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class NewJFrame extends javax.swing.JFrame {
                  
    private GraphPanel graphPanel1;

    public NewJFrame() {
        initComponents();
        
        XYSeries series = new XYSeries("series");
        
        for(int i = 0; i < 10; i++)
        {
           series.add(i,i); 
        }

        graphPanel1.createGraph(series);
    }
                       
    private void initComponents() {
        graphPanel1 = new compressor.GraphPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        graphPanel1.setLayout(new java.awt.BorderLayout());

        getContentPane().add(graphPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }                      

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
}

class GraphPanel extends javax.swing.JPanel {
    
    private JFreeChart chart = null;

    public GraphPanel() {
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
        });
    }

    private void formMouseDragged(java.awt.event.MouseEvent evt) {                                  
// TODO add your handling code here:
        System.out.println("Mouse Dragged!");
    }                                 
    
    public void createGraph(XYSeries series) {
        IntervalXYDataset xyDataset = new XYSeriesCollection(series);
        
        chart = ChartFactory.createXYBarChart("My Chart",  "X", false, "Y",
                xyDataset, PlotOrientation.VERTICAL, true, true, true);
    }
    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(chart != null ) {
            chart.draw((Graphics2D) g, this.getBounds());
        }
    }
}



--------------------
user posted image нет времени думать - нужно писать КОД!

PM MAIL   Вверх
mole_84
Дата 24.4.2007, 15:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



Thanks but I came across an odd line:
Цитата(powerOn @  19.4.2007,  21:25 Найти цитируемый пост)
graphPanel1 = new compressor.GraphPanel();


I understand that answer maybe simple but still: What is compressor?

PM MAIL   Вверх
mole_84
Дата 24.4.2007, 16:13 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



Oh. I see. I had just to delete it:)
But still one question.
How should I make a chart ineractive?
I want to redraw a chart according to the mouse motion. 
For example to add new point or move a point or make one of the columns higher.
Could you please spend a bit more time?

Thanks in advance. 
PM MAIL   Вверх
mole_84
Дата 24.4.2007, 17:12 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



powerOn, I've done in this way:

Код

public GraphPanel()
{
            addMouseListener(java.awt.event.MouseAdapter()
            {
                      public void mousePressed(java.awt.event.MouseEvent e)
                      {
                             formMouseClicked(e)
                       }
             });
}
..........
private void formMouseClicked(java.awt.event.MouseEvent e)
{
      series.add(e.getX(),e.getY());
      CreateGrapph(series);
}

getX() return coordinate in pixels. Is it possible to convert it coordinate of a chart?
And one more question:
Is it possible to find out whether a chart was clicked? I mean to distinguish clicking on a chart and clicking on other part of a frame?
  
Thanks
PM MAIL   Вверх
powerOn
Дата 24.4.2007, 21:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


software saboteur
****


Профиль
Группа: Участник
Сообщений: 4367
Регистрация: 7.10.2005

Репутация: 31
Всего: 159



Цитата(mole_84 @  24.4.2007,  16:45 Найти цитируемый пост)
I understand that answer maybe simple but still: What is compressor?

This is my mistake. I took this code from one of my projects and forgot to clean up a package name (compressor).  smile 

Цитата(mole_84 @  24.4.2007,  17:13 Найти цитируемый пост)
I had just to delete it:)

That's right. 

Цитата(mole_84 @  24.4.2007,  17:13 Найти цитируемый пост)
How should I make a chart ineractive?
I want to redraw a chart according to the mouse motion. 
For example to add new point or move a point or make one of the columns higher.
Could you please spend a bit more time?


I think, this is not trivial work. For a start, you should look a demo from official JFreeChart web site. I hope you find where something interesting. Otherwise, you need create own component (it means writing a lot of code).

Цитата(mole_84 @  24.4.2007,  18:12 Найти цитируемый пост)
Is it possible to convert it coordinate of a chart?

I think, it's very difficult, but possible. 


--------------------
user posted image нет времени думать - нужно писать КОД!

PM MAIL   Вверх
mole_84
Дата 27.4.2007, 16:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



This code maybe useful if you want to translate event coordinates to your axis coordinates:

Код

java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.NumberFormat;
import javax.swing.*;
 
public class Translation extends JPanel {
    JLabel xLabel;
    JLabel yLabel;
    NumberFormat nf;
    double[] data = { 16.0, 32.9, 7.4, 18.9, 12.3 };
    final int Y_GRADS = 5;
    final int PAD = 35;
    final int SPAD = 3;
    final int TICK = 2;
    double maxVal;
 
    public Translation() 
    {
        nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(1);
        nf.setMaximumFractionDigits(1);
        maxVal = getMaxValue();
        addMouseMotionListener(sweep);
    }
 
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        drawAxes(g2);
        plotData(g2);
    }
 
    private void plotData(Graphics2D g2) {
        for(int j = 0; j < data.length; j++) {
            Point2D.Double p = modelToView(j, data[j]);
            if(j < data.length-1) {
                Point2D.Double next = modelToView(j+1, data[j+1]);
                g2.setPaint(Color.blue);
                g2.draw(new Line2D.Double(p, next));
            }
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
        }
    }
 
    private Point2D.Double modelToView(double x, double y) {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = PAD + x*(getWidth() - 2*PAD)/(data.length-1);
        p.y = h-PAD - y*(h - 2*PAD)/maxVal;
        return p;
    }
 
    public Point2D.Double viewToModel(double x, double y) {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = (x - PAD) * (data.length-1) / (getWidth() - 2*PAD);
        p.y = (h - PAD - y) * maxVal / (h - 2*PAD);
        return p;
    }
 
    private void drawAxes(Graphics2D g2) {
        int w = getWidth();
        int h = getHeight();
        double xInc = (double)(w - 2*PAD)/(data.length-1);
        double yInc = (double)(h - 2*PAD)/Y_GRADS;
        // Abcissa
        g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
        // Tick marks
        double y1 = h-PAD, y2 = y1+TICK;
        for(int j = 0; j <= data.length; j++) {
            double x = PAD + j*xInc;
            g2.draw(new Line2D.Double(x, y1, x, y2));
        }
        // Labels
        Font font = g2.getFont().deriveFont(14f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = font.getLineMetrics("0", frc);
        float sx, sy = h - PAD + SPAD + lm.getAscent();
        for(int j = 0; j < data.length; j++) {
            String s = String.valueOf(j);
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD + j*xInc - width/2);
            g2.drawString(s, sx, sy);
        }
 
        // Ordinate
        g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
        // Tick marks
        double x1 = PAD, x2 = PAD-TICK;
        for(int j = 0; j <= Y_GRADS; j++) {
            double y = PAD + j*yInc;
            g2.draw(new Line2D.Double(x1, y, x2, y));
        }
        // Labels
        for(int j = 0; j <= data.length; j++) {
            String s = nf.format(maxVal*(1.0 - (double)j/data.length));
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD - SPAD - width);
            sy = (float)(PAD + j*yInc + lm.getAscent()/3);
            g2.drawString(s, sx, sy);
        }
    }
 
    private double getMaxValue() {
        double max = -Double.MAX_VALUE;
        for(int j = 0; j < data.length; j++) {
            if(data[j] > max) {
                max = data[j];
            }
        }
        return max;
    }
 
    MouseMotionListener sweep = new MouseMotionAdapter() 
    {
        public void mouseMoved(MouseEvent e) 
        {
            Point2D.Double p = viewToModel(e.getX(), e.getY());            
            xLabel.setText(nf.format(p.x));
            yLabel.setText(nf.format(p.y));            
        }
    };
 
    private JPanel getLast() {
        xLabel = new JLabel();
        yLabel = new JLabel();
        Dimension d = new Dimension(45, 25);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        addComponents(new JLabel("x ="), xLabel, panel, gbc, d, true);
        addComponents(new JLabel("y ="), yLabel, panel, gbc, d, false);
        return panel;
    }
 
    private void addComponents(JComponent c1, JComponent c2, Container c,
                               GridBagConstraints gbc, Dimension d, boolean b) {
        gbc.weightx = b ? 1.0 : 0;
        gbc.anchor = GridBagConstraints.EAST;
        c.add(c1, gbc);
        c2.setPreferredSize(d);
        gbc.weightx = b ? 0 : 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        c.add(c2, gbc);
    }
 
    public static void main(String[] args) {
        Translation test = new Translation();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test);
        f.getContentPane().add(test.getLast(), "Last");
        f.setSize(500,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}



PM MAIL   Вверх
mole_84
Дата 27.4.2007, 18:48 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



In this code points can be moved along a vertical line:

Код

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.NumberFormat;
import javax.swing.*;
 
public class Translation extends JPanel 
{
    JLabel xLabel;
    JLabel yLabel;
    NumberFormat nf;
    double[] data = { 16.0, 32.9, 7.4, 18.9, 12.3 };
    final int Y_GRADS = 5;
    final int PAD = 35;
    final int SPAD = 3;
    final int TICK = 2;
    boolean caught = false;
    double maxVal;
    int pointChanged = -1;
 
    public Translation() 
    {
        nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(1);
        nf.setMaximumFractionDigits(1);
        maxVal = getMaxValue();
        addMouseMotionListener(sweep);
        addMouseMotionListener(myMouseMotionListener);        
        addMouseListener(myMouseListener);
    }
 
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        drawAxes(g2);
        plotData(g2);
    }
 
    private void plotData(Graphics2D g2) {
        for(int j = 0; j < data.length; j++) {
            Point2D.Double p = modelToView(j, data[j]);
            if(j < data.length-1) {
                Point2D.Double next = modelToView(j+1, data[j+1]);
                g2.setPaint(Color.blue);
                g2.draw(new Line2D.Double(p, next));
            }
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
        }
    }
 
    private Point2D.Double modelToView(double x, double y) {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = PAD + x*(getWidth() - 2*PAD)/(data.length-1);
        p.y = h-PAD - y*(h - 2*PAD)/maxVal;
        return p;
    }
 
    public Point2D.Double viewToModel(double x, double y) 
    {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = (x - PAD) * (data.length-1) / (getWidth() - 2*PAD);      
        p.y = (h - PAD - y) * maxVal / (h - 2*PAD);        
        return p;
    }
 
    private void drawAxes(Graphics2D g2) 
    {
        int w = getWidth();
        int h = getHeight();
        
        double xInc = (double)(w - 2*PAD)/(data.length-1);
        double yInc = (double)(h - 2*PAD)/Y_GRADS;
        // Abcissa
        g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
        // Tick marks
        double y1 = h-PAD, y2 = y1+TICK;
        for(int j = 0; j <= data.length; j++) {
            double x = PAD + j*xInc;
            g2.draw(new Line2D.Double(x, y1, x, y2));
        }
        // Labels
        Font font = g2.getFont().deriveFont(14f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = font.getLineMetrics("0", frc);
        float sx, sy = h - PAD + SPAD + lm.getAscent();
        for(int j = 0; j < data.length; j++) {
            String s = String.valueOf(j);
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD + j*xInc - width/2);
            g2.drawString(s, sx, sy);
        }
 
        // Ordinate
        g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
        // Tick marks
        double x1 = PAD, x2 = PAD-TICK;
        for(int j = 0; j <= Y_GRADS; j++) 
        {
            double y = PAD + j*yInc;
            g2.draw(new Line2D.Double(x1, y, x2, y));
        }
        // Labels
        for(int j = 0; j <= data.length; j++) 
        {
            String s = nf.format(maxVal*(1.0 - (double)j/data.length));
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD - SPAD - width);
            sy = (float)(PAD + j*yInc + lm.getAscent()/3);
            g2.drawString(s, sx, sy);
        }
    }
 
    private double getMaxValue() {
        double max = -Double.MAX_VALUE;
        for(int j = 0; j < data.length; j++) {
            if(data[j] > max) {
                max = data[j];
            }
        }
        return max;
    }
 
    MouseMotionListener sweep = new MouseMotionAdapter() 
    {
        public void mouseMoved(MouseEvent e) 
        {
            Point2D.Double p = viewToModel(e.getX(), e.getY());            
            xLabel.setText(nf.format(p.x));
            yLabel.setText(nf.format(p.y));            
        }
    };
    
    MouseMotionListener myMouseMotionListener = new MouseMotionAdapter()
    {
        
        public void mouseDragged(MouseEvent e)
        {        
            //checkForCaught(e);                    
        }      
    };
    
    private void checkForCaught(MouseEvent e)
    {
        
        Point2D.Double p = viewToModel(e.getX(), e.getY());    
        System.out.println(p.x+" "+p.y);
        double dx = 0.5;//further calculateDx();
        double dy = 0.5;//
        for (int i=0;i<data.length;i++)
        {        
            if ( (p.x>(i-dx)) && (p.x<(i+dx)) && (p.y>(data[i]-dy))&& (p.y<(data[i]+dy)))
            {                
                System.out.println("Caught");       
                caught = true;
                pointChanged = i;
            }        
        }
    }
    
    MouseListener myMouseListener = new MouseAdapter()
    {      
        public void mouseReleased(MouseEvent e)
        {
            Point2D.Double p = viewToModel(e.getX(), e.getY()); 
            if (caught) 
            {
                 data[pointChanged] = p.y;
                 caught = false;
                 System.out.println("data changed");
                 redraw();
            }
        }       
        
        public void mousePressed(MouseEvent e)
        {
            System.out.println("Pressed");
            checkForCaught(e);
        }    
    };
    
    public void redraw()
    {
        paintComponent(this.getGraphics());
    }
 
    private JPanel getLast() 
    {
        xLabel = new JLabel();
        yLabel = new JLabel();
        Dimension d = new Dimension(45, 25);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        addComponents(new JLabel("x ="), xLabel, panel, gbc, d, true);
        addComponents(new JLabel("y ="), yLabel, panel, gbc, d, false);
        return panel;
    }
 
    private void addComponents(JComponent c1, JComponent c2, Container c,
                               GridBagConstraints gbc, Dimension d, boolean b) {
        gbc.weightx = b ? 1.0 : 0;
        gbc.anchor = GridBagConstraints.EAST;
        c.add(c1, gbc);
        c2.setPreferredSize(d);
        gbc.weightx = b ? 0 : 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        c.add(c2, gbc);
    }
 
    public static void main(String[] args) 
    {
        Translation test = new Translation();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test);
        f.getContentPane().add(test.getLast(), "Last");
        f.setSize(500,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}


PM MAIL   Вверх
mole_84
Дата 27.4.2007, 19:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 9
Регистрация: 19.4.2007

Репутация: нет
Всего: нет



This is a final version. Now plot is redrawn while a point is dragged. powerOn thanks again. You gave an initial push.

Код


import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.NumberFormat;
import javax.swing.*;
 
public class Translation extends JPanel 
{
    JLabel xLabel;
    JLabel yLabel;
    NumberFormat nf;
    double[] data = { 16.0, 32.9, 7.4, 18.9, 12.3 };
    final int Y_GRADS = 5;
    final int PAD = 35;
    final int SPAD = 3;
    final int TICK = 2;
    boolean caught = false;
    double maxVal;
    int pointChanged = -1;
 
    public Translation() 
    {
        nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(1);
        nf.setMaximumFractionDigits(1);
        maxVal = getMaxValue();
        addMouseMotionListener(sweep);
        addMouseMotionListener(myMouseMotionListener);        
        addMouseListener(myMouseListener);
    }
 
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        drawAxes(g2);
        plotData(g2);
    }
 
    private void plotData(Graphics2D g2) {
        for(int j = 0; j < data.length; j++) {
            Point2D.Double p = modelToView(j, data[j]);
            if(j < data.length-1) {
                Point2D.Double next = modelToView(j+1, data[j+1]);
                g2.setPaint(Color.blue);
                g2.draw(new Line2D.Double(p, next));
            }
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
        }
    }
 
    private Point2D.Double modelToView(double x, double y) {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = PAD + x*(getWidth() - 2*PAD)/(data.length-1);
        p.y = h-PAD - y*(h - 2*PAD)/maxVal;
        return p;
    }
 
    public Point2D.Double viewToModel(double x, double y) 
    {
        double h = getHeight();
        Point2D.Double p = new Point2D.Double();
        p.x = (x - PAD) * (data.length-1) / (getWidth() - 2*PAD);      
        p.y = (h - PAD - y) * maxVal / (h - 2*PAD);        
        return p;
    }
 
    private void drawAxes(Graphics2D g2) 
    {
        int w = getWidth();
        int h = getHeight();
        
        double xInc = (double)(w - 2*PAD)/(data.length-1);
        double yInc = (double)(h - 2*PAD)/Y_GRADS;
        // Abcissa
        g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
        // Tick marks
        double y1 = h-PAD, y2 = y1+TICK;
        for(int j = 0; j <= data.length; j++) {
            double x = PAD + j*xInc;
            g2.draw(new Line2D.Double(x, y1, x, y2));
        }
        // Labels
        Font font = g2.getFont().deriveFont(14f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = font.getLineMetrics("0", frc);
        float sx, sy = h - PAD + SPAD + lm.getAscent();
        for(int j = 0; j < data.length; j++) {
            String s = String.valueOf(j);
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD + j*xInc - width/2);
            g2.drawString(s, sx, sy);
        }
 
        // Ordinate
        g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
        // Tick marks
        double x1 = PAD, x2 = PAD-TICK;
        for(int j = 0; j <= Y_GRADS; j++) 
        {
            double y = PAD + j*yInc;
            g2.draw(new Line2D.Double(x1, y, x2, y));
        }
        // Labels
        for(int j = 0; j <= data.length; j++) 
        {
            String s = nf.format(maxVal*(1.0 - (double)j/data.length));
            float width = (float)font.getStringBounds(s, frc).getWidth();
            sx = (float)(PAD - SPAD - width);
            sy = (float)(PAD + j*yInc + lm.getAscent()/3);
            g2.drawString(s, sx, sy);
        }
    }
 
    private double getMaxValue() {
        double max = -Double.MAX_VALUE;
        for(int j = 0; j < data.length; j++) {
            if(data[j] > max) {
                max = data[j];
            }
        }
        return max;
    }
 
    MouseMotionListener sweep = new MouseMotionAdapter() 
    {
        public void mouseMoved(MouseEvent e) 
        {
            Point2D.Double p = viewToModel(e.getX(), e.getY());            
            xLabel.setText(nf.format(p.x));
            yLabel.setText(nf.format(p.y));            
        }
    };
    
    
    private void checkForRedraw(MouseEvent e)
    {
        Point2D.Double p = viewToModel(e.getX(), e.getY()); 
            if (caught) 
            {
                 data[pointChanged] = p.y;                 
                 System.out.println("data changed");
                 redraw();
            }
    }
    
    private void checkForCaught(MouseEvent e)
    {
        
        Point2D.Double p = viewToModel(e.getX(), e.getY());            
        double dx = 0.5;//further calculateDx();
        double dy = 0.5;//
        for (int i=0;i<data.length;i++)
        {        
            if ( (p.x>(i-dx)) && (p.x<(i+dx)) && (p.y>(data[i]-dy))&& (p.y<(data[i]+dy)))
            {                
                System.out.println("Caught");       
                caught = true;
                pointChanged = i;
            }        
        }
    }
    MouseMotionListener myMouseMotionListener = new MouseMotionAdapter()
    {
        
        public void mouseDragged(MouseEvent e)
        {        
            checkForCaught(e);   
            checkForRedraw(e);            
        }      
    };
    
    MouseListener myMouseListener = new MouseAdapter()
    {      
        public void mouseReleased(MouseEvent e)
        {
            checkForRedraw(e);
            caught = false;
        }       
        
        public void mousePressed(MouseEvent e)
        {            
            checkForCaught(e);
        }    
    };
    
    public void redraw()
    {
        paintComponent(this.getGraphics());
    }
 
    private JPanel getLast() 
    {
        xLabel = new JLabel();
        yLabel = new JLabel();
        Dimension d = new Dimension(45, 25);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        addComponents(new JLabel("x ="), xLabel, panel, gbc, d, true);
        addComponents(new JLabel("y ="), yLabel, panel, gbc, d, false);
        return panel;
    }
 
    private void addComponents(JComponent c1, JComponent c2, Container c,
                               GridBagConstraints gbc, Dimension d, boolean b) {
        gbc.weightx = b ? 1.0 : 0;
        gbc.anchor = GridBagConstraints.EAST;
        c.add(c1, gbc);
        c2.setPreferredSize(d);
        gbc.weightx = b ? 0 : 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        c.add(c2, gbc);
    }
 
    public static void main(String[] args) 
    {
        Translation test = new Translation();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test);
        f.getContentPane().add(test.getLast(), "Last");
        f.setSize(500,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}





Это сообщение отредактировал(а) powerOn - 27.4.2007, 20:16
PM MAIL   Вверх
powerOn
Дата 27.4.2007, 20:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


software saboteur
****


Профиль
Группа: Участник
Сообщений: 4367
Регистрация: 7.10.2005

Репутация: 31
Всего: 159



Цитата(mole_84 @  27.4.2007,  20:58 Найти цитируемый пост)
powerOn thanks again.

you are welcome.


--------------------
user posted image нет времени думать - нужно писать КОД!

PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   jk1
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, jk1.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: GUI и Java FX приложения | Следующая тема »


 




[ Время генерации скрипта: 0.0568 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.