我使用以下函数画了一条线:
public void paint(Graphics p) {
super.paint(p);
p.drawLine(600, 200, 580, 250);
}
我想知道有没有办法删除这一行?
那么是否可以在main()
程序的方法?
您可以使用标志来了解该行是否正在显示。
正如我之前所说,你需要构建你的 GUIJPanel
是而不是JFrame
s。也压倒一切paintComponent
并不是paint
method.
例如,以下程序在单击时显示一条线或隐藏它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,但程序本身可以运行。顺便说一句,上面的代码被称为最小、完整且可验证的示例 https://stackoverflow.com/help/mcve对于您的下一个问题,我们鼓励您发布一个问题,以便您的问题得到具体、更快、更好的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)