I do new logic in the HorizontalListView class using the following:
private DataSetObserver mDataObserver = new DataSetObserver() {
#Override
public void onChanged() {
synchronized (HorizontalListView.this) {
mDataChanged = true;
int firstVisiblePos = HorizontalListView.this.getFirstVisiblePosition();
int lastVisiblePos = HorizontalListView.this.getLastVisiblePosition();
Log.i(mTag, "firstVisiblePosl " + firstVisiblePos+ " lastVisiblePos " + lastVisiblePos );
if (mAdapter.getCount() > lastVisiblePos) {
int sumTotal = 0;
for (int i = firstVisiblePos; i < mAdapter.getCount(); i++) {
View child = HorizontalListView.this.getChildAt(i);
if (child != null) {
sumTotal += child.getWidth();
}
}
int sumPartial = 0;
for (int i = lastVisiblePos; i < mAdapter.getCount(); i++) {
View child = HorizontalListView.this.getChildAt(i);
if (child != null) {
sumPartial += child.getWidth();
}
}
Log.i(mTag, "sumTotal " + sumTotal+ " sumPartial " + sumPartial);
mScroller.startScroll(sumTotal, 0, sumPartial, 0);
}
}
Log.i(mTag, " " + mCurrentX + "mNextX " + mNextX);
invalidate();
requestLayout();
}
but this has no effect: I want to scroll to left up to last item at mAdapter is visible.
Related
I don't know if I'm using the correct way of filtering a barchart, or even if my code is properly written.
But I have problem, when I open my dashboard, I have 3 charts, one of the piecharts can filter the barchart, and depending on which was selected, the barchart only shows the piechart selected, otherwise shows all.
My problem is when I filter those, I'm getting the correct filter, but I can't get the labels to appear, they just appear when I got only one, for example if I have 1Yellow, 15 Reds, its only a bar to show, but it only shows the label for the yellow one, but if yellow2 and 15 reds, it doesn't show any of them.
It should be a easy fix, I just can't see where is the error.
ArrayList<Integer> colors_to_add_type = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MINOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MEDIUM = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MAJOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_OTHER = new ArrayList<>();
Iterator<String> defects_colors_keys;
defects_colors_keys = colors_type.keys();
while (defects_colors_keys.hasNext()){
String key = defects_colors_keys.next();
Log.e("COLOR_KEY", "onResponse: " + key );
int to_add = Color.parseColor(colors_type.getString(key));
int to_add_MINOR = Color.parseColor("#00FF00");
int to_add_MEDIUM = Color.parseColor("#FFFF00");
int to_add_MAJOR = Color.parseColor("#FF0000");
int to_add_OTHER = Color.parseColor("#800080");
Log.e("COLOR_NAME", "onResponse: " + colors_type.getString(key));
colors_to_add_type.add(to_add);
colors_to_add_type_MAJOR.add(to_add_MAJOR);
colors_to_add_type_MEDIUM.add(to_add_MEDIUM);
colors_to_add_type_MINOR.add(to_add_MINOR);
colors_to_add_type_OTHER.add(to_add_OTHER);
}
List<LegendEntry> legends_type = new ArrayList<>();
List<LegendEntry> legends_type_MINOR = new ArrayList<>();
List<LegendEntry> legends_type_MEDIUM = new ArrayList<>();
List<LegendEntry> legends_type_MAJOR = new ArrayList<>();
List<LegendEntry> legends_type_OTHER = new ArrayList<>();
type_of_defects = by_type.keys();
int c = 0;
if(!map_defects_by_type_count.isEmpty()){
map_defects_by_type_count.clear();
}
Log.e("DEFECTS", defects_list.toString());
Log.e("DEFECTS",String.valueOf(defects_list.size()));
while(type_of_defects.hasNext()) {
String key = type_of_defects.next();
Log.e("DEFECTS_type", key.toString());
map_defects_by_type_count.put(key, by_type.getInt(key));
map_get_defect_type.put(c, key);
LegendEntry legendEntry = new LegendEntry();
legendEntry.label = key;
legendEntry.formColor = colors_to_add_type.get(c);
legends_type.add(legendEntry);
arr_by_type.add(new BarEntry((float)c + 1, (int)by_type.getInt(key), (String)key));
c++;
for (int i = 0; i < defects_list.size(); i++){
if (defects_list.get(i).getStringProperty("defect").equals(key)){
if (defects_list.get(i).getStringProperty("criticality").equals("MAJOR")){
arr_by_type_MAJOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MAJOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MEDIUM")){
arr_by_type_MEDIUM.add(new BarEntry((float)c +1 , (int)by_type.getInt(key), (String)key));
legends_type_MEDIUM.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MINOR")){
arr_by_type_MINOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MINOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("OTHER")){
arr_by_type_OTHER.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_OTHER.add(legendEntry);
break;
}
}
}
}
TOTAL_DEFECTS = TOTAL_BY_CRIT;
if(TOTAL_BY_CRIT != 0){
if(MAJOR != 0){
major_percent = (float) MAJOR / TOTAL_BY_CRIT;
}
if(MEDIUM != 0){
medium_percent = (float) MEDIUM / TOTAL_BY_CRIT;
}
if(MINOR != 0){
minor_percent = (float) MINOR / TOTAL_BY_CRIT;
}
if(OTHER != 0){
other_percent = (float) OTHER / TOTAL_BY_CRIT;
}
}
TOTAL_SOURCE = TOTAL_H_M;
if(TOTAL_H_M != 0){
if(HUMAN != 0){
human_percent = (float) HUMAN / TOTAL_H_M;
}
if(MACHINE != 0){
machine_percent = (float) MACHINE / TOTAL_H_M;
}
}
arr_by_defect.add(new PieEntry(MAJOR, "MAJOR"));
arr_by_defect.add(new PieEntry(MEDIUM, "MEDIUM"));
arr_by_defect.add(new PieEntry(MINOR, "MINOR"));
arr_by_defect.add(new PieEntry(OTHER, "OTHER"));
arr_by_source.add(new PieEntry(HUMAN, "HUMAN"));
arr_by_source.add(new PieEntry(MACHINE, "MACHINE"));
dataSet_by_defect = new PieDataSet(arr_by_defect, "");
dataSet_by_source = new PieDataSet(arr_by_source, "");
dataSet_by_type = new BarDataSet(arr_by_type, "");
dataSet_by_type_MAJOR = new BarDataSet(arr_by_type_MAJOR, "");
dataSet_by_type_MEDIUM = new BarDataSet(arr_by_type_MEDIUM, "");
dataSet_by_type_MINOR = new BarDataSet(arr_by_type_MINOR, "");
dataSet_by_type_OTHER = new BarDataSet(arr_by_type_OTHER, "");
//GET THE COLORS
String colorMajor = colors.getString("MAJOR");
String colorMedium = colors.getString("MEDIUM");
String colorMinor = colors.getString("MINOR");
String colorOther = colors.getString("OTHER");
String colorHuman = human_machine_colors.getString("human");
String colorMachine = human_machine_colors.getString("machine");
final int[] sliceColors = {Color.parseColor(colorMajor), Color.parseColor(colorMedium), Color.parseColor(colorMinor), Color.parseColor(colorOther)};
ArrayList<Integer> colorsSet = new ArrayList<>();
for (int color : sliceColors){
colorsSet.add(color);
}
Log.e("COLORS_TO ADD", "MAJOR" + colorMajor);
Log.e("COLORS_TO ADD", "MEDIUM" + colorMedium);
Log.e("COLORS_TO ADD", "MINOR" + colorMinor);
Log.e("COLORS_TO ADD", "OTHER" + colorOther);
dataSet_by_defect.setColors(colorsSet);
final int[] sliceColors_hm = {Color.parseColor(colorHuman), Color.parseColor(colorMachine)};
ArrayList<Integer> colorsSet_hm = new ArrayList<>();
for (int color : sliceColors_hm){
colorsSet_hm.add(color);
}
dataSet_by_source.setColors(colorsSet_hm);
dataSet_by_type.setColors(colors_to_add_type);
dataSet_by_type_MINOR.setColors(colors_to_add_type_MINOR);
dataSet_by_type_MEDIUM.setColors(colors_to_add_type_MEDIUM);
dataSet_by_type_MAJOR.setColors(colors_to_add_type_MAJOR);
dataSet_by_type_OTHER.setColors(colors_to_add_type_OTHER);
dataSet_by_type.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MINOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MEDIUM.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MAJOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_OTHER.setAxisDependency(YAxis.AxisDependency.RIGHT);
final PieData data_defect = new PieData(dataSet_by_defect);
final PieData data_source = new PieData(dataSet_by_source);
final BarData data_type = new BarData(dataSet_by_type);
final BarData data_type_MINOR = new BarData(dataSet_by_type_MINOR);
final BarData data_type_MEDIUM = new BarData(dataSet_by_type_MEDIUM);
final BarData data_type_MAJOR = new BarData(dataSet_by_type_MAJOR);
final BarData data_type_OTHER = new BarData(dataSet_by_type_OTHER);
data_type.setDrawValues(true);
data_type_MAJOR.setDrawValues(true);
data_type_MEDIUM.setDrawValues(true);
data_type_MINOR.setDrawValues(true);
data_type_OTHER.setDrawValues(true);
data_defect.setDrawValues(false);
data_source.setDrawValues(false);
//data_type.setBarWidth(.75f);
piechart_defects.setDrawHoleEnabled(true);
piechart_defects.setHoleColor(Color.TRANSPARENT);
piechart_defects.setDrawEntryLabels(false);
piechart_defects.setDrawMarkers(false);
piechart_defects.setCenterText(String.valueOf(TOTAL_DEFECTS) + " TOTAL");
piechart_defects.setCenterTextSize(10);
piechart_defects.getDescription().setEnabled(false);
Legend l_defect = piechart_defects.getLegend();
l_defect.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_defect.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_defect.setOrientation(Legend.LegendOrientation.VERTICAL);
l_defect.setDrawInside(false);
l_defect.setEnabled(true);
l_defect.setFormSize(4f);
l_defect.setTextColor(Color.WHITE);
l_defect.setTextSize(.5f);
piechart_source.setDrawHoleEnabled(true);
piechart_source.setDrawEntryLabels(false);
piechart_source.setHoleColor(Color.TRANSPARENT);
piechart_source.setDrawMarkers(false);
piechart_source.setCenterText(String.valueOf(TOTAL_SOURCE) + " TOTAL");
piechart_source.setCenterTextSize(10);
piechart_source.getDescription().setEnabled(false);
piechart_source.setTransparentCircleRadius(10f);
Legend l_source = piechart_source.getLegend();
l_source.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_source.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_source.setOrientation(Legend.LegendOrientation.VERTICAL);
l_source.setDrawInside(false);
l_source.setEnabled(true);
l_source.setFormSize(4f);
l_source.setTextColor(Color.WHITE);
l_source.setTextSize(.5f);
dataSet_by_type.setValueTextColor(Color.WHITE);
dataSet_by_type_MAJOR.setValueTextColor(Color.WHITE);
dataSet_by_type_MEDIUM.setValueTextColor(Color.WHITE);
dataSet_by_type_MINOR.setValueTextColor(Color.WHITE);
dataSet_by_type_OTHER.setValueTextColor(Color.WHITE);
dataSet_by_type.setValueTextSize(7f);
dataSet_by_type_MINOR.setValueTextSize(7f);
dataSet_by_type_MEDIUM.setValueTextSize(7f);
dataSet_by_type_MAJOR.setValueTextSize(7f);
dataSet_by_type_OTHER.setValueTextSize(7f);
data_type.setBarWidth(.5f);
data_type.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MAJOR = barchart_type.getLegend();
l_type_MAJOR.setCustom(legends_type_MAJOR);
l_type_MAJOR.setWordWrapEnabled(true);
l_type_MAJOR.setDrawInside(true);
data_type_MAJOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_MAJOR.setBarWidth(.5f);
Legend l_type_OTHER = barchart_type.getLegend();
l_type_OTHER.setCustom(legends_type_OTHER);
l_type_OTHER.setWordWrapEnabled(true);
l_type_OTHER.setDrawInside(true);
data_type_OTHER.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_OTHER.setBarWidth(.5f);
Legend l_type_MINOR = barchart_type.getLegend();
l_type_MINOR.setCustom(legends_type_MINOR);
l_type_MINOR.setWordWrapEnabled(true);
l_type_MINOR.setDrawInside(true);
data_type_MINOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MEDIUM = barchart_type.getLegend();
l_type_MEDIUM.setCustom(legends_type_MEDIUM);
l_type_MEDIUM.setWordWrapEnabled(true);
l_type_MEDIUM.setDrawInside(true);
data_type_MEDIUM.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
barchart_type.setRenderer(new MyRenderer(barchart_type, barchart_type.getAnimator(), barchart_type.getViewPortHandler()));
Legend l_type = barchart_type.getLegend();
l_type.setCustom(legends_type);
l_type.setWordWrapEnabled(true);
l_type.setDrawInside(true);
piechart_defects.setData(data_defect);
piechart_defects.invalidate();
piechart_source.setData(data_source);
piechart_source.invalidate();
barchart_type.getAxisLeft().setEnabled(false);
barchart_type.setScaleEnabled(false);
barchart_type.getAxisRight().setEnabled(false);
barchart_type.getAxisRight().setDrawGridLines(false);
barchart_type.getXAxis().setDrawLabels(false);
barchart_type.getXAxis().setDrawGridLines(false);
barchart_type.getDescription().setEnabled(false);
barchart_type.getLegend().setEnabled(false);
barchart_type.setBorderColor(Color.BLACK);
barchart_type.setDrawBorders(false);
barchart_type.setData(data_type);
barchart_type.setMinimumHeight(arr_by_type.size()*250);
barchart_type.invalidate();
Log.e("INFO BAR", data_type.toString());
piechart_defects.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
String value = String.valueOf((int)h.getY());
String toShow = "";
if(h.getX() == 0){
toShow = " MAJOR \n" + value;
chartSelectedDefect = "MAJOR";
barchart_type.setData(data_type_MAJOR);
}else if(h.getX() == 1){
toShow = " MEDIUM \n" + value;
chartSelectedDefect = "MEDIUM";
barchart_type.setData(data_type_MEDIUM);
barchart_type.invalidate();
}else if(h.getX() == 2){
toShow = " MINOR \n" + value ;
chartSelectedDefect = "MINOR";
barchart_type.setData(data_type_MINOR);
}else if(h.getX() == 3){
toShow = " OTHER \n" + value;
chartSelectedDefect = "OTHER";
barchart_type.setData(data_type_OTHER);
How it appears when I show all:
So I managed to make Jtable working one way, from table1 to table2. but I don't really know how to make it work both ways(from table2 to table1). I was trying putting transferhandler on both Jtables, but I guess that they interfere with each other. So I'm pretty much stuck. Can someone explain how should I do it?
Here is the implementation (when I'm trying to do the same with the second Jtable it is not working):
table1.setDragEnabled(true);
table2.setTransferHandler(new TransferHandler() {
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
int row2 = table1.getSelectedRow();
int rows[] = table1.getSelectedRows();
if (rows.length > 1){
Object strings2[][] = new String[rows.length][2];
for (int i=0; i<rows.length; i++) {
for (int j = 0; j < 2; j++)
strings2[i][j] = table1.getValueAt(rows[i], j);
}
String pathToCopy, pathToPaste;
for (int k=0; k<strings2.length; k++) {
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings2[k][0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings2[k][0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings2[k][0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings2[k][0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
}
return true;
}
else {
if (row2 != -1) {
for (int i = 0; i < 2; i++)
strings[i] = table1.getValueAt(row2, i);
}
String pathToCopy, pathToPaste;
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings[0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings[0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings[0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings[0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
return true;
}
}
});
Every time a new swing windows opens in code that is executed in a for loop.
I have some code that is runned in a for loop.
The for loop gives every time a new value to my multidimensional array.
But, every time my for loop creates open's a new windows but does not close the old window.
How can I solve this issues? I want to close the old windows and refresh my window with the new actual values or that only one Windows is opened and that the new values of the for loop refreshes the values inside the table based on the multidimensional array names data.
Because now more than 200 (every second a new windows is opened) windows are opened and after 1 minute I don’t see new values appearing on my window and the computer freezes.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.Timer;
public class UAppWin {
private static final int Status_COL = 1;
String[][] data = new String[3][3];
int dptr;
String[] cols = { "Feature", "Status", "Value" };
public UAppWin(String label, int nphases) {
System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
}
void newCycle(int phasenr) {
System.out.println("UApp =============================");
dptr = 0;
}
void addEntry(int index, double tim, String label, int status, double dval) {
System.out.println("Uapp [" + index + "] " + label + "(" + status + ") " + dval);
data[dptr][0] = label;
data[dptr][1] = "" + status;
data[dptr][2] = "" + dval;
dptr++;
}
void addMessage(String msg) {
System.out.println("Uapp alert: " + msg);
// rode balk met bericht
}
void deleteMessage() {
}
void endCycle() {
System.out.println("UApp =============================");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
}
});
}
private JTable getTable() {
DefaultTableModel model = new DefaultTableModel(data, cols);
return new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(300, 150);
}
};
}
private static JTable getNewRenderedTable(final JTable table) {
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
String Status = (String) table.getModel().getValueAt(row, Status_COL);
if ("0".equals(Status)) {
setBackground(Color.GREEN);
setForeground(Color.BLACK);
} else if ("2".equals(Status)) {
setBackground(Color.RED);
setForeground(Color.BLACK);
} else {
setBackground(Color.YELLOW);
setForeground(Color.BLACK);
}
return this;
}
});
return table;
}
}
The second part of the code edited:
public class HmOpIntf {
static final String DFLT_IP_ADDR = "127.0.0.1";
static final int DFLT_IP_PORT = 9502;
static final int DFLT_MB_UNIT = 1;
static final int DFLT_POLL_TM = 2;
public static ModbusClient connectPLC(String ipAddr, int port, int unitNr)
{
ModbusClient mc = null;
System.out.println("Connecting to " + ipAddr + " port " + port + " unit " + unitNr);
try {
mc = new ModbusClient(ipAddr, port);
mc.Connect();
mc.setUnitIdentifier((byte)unitNr);
mc.WriteSingleCoil(0, true);
} catch (Exception e) {
System.err.println("*** connectPLC: exception caught");
return null;
}
System.out.println("Connected!");
return mc;
}
public static void disconnectPLC(ModbusClient mc)
{
mc = null;
}
public static String MyConvertRegistersToString(int[] regs, int startIx, int len) {
char[] ca = new char[len];
for (int i = 0; i < len; i++) {
ca[i] = (char) regs[startIx + i];
}
return new String(ca);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ModbusClient mc = null;
String ipAddr = DFLT_IP_ADDR;
int ipPort = DFLT_IP_PORT;
int mbUnit = DFLT_MB_UNIT;
int pollTime = DFLT_POLL_TM;
int tlBase = 2000; /* Offset in PLC's holding registry */
int tlBlocksz = 84;
String[] tlLabel = {"T4 mould", "T injection valve"}; /* Default */
int trafLightNum = tlLabel.length;
String[] colors = { "green", "yellow", "red" };
int status;
// Notifications.infoBox("Hello world!", "Welcome message");
if (args != null && args.length > 0) {
if (args.length < 4) {
System.err.println("*** Error (" + args.length +"): arguments are: ip-addr port unit polltime label-1 ...");
System.exit(1);
}
ipAddr = args[0];
ipPort = Integer.parseInt(args[1]);
mbUnit = Integer.parseInt(args[2]);
pollTime = Integer.parseInt(args[3]);
}
if (args.length > 4) {
trafLightNum = args.length - 4;
tlLabel = new String[trafLightNum];
for (int i = 0; i < trafLightNum; i++) {
tlLabel[i] = args[i + 4];
}
}
// Scope sc = new Scope();
// sc.runScope();
if ((mc = connectPLC(ipAddr, ipPort, mbUnit)) == null) {
System.out.println("*** Failed to connect to PLC");
System.exit(1);
}
TrafficLight tlLast = null;
int[] values = new int[tlBlocksz];
TrafficLight[] tl = new TrafficLight[trafLightNum];
Scope[] sc = new Scope[trafLightNum];
Notifications nots = new Notifications(trafLightNum);
int locX, locY;
for (int i = 0; i < tl.length; i++) {
tl[i] = new TrafficLight();
tl[i].setLbl(tlLabel[i]);
tl[i].setVisible(true);
if (tlLast != null) {
locX = tlLast.getLocation().x;
locY = tlLast.getLocation().y + tlLast.getHeight();
} else {
locX = tl[i].getLocation().x;
locY = tl[i].getLocation().y;
}
tl[i].setLocation(locX, locY);
sc[i] = new Scope(tlLabel[i], locX + tl[i].getWidth(), locY, 320, 290 /* tl[i].getHeight()-80 */ );
sc[i].setGrid(10, 5);
tlLast = tl[i];
}
UAppWin uw = new UAppWin("RTM Facility", 5);
int phase = 1;
// tl2.setVisible(true); tl2.setLocation(tl.getWidth(), 0);
try {
double t = 0.0;
int[] dreg = new int[2];
for (;;) {
uw.newCycle(phase);
for (int i = 0; i < tl.length; i++) {
values = mc.ReadHoldingRegisters(tlBase + i * tlBlocksz, values.length);
status = values[0];
if (status >= 0 && status < colors.length) {
// System.out.println(i + ": " + colors[status]);
if (status == 0) tl[i].greenOn();
else if (status == 1) tl[i].yellowOn();
else tl[i].redOn();
}
else
System.out.println("Status value " + i + " out of range: " + status);
dreg[0] = values[1]; dreg[1] = values[2];
double dval = (double) ModbusClient.ConvertRegistersToFloat(dreg);
sc[i].addValue(t, dval);
sc[i].drawSignal();
// w.addEntry(int i, float t, String label, int status (o = groen, 1 = yellow, 2 = red), float dval);
uw.addEntry(i, t, tlLabel[i], status, dval);
int msglen = values[3];
if (msglen > 0) {
String msg = MyConvertRegistersToString(values, 4, msglen);
System.out.println("DEBUG: received message for " + tlLabel[i] + ": " + msg);
nots.notify(i, msg);
uw.addMessage(msg);
}
else {
nots.notify(i, null);
uw.deleteMessage();
}
// System.out.println("Received for set " + i + ": status=" + status + " dval=" + dval + " msglen=" + msglen);
}
uw.endCycle();
t += 1.0;
Thread.sleep(pollTime * 500);
}
} catch (Exception e) {
System.out.println("*** Failed to communicate with PLC - exit");
System.exit(1);
}
try {
mc.Disconnect();
} catch (IOException e) {
System.out.println("*** Failed to disconnect from PLC");
}
}
}
The UappWin seems to be tied to a window. So when you create it, also create a JFrame. Then nothing else would need to change except the run method and declaring the JFrame.
public class UAppWin {
private JFrame frame;
public UAppWin(String label, int nphases) {
//System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
JLabel label = new JLabel("UApp \"" + label + "\" (" + nphases + " phases)");
frame = new JFrame("title");
frame.add(label);
frame.setVisible(true);
}
Then when you create the window.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
frame.setContentPane( new JScrollPane( getNewRenderedTable( getTable() ) );
frame.setVisible(true);
}
});
This is my BFS algorithm code.
I can calculate the shortest path distance, but somehow I am not able to display the shortest path.
Like for example, I calculated the shortest path from source to destination is 2. But i would like to also display the pathway. (PlaceA -> PlaceB -> PlaceC) for example.
May i know how do i display out the shortest path out using Java?
Please do help me! Thank you!
public static void main(String[] args) {
// TODO Auto-generated method stub
chooseNumOfVertices();
chooseNumOfEdges();
generateGraph();
in.close();
}
private static void generateGraph() {
int source = 0;
int destination = 0;
int edge = chooseEdge;
// TODO Auto-generated method stub
ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < limit; i++) {
LinkedList<Integer> vertex = new LinkedList<Integer>();
vertex.add(i);
graph.add(vertex);
}
while (chooseEdge > 0) {
// Randomize the value
int value = new Random().nextInt(cityMapping.size());
int value2 = new Random().nextInt(cityMapping.size());
//
if (value != value2 && !graph.get(value).contains(value2) && !graph.get(value2).contains(value)) {
graph.get(value).add(value2);
graph.get(value2).add(value);
chooseEdge--;
}
}
// Printing out the Nodes
for (int i = 0; i < graph.size(); i++) {
// Return each LinkedList nodes
// System.out.println(graph.get(i));
for (int j = 0; j < graph.get(i).size(); j++) {
// Return each individual nodes inside LinkedList
for (Entry<Integer, String> entry : cityMapping.entrySet()) {
if (entry.getKey() == graph.get(i).get(j)) {
//System.out.print(graph.get(i).get(j) + "-> ");
System.out.print(graph.get(i).get(j) + ". " + entry.getValue() + " -> ");
}
}
}
System.out.println();
}
do {
for (
int i = 0; i < limit; i++) {
int[] newArray = new int[limit];
distance.add(newArray);
predecessor.add(newArray);
}
long time = System.nanoTime();
System.out.println("Searching BFS");
System.out.println("--------------------------------------------");
for (int i = 0; i < limit; i++) {
BFS(graph, i);
}
long CPUTime = (System.nanoTime() - time);
System.out.println("CPU Time for BFS for " + limit + "vertices and " + edge + "edges (in ns): " + CPUTime);
System.out.print("Enter -1 to exit! Enter source vertex (between 0 to " + (limit - 1) + ") : ");
source = in.nextInt();
if (source == -1) {
System.out.print("System terminating...");
break;
}
System.out.print("Enter destination vertex (between 0 to " + (limit - 1) + ") : ");
destination = in.nextInt();
System.out.println("Distance from " + source + " to " + destination + " is: " +
getDistance(source, destination));
System.out.println("The Predecessor of the path from " + source + " to " + destination + " is: "
+ getPredecessor(source, destination));
} while (source != -1);
}
private static void BFS(ArrayList<LinkedList<Integer>> graph, int i) {
// TODO Auto-generated method stub
boolean[] mark = new boolean[graph.size()];
Queue<Integer> L = new ArrayBlockingQueue<Integer>(graph.size()); //Queue
L.add(i);
mark[i] = true;
Arrays.fill(predecessor.get(i), -1);
Arrays.fill(distance.get(i), -1);
distance.get(i)[i] = 0;
while (!L.isEmpty()) {
int vertex = L.remove();
for (int i1 = 0; i1 < graph.get(vertex).size(); i1++) {
int v = graph.get(vertex).get(i1);
if (!mark[v]) {
mark[v] = true;
predecessor.get(i)[v] = vertex;
L.add(v);
distance.get(i)[v] = distance.get(i)[predecessor.get(i)[v]] + 1;
}
}
}
}
public static int getDistance(int start, int end) {
return (distance.get(start)[end]);
}
public static int getPredecessor(int start, int end) {
return (predecessor.get(start)[end]);
}
private static void chooseNumOfEdges() {
System.out.println("Please input the number of Edges:");
chooseEdge = in.nextInt();
}
// Number of Vertices
private static void chooseNumOfVertices() {
in = new Scanner(System.in);
System.out.println("Please input the number of Vertices:");
limit = in.nextInt();
// Read CSV
List<String[]> content = readCsvFile();
// Map each number to a city name
cityMapping = new HashMap<>();
for (int i = 0; i < limit; i++) {
cityMapping.put(i, content.get(i)[0]);
}
// System.out.println(cityMapping);
}
// Read CSV file
public static List<String[]> readCsvFile() {
String csvFile = "./Lab 4/country.csv";
BufferedReader br = null;
ArrayList<String> names = new ArrayList<String>();
List<String[]> content = new ArrayList<>();
String cvsSplitBy = ",";
try {
String line = "";
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
content.add(line.split(cvsSplitBy));
}
} catch (Exception e) {
e.printStackTrace();
}
Random r = new Random();
Collections.shuffle(content);
return content;
}
}
I am trying to detect faces and crop the face part in rectangular Image. I have done the face detection Part, but still not finding any help about how to crop the face part. Please have a look on my code..!
public class FaceDetect extends Activity {
private MyImageView mIV;
private Bitmap mFaceBitmap;
private int mFaceWidth = 200;
private int mFaceHeight = 200;
int cropXinit = 0;
int cropYint = 0;
int cropXend = 0;
int cropYend = 0;
Bitmap cropedBitmap;
Bitmap b;
private static final int MAX_FACES = 1;
private static String TAG = "FaceDetect";
private static boolean DEBUG = false;
protected static final int GUIUPDATE_SETFACE = 999;
protected Handler mHandler = new Handler() {
// #Override
public void handleMessage(Message msg) {
mIV.invalidate();
super.handleMessage(msg);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIV = new MyImageView(this);
setContentView(mIV, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
// load the photo
b = ChooseActivity.bitmap;
mFaceBitmap = b.copy(Bitmap.Config.RGB_565, true);
b.recycle();
mFaceWidth = mFaceBitmap.getWidth();
mFaceHeight = mFaceBitmap.getHeight();
mIV.setImageBitmap(mFaceBitmap);
mIV.invalidate();
setFace();
}
public void setFace() {
FaceDetector fd;
FaceDetector.Face[] faces = new FaceDetector.Face[MAX_FACES];
PointF eyescenter = new PointF();
float eyesdist = 0.0f;
int[] fpx = null;
int[] fpy = null;
int count = 0;
try {
fd = new FaceDetector(mFaceWidth, mFaceHeight, MAX_FACES);
count = fd.findFaces(mFaceBitmap, faces);
} catch (Exception e) {
Log.e(TAG, "setFace(): " + e.toString());
return;
}
// check if we detect any faces
if (count > 0) {
fpx = new int[count * 2];
fpy = new int[count * 2];
for (int i = 0; i < count; i++) {
try {
faces[i].getMidPoint(eyescenter);
eyesdist = faces[i].eyesDistance();
// set up left eye location
fpx[2 * i] = (int) (eyescenter.x - eyesdist / 2);
fpy[2 * i] = (int) eyescenter.y;
// set up right eye location
fpx[2 * i + 1] = (int) (eyescenter.x + eyesdist / 2);
fpy[2 * i + 1] = (int) eyescenter.y;
if (DEBUG)
Log.e(TAG,
"setFace(): face "
+ i
+ ": confidence = "
+ faces[i].confidence()
+ ", eyes distance = "
+ faces[i].eyesDistance()
+ ", pose = ("
+ faces[i]
.pose(FaceDetector.Face.EULER_X)
+ ","
+ faces[i]
.pose(FaceDetector.Face.EULER_Y)
+ ","
+ faces[i]
.pose(FaceDetector.Face.EULER_Z)
+ ")" + ", eyes midpoint = ("
+ eyescenter.x + "," + eyescenter.y
+ ")");
} catch (Exception e) {
Log.e(TAG, "setFace(): face " + i + ": " + e.toString());
}
}
}
mIV.setDisplayPoints(fpx, fpy, count * 2, 1);
// if(eyescenter.x -eyesdist >= 0)
// {
// cropXinit = (int) (eyescenter.x -eyesdist) ;
// }
// else
// {
// cropXinit = 0;
// }
// if(eyescenter.x +eyesdist <= mFaceWidth)
// {
// cropXend = (int) (eyescenter.x +eyesdist) ;
// }
// else
// {
// cropXend = mFaceWidth;
// }
// if(eyescenter.y +eyesdist*2 <= mFaceHeight)
// {
// cropYend = (int) (eyescenter.y +eyesdist*2) ;
// }
// else
// {
// cropYend = mFaceHeight;
// }
// if(eyescenter.y -eyesdist >= 0)
// {
// cropYint = (int) (eyescenter.y -eyesdist) ;
// }
// else
// {
// cropYint = 0;
// }
// mIV.setImageBitmap(Bitmap.createBitmap(mFaceBitmap,cropXinit,cropYint,cropXend,cropYend));
}
}
createBitmap(Bitmap source, int x, int y, int width, int height) receives a start X and start Y, and a width and height value, not an end X and end Y. If you change your commented-out code to this it should work:
mIV.setImageBitmap(Bitmap.createBitmap(mFaceBitmap,cropXinit,cropYint,cropXend-cropXinit,cropYend-cropYinit));