gpt4 book ai didi

java - 观察者模式更新文本字段和条形图

转载 作者:行者123 更新时间:2023-12-01 11:41:58 27 4
gpt4 key购买 nike

所以我正在研究观察者模式分配。我有 2 个窗口,每个窗口有 4 个字段。在一个窗口中,您可以在 4 个不同的文本框中输入 double 值,它们会反射(reflect)在条形图中 4 个相应条形之一中。

我还可以通过按鼠标按钮来更改条形图中的条形,它会移动到我的指针所在的位置。现在,我也想更新文本字段,但我不知道该怎么做。似乎收到了发生更改的通知,但我不知道如何在该字段中设置适当的文本。酒吧框架已重新喷漆。我是否也对文本框架执行此操作?

这是迄今为止我的 3 个相关类的代码:

条形框架

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.*;

import javax.swing.*;
import javax.swing.event.*;

import java.util.*;

/**
A class that implements an Observer object that displays a barchart view of
a data model.
*/
public class BarFrame extends JFrame implements ChangeListener, MouseListener
{

private ArrayList<Double> a;
private DataModel dataModel;

private static final int ICON_WIDTH = 200;
private static final int ICON_HEIGHT = 200;
/**
Constructs a BarFrame object
@param dataModel the data that is displayed in the barchart
*/
public BarFrame(DataModel dataModel)
{
this.dataModel = dataModel;
a = dataModel.getData();

setLocation(0,200);
setLayout(new BorderLayout());

addMouseListener(this); // adds the mouse listener in to the bar frame

Icon barIcon = new Icon()

{
public int getIconWidth() { return ICON_WIDTH; }
public int getIconHeight() { return ICON_HEIGHT; }

public void paintIcon(Component c, Graphics g, int x, int y)
{
Graphics2D g2 = (Graphics2D) g;

g2.setColor(Color.red);

double max = (a.get(0)).doubleValue();

for (Double v : a)
{
double val = v.doubleValue();
if (val > max)
max = val;
}
double barHeight = getIconHeight() / a.size();

int i = 0;
for (Double v : a)
{
double value = v.doubleValue();

double barLength = getIconWidth() * value / max;
Rectangle2D.Double rectangle = new Rectangle2D.Double
(0, barHeight * i, barLength, barHeight);
i++;
g2.fill(rectangle);
}
}
};

add(new JLabel(barIcon));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}

/**
Called when the data in the model is changed.
@param e the event representing the change
*/
public void stateChanged(ChangeEvent e)
{
a = dataModel.getData();
// for(Double d: a){
// System.out.println(d);
// }
repaint();
}


@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub

double max = Collections.max(dataModel.getData());
double value = (double)e.getX() / (double)getWidth()* max;

if( 30 <= e.getY() && e.getY() < 80 ){
//first bar
dataModel.update(0, value);
}

if( 80 <= e.getY() && e.getY() < 130 ){
//second bar
dataModel.update(1, value);
}

if( 130 <= e.getY() && e.getY() < 180 ){
//third bar
dataModel.update(2, value);
}

if( 180 <= e.getY() && e.getY() < 230 ){
//fourth bar
dataModel.update(3, value);
}
}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

}

数据模型

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.event.*;

/**
A Subject class for the observer pattern.
*/
public class DataModel
{
ArrayList<Double> data;
ArrayList<ChangeListener> listeners;

/**
Constructs a DataModel object
@param d the data to model
*/
public DataModel(ArrayList<Double> d)
{
data = d;
listeners = new ArrayList<ChangeListener>();

}

/**
Constructs a DataModel object
@return the data in an ArrayList
*/
@SuppressWarnings("unchecked")
public ArrayList<Double> getData()
{
return (ArrayList<Double>) (data.clone());
}

/**
Attach a listener to the Model
@param c the listener
*/
public void attach(ChangeListener c)
{
listeners.add(c);
}

/**
Change the data in the model at a particular location
@param location the index of the field to change
@param value the new value
*/
public void update(int location, double value)
{
data.set(location, new Double(value));
// frame.fieldList[location].setText(Double.toString(value));
for (ChangeListener l : listeners)
{
// System.out.println("l = " + l);
l.stateChanged(new ChangeEvent(this));
}

}

}

文本框

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import java.util.ArrayList;

/**
A class for displaying the model as a column of textfields in a frame.
*/
public class TextFrame extends JFrame implements ChangeListener
{

DataModel dataModel;
JTextField[] fieldList;
private ArrayList<Double> a;
/**
Constructs a JFrame that contains the textfields containing the data
in the model.
@param d the model to display
*/
public TextFrame(DataModel d)
{
dataModel = d;

final Container contentPane = this.getContentPane();
setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

ArrayList<Double> a = dataModel.getData();
fieldList = new JTextField[a.size()];

// A listener for action events in the text fields
ActionListener l = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Figure out which field generated the event
JTextField c = (JTextField) e.getSource();
int i = 0;
int count = fieldList.length;
while (i < count && fieldList[i] != c)
i++;

String text = c.getText().trim();

try
{
double value = Double.parseDouble(text);
dataModel.update(i, value);
}
catch (Exception exc)
{
c.setText("Error. No update");
}
}
};

final int FIELD_WIDTH = 11;
for (int i = 0; i < a.size(); i++)
{
JTextField textField = new JTextField(a.get(i).toString(),FIELD_WIDTH);
textField.addActionListener(l);
add(textField);
fieldList[i] = textField;
}

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}


/**
Called when the data in the model is changed.
@param e the event representing the change
*/
public void stateChanged(ChangeEvent e)
{
a = dataModel.getData();
// for(Double d: a){
// System.out.println(d);
// }

}


}

一些注意事项:我知道如果您用最大值更改条形的值(其他条形发生变化),则会出现错误。那是我应该扩展的代码。我猜就是这样,这样它就可以用作引用点。我知道我可以通过使用适配器来摆脱不必要的鼠标监听器,但我的说明指出将它们实现为空。

如果有人想回答的话,还有一个额外的问题:有没有办法在我的鼠标按下时获得实际的 double ?它总是返回一个整数。

无论如何,很抱歉这篇文章很长。提前感谢您的帮助!

最佳答案

想通了!我在 TextFrame 的 stateChanged 方法中添加了以下内容:

   for(int i = 0; i < a.size(); i++){
fieldList[i].setText(Double.toString(Math.round(a.get(i) * 10) / 10.0)); // to get 1 decimal place accuracy
}

关于java - 观察者模式更新文本字段和条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29453018/

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