我刚刚回到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.
} }
答案 0 :(得分:3)
代码只执行你告诉它的事情:
paint(...)
方法没有覆盖Swing组件的paint方法,那么它将无效。我很惊讶您希望它能做得更多。如果您想要实际显示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();
}
});
}
}