gpt4 book ai didi

java - 分割paintComponent方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:37 25 4
gpt4 key购买 nike

我是 GUI 新手,正在编写一个程序来在图表上显示 NameRecord 的多个条目。当我只需要放入一个条目时,我在paintComponent中启动了整个框架。

但是,现在我需要修改它,以便可以存储多个NameRecords条目,我决定使用ArrayList来存储。然后我希望能够搜索、清除这些条目。但我在paintComponent 中的内容太困惑了。

如何修改此方法,以便拥有单独的类来存储条目并执行其他方法?因为我无法在此类之外引用 g。

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);

w = getWidth();
h = getHeight();

//draw horizontal lines
g.drawLine(0, 20, w, 20);
g.drawLine(0, h - 20, w, h - 20);

//draw vertical lines
for (int i = 1; i < 12; i++) {
g.drawLine((w / 12) * i, 0, (w / 12) * i, h);
}
//draw lable of years
g.drawString(" 1900", 0, 13);
g.drawString(" 1900", 0, h - 7);

int year = 1900;
for (int i = 1; i < 12; i++) {
g.drawString(" " + Integer.toString(year + (i * 10)), (w / 12 * i), 13);
g.drawString(" " + Integer.toString(year + (i * 10)), (w / 12 * i), h - 7);
}

// draw line of rank
if (nameData != null) {
nameList.add(nameData);
for (int i = 0; i < 11; i++) {
g.drawLine((w / 12 * i), convertValue(nameData.getRank(i)),
(w / 12) * (i + 1), convertValue(nameData.getRank(i + 1)));
}

for (int i = 0; i < 12; i++) {
String label = " ";
label = (nameData.getName() + " " + nameData.getRank(i));
g.drawString(label, (w / 12 * i), convertValue(nameData.getRank(i)));
}
}
}

我还使用了另一个类来完成所有 GUI 显示(我不确定这是否是这样说的,但它调用了 actionPerformed 方法)。他们的联系让我有点困惑。我只是把它放在这里作为引用。

 @Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();

if (s.equalsIgnoreCase("graph")) {
doGraph();
} else if (s.equalsIgnoreCase("search")) {
findName(inputField.getText());
} else if (s.equalsIgnoreCase("clear all")) {
clear();
//– remove all names from the NameGraph

} else if (s.equalsIgnoreCase("clear one")) {

//remove the name that was added to the NameGraph earliest.
} else if (s.equalsIgnoreCase("quit")) {
setVisible(false);
dispose();
System.exit(0);
} else {
// This is the response to the Enter Key pressed in inputField.
doGraph();
}
}

最佳答案

How can I modify this method so that I have separate classes to store entries and perform other methods? Since I cannot refer to g outside of this class.

您将能够访问Graphics object g通过将其传递给方法或另一个类的方法:

//for example
class MyGraph{
public void draw(Graphics g){
//implements how the graph is drawn, for e.g:
//g.drawLine(x, y);
}
}

在显示绘图的面板类中:

class DisplayPanel extends JPanel{

private MyGraph;

public DisplayPanel(){
MyGraph graph = new MyGraph();
}

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
graph.draw(g); //let the objects draw themselves
}
}

关于java - 分割paintComponent方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49932471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com