简体   繁体   English

JPanel内未显示图形

[英]Graph not showing inside JPanel

I need some help with my code; 我的代码需要一些帮助; I have a program that will show the graph of Ohm's Law. 我有一个程序可以显示欧姆定律图。 The graph was showing before I put a save button. 在显示保存按钮之前,该图已显示。 When i run the program, it will only show the everything except for the graph. 当我运行程序时,它将仅显示除图形之外的所有内容。 Also, I have problems in saving the current and voltage array into a .txt file. 另外,在将电流和电压数组保存到.txt文件中时遇到问题。 Please help! 请帮忙!

import java.awt.*;  
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import static java.nio.file.Files.newBufferedWriter;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;  

public class DrawGraph extends JPanel {  
double current[] = new double [999];
double voltage[] = new double [999];
final int TEXT = 20;   

@Override
public void paintComponent(Graphics g) {  
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int w = 400;  
    int h = 400;  
    g2.setStroke(new BasicStroke(3));
    g2.drawLine(TEXT, TEXT, TEXT, h-TEXT);  
    g2.drawLine(TEXT, h-TEXT, w-TEXT, h-TEXT);  

    for(int x= 0; x<1000; x++ )
    {
        current[x]=x+1;
        voltage[x]=x+1;
    }

    g2.setPaint(Color.red);  
    g2.setStroke(new BasicStroke(2));
    g2.draw(new Line2D.Double(TEXT, h-TEXT, w-TEXT ,TEXT ));  

    // Draw labels.
    g2.setPaint(Color.black);   
    Font font = g2.getFont();

    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = font.getLineMetrics("0", frc);
    float sheight = lm.getAscent() + lm.getDescent();
    // Ordinate label.
    g2.setFont(new Font("Century Gothic", Font.PLAIN, 15));
    String s = "Voltage V";
    float sY = TEXT + ((h - 2*TEXT) - s.length()*sheight)/2 + lm.getAscent();
    for(int r = 0; r < s.length(); r++) 
    {
          String letter = String.valueOf(s.charAt(r));
          float swidth = (float)font.getStringBounds(letter, frc).getWidth();
          float sX = (TEXT - swidth)/2;
          g2.drawString(letter, sX, sY);
          sY += sheight;
    }
    // Abcissa label.
    s = "Current A";
    sY = h - TEXT + (TEXT - sheight)/2 + lm.getAscent();
    float swidth = (float)font.getStringBounds(s, frc).getWidth();
    float sX = (w - swidth)/2;
    g2.drawString(s, sX, sY);

    //Gridlines
    int b=TEXT+(((w-TEXT)-TEXT)/10);
    g2.setPaint(Color.gray);
    for(int a=1; a<=10; a++)
    {
           b+=36;
           g2.setStroke(new BasicStroke(1));
           g2.drawLine(b, h-TEXT, b, TEXT);  
           g2.drawLine(TEXT, b, w-TEXT, b); 

    }

}  

private static void createAndShowGui() {
  JFrame frame = new JFrame("Ohm's Law");

  JPanel panel = new JPanel(new BorderLayout(3,1));

  JPanel titlepanel = new JPanel();
  titlepanel.setPreferredSize(new Dimension(400,50));
  JLabel title = new JLabel("OHM'S LAW");
  title.setFont(new Font("Century Gothic", Font.BOLD, 25));
  titlepanel.add(title);
  panel.add(titlepanel,BorderLayout.NORTH);

  JPanel graphpanel = new JPanel();
  graphpanel.setBackground(Color.white);
  graphpanel.setPreferredSize(new Dimension(420,420));
  DrawGraph drawgraph = new DrawGraph();
  graphpanel.add(drawgraph);
  panel.add(graphpanel,BorderLayout.CENTER);

  JPanel buttonpanel = new JPanel ();
  buttonpanel.setPreferredSize(new Dimension(400,50));
  JButton save = new JButton("SAVE");
  save.addActionListener(
    new ActionListener()
    {

        @Override
        public void actionPerformed (ActionEvent event)
        {

            JFrame parentFrame = new JFrame();

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Specify a file to save");   

            int userSelection = fileChooser.showSaveDialog(parentFrame);

            if (userSelection == JFileChooser.APPROVE_OPTION) 

            {
                java.io.File fileToSave = fileChooser.getSelectedFile();
                try 
                {                                    
                    fileToSave.createNewFile();
                    try (BufferedWriter writer = newBufferedWriter(fileToSave.toPath(), Charset.defaultCharset(), StandardOpenOption.WRITE)) 
                    {

                            writer.write("V=I\t R=1\r Voltage \t Current\n");

                            //writer.write("Material: " + material.getSelectedValue().toString()+"\r\nv = " + v + "\r\nE1 = " + e1 + "\r\nE2 = " + e2);
                    }
                } 
                catch (IOException ex) 
                {
                    Logger.getLogger(DrawGraph.class.getName()).log(Level.SEVERE, null, ex);
                }                                
                System.out.println("Save as file: " + fileToSave.getAbsolutePath());
            }
        }
    }
  );
  save.setFont(new Font("Century Gothic", Font.BOLD, 15));
  buttonpanel.add(save);
  panel.add(buttonpanel, BorderLayout.SOUTH);

  frame.add(panel);
  frame.getContentPane().setBackground(Color.GREEN);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.setLocationByPlatform(true);
  frame.setVisible(true);
}

public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
     @Override
     public void run() {
        createAndShowGui();
     }
  });
 }
}  
  JPanel graphpanel = new JPanel();
  graphpanel.setBackground(Color.white);
  graphpanel.setPreferredSize(new Dimension(420,420));
  DrawGraph drawgraph = new DrawGraph();
  graphpanel.add(drawgraph);
  panel.add(graphpanel,BorderLayout.CENTER);

You add your DrawGraph component to a JPanel. 您将DrawGraph组件添加到JPanel。 By default a JPanel uses a FlowLayout() which respects the preferred size of any component added to it. 默认情况下,JPanel使用FlowLayout()来preferred size添加到它的任何组件的preferred size Your custom DrawGraph component has a preferred size of 0, so there is nothing to paint. 您的自定义DrawGraph组件的首选大小为0,因此无需绘制任何内容。

Every Swing component is responsible for determining its own preferred size so you need to override the getPreferredSize() method of your DrawGraph components to return its preferred size so the layout manager can do its job. 每个Swing组件都有责任确定自己的首选大小,因此您需要重写DrawGraph组件的getPreferredSize()方法以返回其首选大小,以便布局管理器可以执行其工作。

Read the section from the Swing tutorial on Custom Painting for more information and working examples. 阅读有关定制绘画的Swing教程中的部分,以获取更多信息和工作示例。

Also, don't use setPreferredSize(). 另外,不要使用setPreferredSize()。 The layout manager will determine the preferred size of the panel based on the components added to it. 布局管理器将根据添加到其中的组件确定面板的首选大小。

First things first. 首先是第一件事。 Make a JFrame derived class and in that class insert separately your buttonPanel which extends JPanel on the BorderLayout.SOUTH and your DrawGraph panel on the BorederLayout.Center . 创建一个JFrame派生的类,并在该类中分别插入您的buttonPanel (在BorderLayout.SOUTH上扩展JPanel和在DrawGraph上的BorederLayout.Center面板。 Don't add butttonPanel to the window you are drawing in. 不要将butttonPanel添加到要绘制的窗口中。

I also suggest to change name from DrawGraph to GraphPanel you can do it just by clicking on any reference to the class and hitting alt+shift+r if you use Eclipse IDE. 我还建议从改变名称DrawGraphGraphPanel你可以通过点击任何参考类和击球做alt+shift+r ,如果你使用Eclipse IDE中。

So to conclude: 因此得出结论:

public class MainWindow extends JFrame(){


  public void createGUI(){
    add(graphPanel = new GraphPanel(), BorderLayout.CENTER);
    add(buttonPanel = new JPanel(), BorderLayout.SOUTH);

  }
}

and build your solution around that. 并围绕此构建您的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM