程序运行,但没有显示任何内容?

时间:2015-01-09 02:40:11

标签: java

我刚刚回到Java编程和长话短说,我做了一个Applet而不知道那些只能在浏览器中运行,所以我试着改成代码所以我可以把它放在一个可运行的.Jar中,但当我运行我的代码它没有做任何事情。

public static void main(String args[])
{
    setBackground(Color.black); //Sets the background to black.
    Font myFont = new Font("Arial", Font.PLAIN, 14); //Makes "myFont" a font that is plain.
    setFont(myFont); //Sets the font to "myFont"..
}

private static void setFont(Font myFont) {


}

private static void setBackground(Color black) {

}

public void paint(java.awt.Graphics g) {
    g.setColor(Color.blue); //Sets anything in "paint" to be in blue.
    int xArray[] = {20, 110, 200, 200, 110, 20, 20}; //This line, and the line below are the cords for the bowtie.
    int yArray[] = {20, 45, 20, 100, 65, 100, 20};
    g.drawPolygon(xArray, yArray, 7); //Draws the bowtie.
    g.drawString("Bow ties are no longer cool.", 20, 150); //Writes the text.

} }

1 个答案:

答案 0 :(得分:3)

代码只执行你告诉它的事情:

  • 主要方法当然会运行。
  • 然后调用setFont,setBackground,这两种方法都没有做任何事情,因为你已经把它们写成什么都不做了
  • 然后主要方法和程序结束。
  • 如果paint(...)方法没有覆盖Swing组件的paint方法,那么它将无效。
  • 最好覆盖Swing组件的paintComponent方法,教程会告诉你所有这些。

我很惊讶您希望它能做得更多。如果您想要实际显示GUI,那么将大部分代码从静态领域中移出并进入类或实例领域,让代码扩展JPanel,覆盖其paintComponent,并将JPanel放在main方法的JFrame中。最重要的是,阅读教程,因为它们将向您展示最佳途径。您可以在此处找到Swing教程和其他Swing资源的链接:Swing Info

例如,

import java.awt.*;
import javax.swing.*;

public class SwingExample extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = 300;

   public SwingExample() {
      setBackground(Color.black); //Sets the background to black.
      Font myFont = new Font("Arial", Font.PLAIN, 14); //Makes "myFont" a font that is plain.
      setFont(myFont); //Sets the font to "myFont"..
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.blue); //Sets anything in "paint" to be in blue.
      int xArray[] = {20, 110, 200, 200, 110, 20, 20}; //This line, and the line below are the cords for the bowtie.
      int yArray[] = {20, 45, 20, 100, 65, 100, 20};
      g.drawPolygon(xArray, yArray, 7); //Draws the bowtie.
      g.drawString("Bow ties are no longer cool.", 20, 150); //Writes the text.
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      SwingExample mainPanel = new SwingExample();

      JFrame frame = new JFrame("SwingExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}