我使用以下函数画了一行:
public void paint(Graphics p) {
super.paint(p);
p.drawLine(600, 200, 580, 250);
}
我想知道有没有办法可以删除这一行?
那么是否可以在程序的main()
方法中调用此函数?
答案 0 :(得分:2)
您可以使用标记来了解该行是否正在显示。
正如我之前所说,您需要为JPanel
而不是JFrame
构建GUI。同样重写paintComponent
而不是paint
方法。
例如,当您单击JButton
时,以下程序会显示一行或隐藏它,根据您自己的条件将该逻辑调整到您自己的程序。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LineDrawer {
private JFrame frame;
private JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new LineDrawer()::createAndShowGui); //Put our program on the EDT
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
MyPane pane = new MyPane(); //Create an instance of our custom JPanel class
button = new JButton("Hide/Show");
button.addActionListener(e -> {
pane.setShowLine(!pane.isShowLine()); //Change the state of the flag to its inverse: true -> false / false -> true
});
frame.add(pane);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Our custom class that handles painting.
@SuppressWarnings("serial")
class MyPane extends JPanel {
private boolean showLine;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (showLine) { //If true, show line
g2d.draw(new Line2D.Double(50, 50, 100, 50));
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300); //For the size of our JPanel
}
public boolean isShowLine() {
return showLine;
}
public void setShowLine(boolean showLine) {
this.showLine = showLine;
this.repaint(); //Everytime we set a new state to showLine, repaint to make the changes visible
}
}
}
我现在不能发布GIF,但程序本身也可以。顺便说一句,上面的代码称为Minimal, Complete and Verifiable Example,在接下来的问题中,我们鼓励您发布一个代码,以便为您的问题获得更具体,更快,更好的答案。