使用更新JSlider绘制图形

时间:2015-02-15 18:24:33

标签: java swing graph event-handling jslider

我正在制作一个从用户给出的数学表达式绘制图形的图示器。此外,程序有一个滑块和播放按钮,用户可以选择滑块及其范围的变量,以便点击播放按钮滑块将从最小范围开始到最大,并且将绘制图形。 对于计时器我使用previous question的答案。

表示我使用This代码。 (我特意在Plotter.java文件上工作)

编辑过的Plotter.java文件,带有可播放的滑块(计时器)代码:

import java.util.*;


public class Plotter extends JFrame implements ActionListener
{   

private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private int value;
private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton ;
private Graph graph;
private JPanel userPanel , sliderPanel;

private JSlider slider_1 = new JSlider();
private JButton playButton = new JButton();
private JTextField textField = new JTextField();
private Timer timer ;
private ImageIcon playIcon = new ImageIcon(getClass().getResource("/images/play.png"));
private ImageIcon pauseIcon = new ImageIcon(getClass().getResource("/images/pause.png"));

public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
    super("Plotter");
    textField.setBounds(266, 11, 134, 28);
    textField.setColumns(10);

    createNewGraph(lowX, highX, frequency, file);
    createLayout();
    //createsliderpanel();
}

private void createLayout() throws GraphArgumentsException
{
    Container c = getContentPane();
    setSize(850,600);
    getContentPane().setLayout(null);
    c.add(graph);
    c.add(userPanel);

    JPanel down = new JPanel();
    down.setBounds(0, 437, 650, 119);
    getContentPane().add(down);
    down.setLayout(null);
    slider_1.setValue(0);
    slider_1.setMajorTickSpacing(5);
    slider_1.setMinorTickSpacing(1);
    slider_1.setPaintLabels(true);
    slider_1.setPaintTicks(true);
    slider_1.setBounds(145, 51, 467, 42);

    down.add(slider_1);
    playButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    playButton.setBounds(16, 51, 117, 29);
    playButton.setIcon(playIcon);
    down.add(playButton);

    down.add(textField);

    JPanel panel_1 = new JPanel();
    panel_1.setBounds(649, 39, 201, 517);
    getContentPane().add(panel_1);
    panel_1.setLayout(new BorderLayout(0, 0));
//  c.add(sliderPanel , BorderLayout.SOUTH);
    createMenuBar();
}



/**
 * Creates a new Graph instance and adds equations from file into Graph
 * @param eqFile file where equations are stored
 * @throws IOException
 */
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
    Equation[] eq = null;
    graph = new Graph(minX, maxX, freq);
    graph.setBounds(0, 39, 650, 396);

    eq = readEquationsFromFile(eqFile);

    if (eq != null)
        addEquation(eq);

    graph.setBackground(Color.WHITE);
    userPanel = createUserPanel(eq);
}

private void createMenuBar()
{
    menuBar.add(fileMenu);
    fileMenu.add(openMenuItem);
    fileMenu.add(saveMenuItem);
    fileMenu.addSeparator();
    fileMenu.add(exitMenuItem);
    openMenuItem.addActionListener(this);
    saveMenuItem.addActionListener(this);
    exitMenuItem.addActionListener(this);
    setJMenuBar(menuBar);
}

/**
 * Create user panel at top of the GUI for adding and editing functions
 * @param eq equation list to add into the combo box
 * @return panel containing buttons and an editable combo box
 */
private JPanel createUserPanel(Equation[] eq)
{
    JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
    up.setBounds(0, 0, 844, 39);
    eqCombo.setEditable(true);

    if (eq != null)
    {
        //Add all equations into the combo box
        for (int i = 0; i < eq.length; i++)
            eqCombo.addItem(eq[i].getPrefix());
    }

    addButton = new JButton("Add");
    removeButton = new JButton("Remove");
    clearButton = new JButton("Clear");

    addButton.addActionListener(this);
    removeButton.addActionListener(this);
    clearButton.addActionListener(this);

    up.add(eqCombo);
    up.add(addButton);
    up.add(removeButton);
    up.add(clearButton);


    return up;





}

// slider panel
/*private JPanel createsliderpanel()
{
    JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));

    playbutton = new JButton("Play");
    slider = new JSlider();
    field = new JTextField();


    down.add(playbutton);
    down.add(slider);
    down.add(field);


    return down;
}*/



/**
 * Check action lister for button and menu events
 */
public void actionPerformed(ActionEvent e)
{

    timer = new Timer(500, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int value = slider_1.getValue() + 1;
            if (value >= slider_1.getMaximum()) {
                stopTheClock();
            } else {
                slider_1.setValue(value);
            }
        }
    });
    slider_1.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            textField.setText(Integer.toString(slider_1.getValue()));
        }
    });
    slider_1.setValue(0);

    playButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (timer.isRunning()) {
                stopTheClock();
            } else {
                startTheClock();
            }
        }
    });

    if (e.getSource() == addButton)
        addEquation((String)eqCombo.getSelectedItem());

    else if (e.getSource() == removeButton)
        removeEquation(eqCombo.getSelectedIndex());

    else if (e.getSource() == saveMenuItem)
        saveEquationList();

    else if (e.getSource() == openMenuItem)
        loadEquations();

    else if (e.getSource() == clearButton)
        clearEquations();


    else if (e.getSource() == exitMenuItem)
        System.exit(0);
}



/**
 * Save equations to file
 *
 */
private void saveEquationList()
{
    try
    {
        PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
        for (int i = 0; i < eqCombo.getItemCount(); i++)
            out.println(eqCombo.getItemAt(i));

        out.close();
    }
    catch (IOException e)
    {
        System.out.println(e);

    }
}


private void clearEquations()
{
    graph.removeAllEquations();
    eqCombo.removeAllItems();
}

/**
 * Load equations from file into graph
 *
 */
private void loadEquations()
{
    String file=null;
    JFileChooser fc = new JFileChooser();

    fc.showOpenDialog(null);
    if (fc.getSelectedFile() != null)
    {
        file = fc.getSelectedFile().getPath();

        try
        {
            Equation[] eq = readEquationsFromFile(file);
            if (eq != null)
            {
                clearEquations();
                addEquation(eq);

                //Restock combo box with new equations
                for (int i = 0; i < eq.length; i++)
                    eqCombo.addItem(eq[i].getPrefix());
            }
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
        }
    }
}

/**
 * Add an equation to the Graph
 * @param eq equation
 */
private void addEquation(String eq)
{
    try
    {
        if (eq != null && !eq.equals(""))
        {
            Equation equation = new Equation(eq);
            eqCombo.addItem(eq);
            graph.addEquation(equation);
        }
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
    }
}
/**
 * Add multiple equations to Graph
 * @param eq equation array
 */
private void addEquation(Equation[] eq)
{
    for (int i = 0; i < eq.length; i++)
    {
        graph.addEquation(eq[i]);
    }
}

/**
 * Remove equation from Graph
 * @param index index to remove
 */
private void removeEquation(int index)
{
    if (index >= 0)
    {
        graph.removeEquation(index);
        eqCombo.removeItem(eqCombo.getSelectedItem());
    }
}
// Timer methods
protected void startTheClock() {
    slider_1.setValue(0);
    timer.start();
    playButton.setIcon(pauseIcon);;
}

protected void stopTheClock() {
    timer.stop();
    playButton.setIcon(playIcon);
}


/**
 * Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
 * @param file name of file containing equations
 * @return array of equations
 * @throws IOException
 */
public Equation[] readEquationsFromFile(String file) throws IOException
{
    ArrayList<Equation> eqList = new ArrayList<Equation>(20);

    if (file == null)
        return null;

    String line;
    int lineCount = 1;
    try
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null)
        {
            Equation eq = new Equation(line);
            eqList.add(eq);
            lineCount++;
        }
        br.close();
        return ((Equation[])(eqList.toArray(new Equation[0])));
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
        return null;
    }
}






/**
 * Set up Plotter object and draw the graph.
 * @param args command line arguments for Plotter
 */
public static void main(String[] args)
{
    Scanner s = new Scanner(System.in);

    String expr     = JOptionPane.showInputDialog("Enter your expression");
    String maxInput = JOptionPane.showInputDialog("Enter max value of x");
    String minInput = JOptionPane.showInputDialog("Enter min value of x");

    double frequency = 0.01;
    double maxX = Double.parseDouble(maxInput);
    double minX = Double.parseDouble(minInput);

    String eqFile = null;
        try
    {
        ///double minX = Double.parseDouble(args[0]);
    //  double maxX = Double.parseDouble(args[1]);
    //  double frequency = Double.parseDouble(args[2]);
        //double minX = -10; 
        //double maxX = 10; 
        //double frequency = 0.01;

        if (args.length > 3)
            eqFile = args[3];   

        Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
        plotterGUI.setVisible(true);
        plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    catch (NumberFormatException e)
    {
        System.out.println("ERR: Invalid arguments");
    }
    catch (GraphArgumentsException e)
    {
        System.out.println(e.getMessage());
    }
    catch (IOException e)
    {
        System.out.print("ERR4: Unable to read or access file");
    }

   }
}

程序的一般外观:

gifgraph

现在我想更改代码,以便滑块会影响图示器。这意味着当用户选择从-10到10的x范围时,通过单击播放按钮,当滑块更改x时,图示器开始绘制图形从-10到10 Gapminder chart是关于滑块和grapher应该工作的示例。 enter image description here

问题是我该怎么做?

1 个答案:

答案 0 :(得分:0)

这里有一个小代码,可以帮助您了解JSlider。

      import javax.swing.*;
      import javax.swing.event.ChangeEvent;
      import javax.swing.event.ChangeListener;


  class demo extends JFrame
{
JFrame f=new JFrame("G");
JSlider slide=new JSlider();
JTextField field=new JTextField();
JTextField d=new JTextField();
final double value=0;

 demo()
{
    setSize(500,500);

    f.setSize(600,600);
    f.setVisible(true);


    slide.setBounds(100,100,200,50);
    field.setBounds(150,150,100,30);
    d.setBounds(0,0,0,0);

    add(slide);
    add(field);
    add(d);
}


 public static void main(String args[])
          {
            demo m=new demo();
            m.setVisible(true);
            m.setLocationRelativeTo(null);
            m.slidec();



              }

public double slidec()
{
    slide.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent e) {


      double value=((JSlider)e.getSource()).getValue();
      field.setText(Double.toString(value));

     }

    });
    return value;
     }






}