我正在尝试绘制图形,JButton单击时应显示图形。为了创建数据集,我正在获取一些值JTextField,然后创建一个图表并绘制它。我有两个问题:
这是我的程序:
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private ChartPanel chartPanel;
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
panel.setLayout(new MigLayout("", "[][grow]", "[][][][][]"));
JLabel lblA = new JLabel("a");
panel.add(lblA, "cell 0 2,alignx trailing");
textField = new JTextField();
panel.add(textField, "cell 1 2,growx");
textField.setColumns(10);
JButton btn = new JButton("Plot");
btn.addActionListener(new …Run Code Online (Sandbox Code Playgroud) 我只想在鼠标点击后绘制圆圈.由于paintComponent方法调用了自己,所以第一个圆绘制没有单击.
public class DrawPanel extends JPanel implements MouseListener {
private static final long serialVersionUID = 1L;
int x, y;
public DrawPanel() {
setBackground(Color.WHITE);
addMouseListener(this);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(x, y, 20, 20);
}
@Override
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
}
Run Code Online (Sandbox Code Playgroud)