该程序要求用户输入圆的数据。包括:x 的位置、y 的位置以及圆的宽度和高度。
所以当我测试这个程序时,我输入位置及其大小;然后我按下了绘图按钮。圆圈没有出现。
这是我的代码!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Draw extends JFrame
{
private JButton draw;
private JTextField posOfX;
private JTextField posOfY;
private JTextField Jwidth;
private JTextField Jheight;
private ActionListener listener;
private JLabel JLx;
private JPanel drawingPanel;
private JLabel JLy;
private JLabel JLwidth;
private JLabel JLheight;
private JComponent component;
public int x =100 ;
public int y =100 ;
public int width = 100;
public int height = 100 ;
private JPanel panel;
public Draw()
{
listener = new actionPerform();
component = new drawCircle();
panel = new JPanel();
draw = new JButton ("Draw");
draw.addActionListener(listener);
posOfX = new JTextField( 15);
posOfY = new JTextField(15);
Jwidth = new JTextField(15);
Jheight = new JTextField(15);
JLx = new JLabel("X");
JLy = new JLabel("Y");
JLwidth = new JLabel("Width");
JLheight = new JLabel("Height");
panel.add(JLx);
panel.add(posOfX);
panel.add(JLy);
panel.add(posOfY);
panel.add(JLwidth);
panel.add(Jwidth);
panel.add(JLheight);
panel.add(Jheight);
panel.add(draw);
panel.add(component);
add(drawingPanel,BorderLayout.SOUTH);
add(panel,BorderLayout.NORTH);
}
class drawCircle extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawOval(x,y,width,height);
}
}
class actionPerform implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try{
if(e.getSource() == draw)
{
width = width + Integer.parseInt(Jwidth.getText());
height = height + Integer.parseInt(Jheight.getText());
x = Integer.parseInt(posOfX.getText()) + width;
y = Integer.parseInt(posOfY.getText())+ height;
Jwidth.setText("");
Jheight.setText("");
posOfX.setText("");
posOfY.setText("");
}
}
catch (Exception except)
{
Jwidth.setText("");
Jheight.setText("");
posOfX.setText("");
posOfY.setText("");
JOptionPane.showMessageDialog(null,"You should enter numbers only","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
import java.awt.*;
import javax.swing.*;
public class DrawViewer
{
public static void main(String []args)
{
Draw d = new Draw();
d.setVisible(true);
d.setTitle("Draw circle");
d.setSize(1000,1000);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
最佳答案
在没有布局管理器的情况下创建新的 JComponent
对象时,其首选大小的宽度最初为 0,高度为 0,因此它根本不可见。要解决此问题,您的 drawCircle
类应重写 getPreferredSize
方法,以便您添加它的组件知道其大小应该是多少。例如:
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
强烈建议您使用 layout manager但是,这样您就不会遇到各种问题,例如组件大小错误。
关于java - 我有一个项目要求我创建按钮,用户输入圆的半径和位置,然后用户单击按钮来绘制圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311673/