在Java中使用GUI时遇到了麻烦。我想写一个程序,要求我在屏幕中央画一个星星,但在它绘制它之前我想让它问我有多想让星星拥有武器。我制作的这段代码只是在没有任何其他东西的情况下绘制一颗星(http://i.imgur.com/JSsfuyt.png)
所以我必须修改它(也许是一些自定义类型的Scanner询问我的武器数量),但我在GUI和Java上并不擅长。你能帮助我吗?提前谢谢。
import java.awt.BasicStroke;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Path2D;
public class App extends Frame
{
public static void main(String[] args)
{
new App();
}
public App()
{
setSize(540, 380);
setVisible(true);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke (new BasicStroke (15.0f));
Rectangle r = getBounds();
float width = 166;
float height = 166;
g2.translate( r.getWidth() / 2 - width/2, r.getHeight() / 2 - height/2);
Path2D star = new Path2D.Float ();
star.moveTo (width/5F, height-1);
star.lineTo (width/2F, 0);
star.lineTo (4*width/5F, height-1);
star.lineTo (0, 2*height/5F);
star.lineTo (width-1, 2*height/5F);
star.closePath ();
g2.draw (star);
g2.fill (star);
}
}
答案 0 :(得分:0)
你需要阅读布局管理器和文档监听器看看这段代码,它使用了一个空布局管理器,这是不推荐的,但在这里工作正常。为了从文本框中获取值,您需要将字段添加到drawpanel并从insertUpdate事件中设置它们
package star;
import java.awt.*;
import java.awt.geom.Path2D;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class StarApp {
public static void main(String[] args) {
new StarApp();
}
StarFrame sf = new StarFrame();
public StarApp() {
}
public class StarFrame extends JFrame implements DocumentListener {
StarDrawPanel drawpanel = new StarDrawPanel();
StarInputPanel inputpanel = new StarInputPanel();
public StarFrame () {
inputpanel.input.getDocument().addDocumentListener(this);
this.setLayout(null);
this.add(inputpanel);
this.add(drawpanel);
drawpanel.setSize(540, 360);
setSize(540, 380);
inputpanel.setSize(50,30);
setVisible(true);
}
public void insertUpdate(DocumentEvent arg0) {
drawpanel.repaint();
}
public void changedUpdate(DocumentEvent arg0) {
}
public void removeUpdate(DocumentEvent arg0) {
}
}
public class StarDrawPanel extends JPanel {
Random rand = new Random();
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke (new BasicStroke (15.0f));
Rectangle r = getBounds();
float width = 166;
float height = 166;
g2.translate( r.getWidth() / 2 - width/2, r.getHeight() / 2 - height/2);
Path2D star = new Path2D.Float ();
star.moveTo (width/5F, height-1);
star.lineTo (width/2F, 0);
star.lineTo (4*width/5F, height-1);
star.lineTo (0, 2*height/5F);
star.lineTo (width-1, 2*height/5F);
star.closePath ();
g2.draw (star);
float rc = rand.nextFloat();
float gc = rand.nextFloat();
float bc = rand.nextFloat();
Color randomColor = new Color(rc, gc, bc);
g2.setPaint(randomColor);
g2.fill (star);
}
}
public class StarInputPanel extends JPanel {
public JTextField input = new JTextField(4);
public StarInputPanel() {
this.add(input);
}
}
}