Plotting BarGraph according to month days dynamically using java - java

i've created a BarChart using jfreechart in java. The bar is plotted according to the days in a month. for example this month March contains 31 days, so there will be 31 bars . The problem is that when i click the next button the month changes to April which contains 30 days, ie 30 bars. How can we change the BarChart according to the days in a month on button click.
Can anyone please tell me how to do that.

You need to update your dataset with each change. I've added an updateDataset() method and called it in several key places.
private void updateDataset() {
dataset.clear();
for (int i = 1; i <= finalday; i++) {
dataset.setValue(i, "Marks", "" + i);
}
Notes:
Do not use absolute layout; let the layout do its work.
Do not do date arithmetic yourself; use Calendar, for example.
Do not call overridable methods in the constructor.
Do re-factor your code to limit the number and scope of variables.
Do use meaningful names, especially for instance variables.
SSCCE, incompletely revised:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarGraph {
public int count = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0;
public int contstatus = 2;
public int date, year, mon, fn, show = 0, finalday, leapcn = 0, task = 0;
String startdte, enddte, monthweek, leavedates = "", nneed = "", year4enab, month4enab, days;
ChartFrame frame;
public static int st = 0;
JButton left = new JButton("<");
JButton right = new JButton(">");
JComboBox month = new JComboBox();
JSpinner yearspin = new javax.swing.JSpinner();
JLabel monthLabel = new javax.swing.JLabel();
JLabel yearLabel = new javax.swing.JLabel();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
BarGraph() {
task = 1;
Calendar cal;
left.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
left.setRequestFocusEnabled(false);
left.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
leftActionPerformed(evt);
}
});
right.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
right.setRequestFocusEnabled(false);
right.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
rightActionPerformed(evt);
}
});
month.setMaximumRowCount(12);
month.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}));
month.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
month.addItemListener(new java.awt.event.ItemListener() {
#Override
public void itemStateChanged(java.awt.event.ItemEvent evt) {
monthItemStateChanged(evt);
}
});
yearspin.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
yearspin.setValue(year);
yearspin.addChangeListener(new javax.swing.event.ChangeListener() {
#Override
public void stateChanged(javax.swing.event.ChangeEvent evt) {
yearspinStateChanged(evt);
}
});
monthLabel.setBackground(new java.awt.Color(255, 255, 255));
monthLabel.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
monthLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
monthLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, java.awt.Color.black, null, null));
monthLabel.setOpaque(true);
monthLabel.setText("SEPTEMBER");
yearLabel.setBackground(new java.awt.Color(255, 255, 255));
yearLabel.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
yearLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
yearLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, java.awt.Color.black, null, null));
yearLabel.setOpaque(true);
yearLabel.setText("2013");
cal = new GregorianCalendar();
year = cal.get(Calendar.YEAR);
mon = cal.get(Calendar.MONTH);
date = cal.get(Calendar.DATE);
yearspin.setValue(year);
month.setSelectedIndex(mon);
calendar(year, mon);
month4enab = getMonth(monthLabel.getText());
year4enab = yearLabel.getText();
startdte = year4enab + "-" + month4enab + "-01";
enddte = year4enab + "-" + month4enab + "-" + finalday;
}
public static void main(String[] args) {
new BarGraph().showBar();
}
private void leftActionPerformed(ActionEvent evt) {
show = 0;
if (mon == 0) {
year--;
mon = 11;
} else {
mon--;
}
yearspin.setValue(year);
month.setSelectedIndex(mon);
display();
calendar(year, mon);
displayCalendar();
updateDataset();
}
private void rightActionPerformed(ActionEvent evt) {
show = 0;
if (mon == 11) {
year++;
mon = 0;
} else {
mon++;
}
yearspin.setValue(year);
month.setSelectedIndex(mon);
display();
calendar(year, mon);
displayCalendar();
updateDataset();
}
private void displayCalendar() {
month4enab = getMonth(monthLabel.getText());
year4enab = yearLabel.getText();
startdte = year4enab + "-" + month4enab + "-01";
enddte = year4enab + "-" + month4enab + "-" + finalday;
}
private void monthItemStateChanged(ItemEvent evt) {
show = 0;
String s = (String) month.getSelectedItem();
if ("January".equals(s)) {
mon = 0;
}
if ("February".equals(s)) {
mon = 1;
}
if ("March".equals(s)) {
mon = 2;
}
if ("April".equals(s)) {
mon = 3;
}
if ("May".equals(s)) {
mon = 4;
}
if ("June".equals(s)) {
mon = 5;
}
if ("July".equals(s)) {
mon = 6;
}
if ("August".equals(s)) {
mon = 7;
}
if ("September".equals(s)) {
mon = 8;
}
if ("October".equals(s)) {
mon = 9;
}
if ("November".equals(s)) {
mon = 10;
}
if ("December".equals(s)) {
mon = 11;
}
display();
calendar(year, mon);
updateDataset();
}
private void yearspinStateChanged(ChangeEvent evt) {
show = 0;
year = (Integer) yearspin.getValue();
display();
calendar(year, mon);
updateDataset();
}
public void display() {
String month = "", day = "";
if (mon < 9) {
month = "0" + (mon + 1);
} else {
month = "" + (mon + 1);
}
if (nneed.length() < 2) {
day = "0" + nneed;
} else {
day = "" + nneed;
}
String datss = year + "-" + (month) + "-" + day;
switch (mon) {
case 0:
monthLabel.setText("JANUARY");
break;
case 1:
monthLabel.setText("FEBRUARY");
break;
case 2:
monthLabel.setText("MARCH");
break;
case 3:
monthLabel.setText("APRIL");
break;
case 4:
monthLabel.setText("MAY");
break;
case 5:
monthLabel.setText("JUNE");
break;
case 6:
monthLabel.setText("JULY");
break;
case 7:
monthLabel.setText("AUGUST");
break;
case 8:
monthLabel.setText("SEPTEMBER");
break;
case 9:
monthLabel.setText("OCTOBER");
break;
case 10:
monthLabel.setText("NOVEMBER");
break;
case 11:
monthLabel.setText("DECEMBER");
break;
}
yearLabel.setText(String.valueOf(year));
}
public void calendar(int year, int mon) {
int year1 = year;
int count1 = 1, fun = 0, day, day1 = 0, key = 0, k = -1, s = 1, ck = 2, cheak, y = 0;
day1 = year % 100;
fun = 1 + (day1 / 4);
switch (mon) {
case 0:
key = 1;
k = -1;
break;
case 1:
key = 4;
k = 0;
break;
case 2:
key = 4;
k = 0;
break;
case 3:
key = 0;
k = 0;
break;
case 4:
key = 2;
k = 0;
break;
case 5:
key = 5;
k = 0;
break;
case 6:
key = 0;
k = 0;
break;
case 7:
key = 3;
k = 0;
break;
case 8:
key = 6;
k = 0;
break;
case 9:
key = 1;
k = 0;
break;
case 10:
key = 4;
k = 0;
break;
case 11:
key = 6;
k = 0;
break;
}
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
k = -1;
day = 29;
leapcn = 0;
if (mon == 0 || mon == 1) {
leapcn = 1;
}
} else {
k = 0;
day = 28;
leapcn = 1;
}
if (year >= 2000) {
y = 6;
}
if (year <= 1900 && year > 2000) {
y = 0;
}
fun = fun + key + k + y;
fun = (fun + day1) % 7;
if (fun == 0) {
fun = 7;
}
if (mon == 0 || mon == 2 || mon == 4 || mon == 6 || mon == 7 || mon == 9 || mon == 11) {
day = 31;
}
if (mon == 3 || mon == 5 || mon == 8 || mon == 10) {
day = 30;
}
finalday = day;
System.out.println("DAYS IN THIS MONTHS:" + finalday);
cheak = fun + 1;
s++;
}
public static String getMonth(String s) {
String mont = "56";
if ("January".equalsIgnoreCase(s)) {
mont = "01";
} else if ("February".equalsIgnoreCase(s)) {
mont = "02";
} else if ("March".equalsIgnoreCase(s)) {
mont = "03";
} else if ("April".equalsIgnoreCase(s)) {
mont = "04";
} else if ("May".equalsIgnoreCase(s)) {
mont = "05";
} else if ("June".equalsIgnoreCase(s)) {
mont = "06";
} else if ("July".equalsIgnoreCase(s)) {
mont = "07";
} else if ("August".equalsIgnoreCase(s)) {
mont = "08";
} else if ("September".equalsIgnoreCase(s)) {
mont = "09";
} else if ("October".equalsIgnoreCase(s)) {
mont = "10";
} else if ("November".equalsIgnoreCase(s)) {
mont = "11";
} else if ("December".equalsIgnoreCase(s)) {
mont = "12";
}
return mont;
}
private void showBar() {
for (int i = 1; i <= finalday; i++) {
dataset.setValue(i, "Marks", "" + i);
}
JFreeChart chart = ChartFactory.createBarChart(" ", "Student", "Marks",
dataset, PlotOrientation.VERTICAL, false, true, false);
chart.setBackgroundPaint(Color.WHITE);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(new Color(221, 223, 238));
plot.setRangeGridlinePaint(Color.white);
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, new Color(231, 175, 61));
renderer.setSeriesPaint(1, Color.green);
renderer.setDrawBarOutline(false);
renderer.setShadowVisible(false);
chart.setBackgroundPaint(Color.WHITE);
chart.getTitle().setPaint(Color.blue);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
frame = new ChartFrame("Bar Chart", chart);
frame.add(month);
frame.add(left);
frame.add(right);
frame.add(yearspin);
frame.add(monthLabel);
frame.add(yearLabel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void updateDataset() {
dataset.clear();
for (int i = 1; i <= finalday; i++) {
dataset.setValue(i, "Marks", "" + i);
}
}
}

Related

Trouble receiving images from an 8 modem server

I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.

How to remove or edit MPAndroidChart - StackedBarChart - entries?

My stacked bar chart in MPAndroidChart works very well but I'm trying to remove or edit the values inside the bars. But I can't find any code which makes sense to modify.
I don't think that my code is very helpful, but here it is...
private void initStackedBarChartStuff() {
mMonths = dfs.getShortMonths();
mChart = (BarChart) mContext.findViewById(R.id.chart1);
mChart.setOnChartValueSelectedListener(this);
mChart.setDescription("");
// if more than 60 entries are displayed in the chart, no values will be
// drawn
mChart.setMaxVisibleValueCount(30);
// scaling can now only be done on x- and y-axis separately
mChart.setPinchZoom(false);
mChart.setDrawGridBackground(false);
mChart.setDrawBarShadow(false);
mChart.setDrawValueAboveBar(false);
// change the position of the y-labels
YAxis yLabels = mChart.getAxisLeft();
yLabels.setValueFormatter(new MyYAxisValueFormatter());
mChart.getAxisRight().setEnabled(false);
mChart.getAxisLeft().setEnabled(false);
XAxis xLabels = mChart.getXAxis();
xLabels.setPosition(XAxis.XAxisPosition.TOP);
Legend l = mChart.getLegend();
l.setPosition(Legend.LegendPosition.BELOW_CHART_RIGHT);
l.setFormSize(8f);
l.setFormToTextSpace(4f);
l.setXEntrySpace(6f);
// mChart.setDrawLegend(false);
}
fill the stackedBarChart
private void fillStackedBarChart(Vector drawingData, Vector drawingIntervall) {
if (drawingData == null || drawingData == null)
return;
int anzBdata = dataSizes[1];
int intervall = globalIntervall;
ArrayList<String> xVals = new ArrayList<String>();
// Strings über die Blöcke schreiben ###########################################
{
long zeit = 0;
String[] months = new String[12];
String[] days = new String[7];
boolean einmal = true;
for (int i = 0; i < drawingIntervall.size(); i++)
zeit += ((Long) drawingIntervall.get(i)).longValue();
if (bigData) // > 2 Jahre
months = null;
else if (zeit > 31623000) // > 1 Jahre
months = dfs.getShortMonths();
else
months = dfs.getMonths();
days = dfs.getWeekdays();
for (int i = 0; i < drawingData.size(); i++) {
long[] pack = (long[]) drawingData.get(i);
String s = "";
// Sonderfall !! In Monatsansicht den Monat dazu schreiben
if ((einmal) && (intervall == 2)) {
if (etStart.getText().toString().trim().startsWith("01.")) {
Calendar calE = convStringToDate(etEnd.getText().toString().trim(), true, true);
int jahr = calE.get(Calendar.YEAR);
int monat = calE.get(Calendar.MONTH);
Calendar calX = myGetInstance();
calX.set(Calendar.YEAR, jahr);
calX.set(Calendar.MONTH, monat);
calX = getLastDayOfMonth(calX);
if (calE.getTimeInMillis() == calX.getTimeInMillis()) {
einmal = false;
s = months[calE.get(Calendar.MONTH)];
}
}
}
switch (intervall) {
case 0:
s += df.format(convMilliToDate(pack[0] * 1000, false, false).getTime());
break;
case 1:
s += convMilliToString(pack[0] * 1000);
break;
case 2:
s += "KW " + convMilliToDate(pack[0] * 1000, false, false).get(Calendar.WEEK_OF_YEAR);
break;
case 3:
if (bigData)
s += convMilliToDate(pack[0] * 1000, false, false).get(Calendar.YEAR) + "";
else
s += months[convMilliToDate(pack[0] * 1000, false, false).get(Calendar.MONTH)];
break;
}
xVals.add(s);
}
}
// nun alle Balken/Blöcke zeichnen ##########################################
{
// 1 Y-Wert entspricht z.B. 1 Tag, o. 1 Woche,... jeder Y-Wert hat so viele floats wie B-Daten vorhanden sind ###########################################
ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
for (int i = 0; i < drawingData.size(); i++) {
long[] pack = (long[]) drawingData.get(i);
long intervallSek = ((Long) drawingIntervall.get(i)).longValue() + 1;
long pastSek = 0;
float[] f = new float[anzBdata + 1];
int b = 0;
for (int j = 0; j < pack.length; j++) {
if ((j >= dataSizes[0]) && (j <= (anzBdata - 1 + dataSizes[0]))) {
f[b++] = pack[j];
pastSek += pack[j];
}
}
f[b++] = intervallSek - pastSek; // zeichnet einen Block indem "keine Daten" aufgezeichnet wurden. (wenn Maschine ohne Strom o.ä.)
yVals1.add(new BarEntry(f, i));
}
// BarDataSet set1 = new BarDataSet(yVals1, "Statistics Business Data");
BarDataSet set1 = new BarDataSet(yVals1, "");
set1.setColors(getColors());
set1.setStackLabels(barChartLegend);
ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
dataSets.add(set1);
BarData data = new BarData(xVals, dataSets);
data.setValueFormatter(new MyValueFormatter());
mChart.setData(data);
mChart.invalidate();
}
}
This solution is not really pretty, may somone else find a better one...
The class BarChart extends from BarLineChartBase. There is a line in BarLineChartBase which can be annotated or removed to get the desired solution.
mRenderer.drawValues(canvas);
There are basically two ways:
Use the ValueFormatter to custom format your values (edit or remove)
Use dataSet.setDrawValues(false) to completely remove all values

JScrollPane not working horizontally

Hi. I need some help. JScrollPane working vertically good but horizontally not. And I cant find whats the problem. I know that its a little big project and there is a lot of confusing codes but I cant delete any of that function.
public final class Salary extends javax.swing.JFrame {
private SalaryTableModel tableModel;
public int selectedRow = -1;
public static String bolme;
public static String ay;
public static int il = 0;
private final String selectedItem_Bolme;
private final String selectedItem_Ay;
private final int selectedItem_Il;
private List<Pojo> sortedList;
public TableColumn date;
public static int bolmeId = 0;
public static String ad;
public static int row2;
public void visible(String bolme2, String ay2, int il2) {
il = il2;
ay = ay2;
bolme = bolme2;
new Salary().setVisible(true);
}
public RXTable autoResizeColWidth(RXTable table, SalaryTableModel model) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setModel(model);
int margin = 5;
for (int i = 0; i < table.getColumnCount(); i++) {
int vColIndex = i;
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width;
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
width += 2 * margin;
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
SwingConstants.LEFT);
table.getTableHeader().setReorderingAllowed(false);
return table;
}
public Salary() {
initComponents();
Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/db.png"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
List<Pojo> model = DBO.findBolme();
HashSet hs = new HashSet();
ArrayList al = new ArrayList();
model.stream().forEach((model1) -> {
hs.add(model1.getBolme());
});
al.addAll(hs);
comboBolme.addItem("Butun Bolmeler");
al.stream().forEach((al1) -> {
comboBolme.addItem(al1);
bolmeId++;
});
comboBolme.removeItem("null");
if (bolme == null) {
comboBolme.setSelectedIndex(0);
} else {
comboBolme.setSelectedItem(bolme);
}
if (ay == null) {
comboAy.setSelectedIndex(0);
} else {
comboAy.setSelectedItem(ay);
}
List<Pojo> model2 = DBO.findIl();
HashSet hs2 = new HashSet();
ArrayList al2 = new ArrayList();
model2.stream().forEach((model1) -> {
hs2.add(model1.getIl());
});
al2.addAll(hs2);
comboIl.addItem(0000);
al2.stream().forEach((al1) -> {
comboIl.addItem(al1);
});
comboIl.removeItem(0);
if (il == 0) {
comboIl.setSelectedIndex(0);
} else {
comboIl.setSelectedItem(il);
}
selectedItem_Bolme = (String) comboBolme.getSelectedItem();
selectedItem_Ay = (String) comboAy.getSelectedItem();
selectedItem_Il = Integer.parseInt(comboIl.getSelectedItem().toString());
Pojo tempVar;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() == sortedList.get(j).getCem()) {
}
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
tempVar = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, tempVar);
}
}
}
tableModel = new SalaryTableModel(sortedList) {
#Override
public boolean isCellEditable(int row, int column) {
ad = tableModel.getTopic(row).getAd();
selectedRow = tableModel.getTopic(row).getId();
row2 = row;
return (column != 0) && (column != 17);
}
};
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel);
JScrollPane pane = new JScrollPane(table);
add(pane);
table.setSelectAllForEdit(true);
table.getColumnModel().getColumn(0).setMinWidth(100);
table.getColumnModel().getColumn(1).setMinWidth(100);
table.getColumnModel().getColumn(2).setMinWidth(100);
table.getColumnModel().getColumn(3).setMinWidth(100);
table.getColumnModel().getColumn(4).setMinWidth(100);
table.getColumnModel().getColumn(5).setMinWidth(100);
table.getColumnModel().getColumn(6).setMinWidth(100);
table.getColumnModel().getColumn(7).setMinWidth(100);
table.getColumnModel().getColumn(8).setMinWidth(100);
table.getColumnModel().getColumn(9).setMinWidth(100);
table.getColumnModel().getColumn(10).setMinWidth(100);
table.getColumnModel().getColumn(11).setMinWidth(100);
table.getColumnModel().getColumn(12).setMinWidth(100);
table.getColumnModel().getColumn(13).setMinWidth(100);
table.getColumnModel().getColumn(14).setMinWidth(100);
table.getColumnModel().getColumn(15).setMinWidth(100);
table.getColumnModel().getColumn(16).setMinWidth(100);
table.getColumnModel().getColumn(17).setMinWidth(100);
table.getColumnModel().getColumn(18).setMinWidth(100);
table.getColumnModel().getColumn(19).setMinWidth(100);
table.getColumnModel().getColumn(20).setMinWidth(100);
table.getColumnModel().getColumn(21).setMinWidth(100);
table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);
double x = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
x += tableModel.getTopic(i).getArtim();
}
lblArtiminCemi.setText(String.valueOf((x)));
double y = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
y += tableModel.getTopic(i).getCem();
}
lblTotal.setText(String.valueOf((y)));
comboBolme.addActionListener((ActionEvent e) -> {
String selectedBolme = (String) comboBolme.getSelectedItem();
visible(selectedBolme, ay, il);
setVisible(false);
});
comboAy.addActionListener((ActionEvent e) -> {
String selectedAy = (String) comboAy.getSelectedItem();
visible(bolme, selectedAy, il);
setVisible(false);
});
comboIl.addActionListener((ActionEvent e) -> {
int selectedIl = Integer.parseInt(comboIl.getSelectedItem().toString());
visible(bolme, ay, selectedIl);
setVisible(false);
});
table.getModel().addTableModelListener((TableModelEvent e) -> {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model1 = (TableModel) e.getSource();
String columnName = model1.getColumnName(column);
Object value = model1.getValueAt(row, column);
Pojo temp;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
temp = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, temp);
}
}
}
List<Pojo> list = sortedList;
Pojo data = list.get(row);
switch (column) {
case 0:
data.setId((int) value);
break;
case 1:
data.setAd((String) value);
break;
case 2:
data.setCins((int) value);
break;
case 3:
data.setBank((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 4:
data.setIlk_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 5:
data.setSon_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 6:
data.setArtim((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 7:
data.setCem((Double) value);
break;
case 8:
data.setElave_is((int) value);
break;
case 9:
data.setMukafatlandirma((Double) value);
break;
case 10:
data.setQayib_gunu((int) value);
break;
case 11:
data.setDetal_xetasi((Double) value);
break;
case 12:
data.setSatin_alma((Double) value);
break;
case 13:
data.setBolme(value.toString().toUpperCase());
break;
case 14:
data.setAy((String) value);
break;
case 15:
data.setIl((Integer) value);
break;
case 16:
data.setIsleyir((int) value);
break;
case 17:
data.setNe_qeder_isleyib((String) value);
break;
case 18:
try {
String time = value.toString();
Date date3 = new Date();
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM");
Date date4 = format2.parse(time);
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM");
data.setBaslama_tarixi(format3.format(date4));
Calendar cal = Calendar.getInstance();
cal.setTime(date3);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date4);
int diffYear = cal.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
int diffMonth = cal.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
if (diffMonth < 0) {
diffMonth += 12;
diffYear--;
}
data.setNe_qeder_isleyib(diffYear + " il " + diffMonth + " ay");
} catch (NumberFormatException | IndexOutOfBoundsException | ParseException ex) {
Logger.getLogger(Salary.class.getName()).log(Level.SEVERE, null, ex);
}
break;
case 19:
data.setBorc((Double) value);
break;
case 20:
data.setYekun_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
data.setYekun_maas(data.getCem() - data.getBorc()
- ((data.getCem() / 26) * data.getQayib_gunu()) - data.getDetal_xetasi()
+ data.getSatin_alma() + ((data.getCem() / 26) * data.getElave_is()));
break;
case 21:
data.setQeyd((String) value);
break;
}
DBO.salary_Update(data, selectedRow);
visible(bolme, ay, il);
setVisible(false);
});
}`
If what you want is to display the full text of the cells instead of an abbreviation, you can use the Table Column Adjuster. e.g.:
String[] columnNames = {"Colum1", "Colum2", "Colum2"};
String[][] data = {
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-", "-"},
{"-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-"},
{"-", "-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
};
TableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
JScrollPane pane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(400, 300);
frame.setVisible(true);
You can get the code for the class TableColumnAdjuster from http://www.camick.com/java/source/TableColumnAdjuster.java
Found a way )
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel) {
#Override
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane pane = new JScrollPane(table);
add(pane);
//table.setSelectAllForEdit(true);
//table.getColumnModel().getColumn(0).setMinWidth(100);
//table.getColumnModel().getColumn(1).setMinWidth(100);
//....
//table.getColumnModel().getColumn(21).setMinWidth(100);
//table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);

Simple code compilation problems

import acm.program.*;
public class mainApp extends ConsoleProgram {
public void run() {
////////////////////////
Item aItems[] = new Item[26];
aItems[1] = new Motherboard("970a", 2014, 200.0, "GIGABYTE", "INTEL", 64, 5);
aItems[2] = new Motherboard("gb4", 2012, 150.0, "ASROCK", "AMD", 32, 4);
aItems[3] = new Proccesor("I5", 2010, 180.0, "INTEL", 3.3, 4);
aItems[4] = new Proccesor("I7", 2014, 900.0, "INTEL", 4.0, 4);
aItems[5] = new Gcard("RADEON", 2012, 300.0, "GIGABYTE", "AMD", 4);
aItems[6] = new Gcard("RADEON", 2010, 200.0, "SAPPHIRE", "NVIDIA", 2);
aItems[7] = new Ram("IO", 2010, 100.0, "ASUS", "DDR", 4, 1600);
aItems[8] = new Ram("LM", 2012, 160.0, "PALIT", "DDR3", 8, 2000);
aItems[9] = new HardDrive("E2", 2013, 100.0, "WD", "SSD", 2.5, 750);
aItems[10] = new HardDrive("LM", 2012, 150.0, "HP", "HDD", 3.5, 1000);
aItems[11] = new Monitor("CFA90", 2014, 180.0, "SAMSUNG", "LCD", "23,5", "1080", "HDMI");
aItems[12] = new Monitor("27EA", 2013, 280.0, "ASUS", "LED", "28", "1080", "HDMI");
aItems[13] = new Mouse("Dethadder", 2013, 80.0, "Razer", "Optical", "wired");
aItems[14] = new Mouse("M9Q", 2013, 80.0, "Microsoft", "laser", "wireless");
aItems[15] = new Keyboard("Blackwidow", 2014, 130.0, "Razer", "wired");
aItems[16] = new Keyboard("GK10", 2013, 100.0, "CM Storm", "wireless");
aItems[17] = new Printer("PS3H", 2012, 90.0, "HP", "laser", "colored");
aItems[18] = new Printer("SPP5", 2013, 190.0, "SAMSUNG", "inkjet", "black and white");
////////////////////////
boolean flag = true;
boolean flag1 = true;
boolean flag2 = true;
String sales[] = new String[5];
String orders[] = new String[5];
println("Welcome to our shop ");
do {
println("0 ) available products");
println("1 ) overview orders ");
println("2 ) overview sales ");
println("3 ) make new order ");
println("4 ) make new sale ");
println("5 ) return ");
int x = readInt("Click a number from 0-5 to choose what you want: ");
/////////////////////// switch of x starts here
switch (x) {
case 0:
for (int i = 0; i <= 25; i++) {
if (aItems[i] != null) {
if (i = 0) {
println("MOTHERBOARDS:");
}
if (i = 2) {
println("PROCESSORS:");
}
if (i = 4) {
println("GRAPHICS CARDS:");
}
if (i = 6) {
println("RAM MEMORIES:");
}
if (i = 8) {
println("HARD DRIVES:");
}
if (i = 10) {
println("MONITORS:");
}
if (i = 12) {
println("MOUSES:");
}
if (i = 14) {
println("KEYBOARDS:");
}
if (i = 16) {
println("PRINTERS:");
}
println(aItems[i]);
}
}
break;
case 4:
boolean flag3 = true;
while (flag3 == true) {
String kind2 = readLine("Do you want to sale hardware or peripheral product ? : ");
if (kind.equals("hardware")) {
String product = readLine("Do you want monitor ,mouse ,printer or keyboard ? : ");
if (product.equals("monitor")) {
println("We have 2 available monitors: ");
} else if (product.equals("mouse")) {
} else if (product.equals("printer")) {
} else if (product.equals("keyboard")) {
}
flag2 = false;
} else if (kind.equals("peripheral")) {
flag2 = false;
} else {
println("give the right type of product!!");
}
}
break;
switch (b) {
case 0:
println("The available Motherboards are:");
println(aItems[1]);
println(aItems[2]);
println("Enter on for first motherboard and 2 for the second motherboard: ");
int c = readInt("Enter number: ");
case 5:
flag = false;
break;
}
}
while (flag == true) ;
println("Have a nice day !!!");
}
}
}
}
Ignore the aItems and the hardware and peripherals classes items that i create they have all been compiled and work fine. But when i compile this class it gives me errors i dont know how to deal with. Please help me.
By the way i must say that i compile through cmd.

JAVA 6x6 grid colouring game

Hi everyone Im on to the last part now which is file reading. i have tried writing a fileReader but seem to not be changing the value of my variable rNum?
any ideas on why it wont change in the following statements? thanks
public void readStartFile(String fileName){
int rowNumber=-1;
int colNumber = -1;
int rN= 0;
int cN = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("start.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] temp = strLine.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
colNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2];
if(rowNumber == 0)
rN =0;
else if(rowNumber == 1)
rN =1;
else if(rowNumber == 2)
rN =2;
else if(rowNumber == 3)
rN =3;
else if(rowNumber == 4)
rN =4;
else if(rowNumber == 5)
rN =5;
if(colNumber == 0)
cN =0;
else if(colNumber == 1)
cN =1;
else if(colNumber == 2)
cN =2;
else if(colNumber == 3)
cN =3;
else if(colNumber == 4)
cN =4;
else if(colNumber == 5)
cN =5;
if (colour == "Red")
buttons[rN][cN].setBackground(Color.RED);
System.out.println(""+rN);
System.out.println(""+cN);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
this is a method from the ButtonColours class. Now how would i set the buttons to the specified colour as what i am doing at the minute does not seem to work.
Unfortunately, there is no reliable way to change the color of any JButton. Some "look and feel" implementations don't honor the color set by setBackground(). You'd be better off just adding a MouseListener to the panel(s) to listen for mouse-up events, and responding to those, rather than using buttons at all.
In order to change the Colour of your JButton, first of all you must keep one thing in mind, always to use buttonObject.setOpaque(true); as very much adviced to me once by #Robin :-). As taken from Java Docs the call to setOpaque(true/false)
Sets the background color of this component. The background color
is used only if the component is opaque
Here I had modified your code a bit, and added some comments as to what I had added, see is this what you wanted.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ButtonColours extends JFrame
{
private static ButtonColours buttonColours;
/*
* Access Specifier is public, so that they can be
* accessed by the ColourDialog class.
*/
public JButton[][] buttons;
private static final int GRID_SIZE = 600;
public static final int ROW = 6;
public static final int COLUMN = 6;
// Gap between each cell.
private static final int GAP = 2;
private static final Color DEFAULT_COLOUR = new Color(100,100,100);
public static final String DEFAULT_COMMAND = "6";
// Instance Variable for the ColourDialog class.
private ColourDialog dialog = null;
private BufferedReader input;
private DataInputStream dataInputStream;
private FileInputStream fileInputStream;
private String line= "";
/*
* Event Handler for each JButton, inside
* the buttons ARRAY.
*/
public ActionListener buttonActions = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(ae.getActionCommand());
if (dialog != null && dialog.isShowing())
dialog.dispose();
dialog = new ColourDialog(buttonColours, "COLOUR CHOOSER", false, button);
dialog.setVisible(true);
button.setBackground(DEFAULT_COLOUR);
button.setName("6");
}
};
public ButtonColours()
{
buttons = new JButton[ROW][COLUMN];
try
{
fileInputStream = new FileInputStream("start.txt");
dataInputStream = new DataInputStream(fileInputStream);
input = new BufferedReader(new InputStreamReader(dataInputStream));
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
/*
* Instead of explicitly calling getPreferredSize() method
* we will override that method instead, for good
* visual appearance fo the Program on different
* Platforms, i.e. Windows, MAC OS, LINUX
*/
public Dimension getPreferredSize()
{
return (new Dimension(GRID_SIZE, GRID_SIZE));
}
private void readFile()
{
int rowNumber = -1;
int columnNumber = -1;
try
{
while((line = input.readLine()) != null)
{
String[] temp = line.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
columnNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2].trim();
System.out.println("Row is : " + rowNumber);
System.out.println("Column is : " + columnNumber);
System.out.println("Colour is : " + colour);
if (colour.equals("RED") && rowNumber < ROW && columnNumber < COLUMN)
{
System.out.println("I am working !");
buttons[rowNumber][columnNumber].setBackground(Color.RED);
buttons[rowNumber][columnNumber].setName("0");
}
else if (colour.equals("YELLOW") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.YELLOW);
buttons[rowNumber][columnNumber].setName("1");
}
else if (colour.equals("BLUE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.BLUE);
buttons[rowNumber][columnNumber].setName("2");
}
else if (colour.equals("GREEN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.GREEN);
buttons[rowNumber][columnNumber].setName("3");
}
else if (colour.equals("PURPLE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,0,102));
buttons[rowNumber][columnNumber].setName("4");
}
else if (colour.equals("BROWN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,51,0));
buttons[rowNumber][columnNumber].setName("5");
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JComponent contentPane = (JComponent) getContentPane();
contentPane.setLayout(new GridLayout(ROW, COLUMN, GAP, GAP));
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setOpaque(true);
buttons[i][j].setBackground(DEFAULT_COLOUR);
buttons[i][j].setActionCommand(i + " " + j);
buttons[i][j].setName("6");
buttons[i][j].addActionListener(buttonActions);
contentPane.add(buttons[i][j]);
}
}
pack();
setVisible(true);
readFile();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
buttonColours = new ButtonColours();
buttonColours.createAndDisplayGUI();
}
});
}
}
class ColourDialog extends JDialog
{
private Color[] colours = {
Color.RED,
Color.YELLOW,
Color.BLUE,
Color.GREEN,
new Color(102,0,102),
new Color(102,51,0)
};
private int[] colourIndices = new int[6];
private JButton redButton;
private JButton yellowButton;
private JButton blueButton;
private JButton greenButton;
private JButton purpleButton;
private JButton brownButton;
private JButton clickedButton;
private int leftRowButtons;
private int leftColumnButtons;
public ColourDialog(final ButtonColours frame, String title, boolean isModal, JButton button)
{
super(frame, title, isModal);
leftRowButtons = 0;
leftColumnButtons = 0;
clickedButton = button;
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
redButton = new JButton("RED");
redButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "0";
/*
* Here we will check, if RED is clicked,
* do we have any block with the same colour
* or not, if yes then nothing will happen
* else we will change the background
* to RED.
*/
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.RED);
clickedButton.setName("0");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
yellowButton = new JButton("YELLOW");
yellowButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "1";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.YELLOW);
clickedButton.setName("1");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
blueButton = new JButton("BLUE");
blueButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "2";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.BLUE);
clickedButton.setName("2");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
greenButton = new JButton("GREEN");
greenButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "3";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.GREEN);
clickedButton.setName("3");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
purpleButton = new JButton("PURPLE");
purpleButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "4";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,0,102));
clickedButton.setName("4");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
brownButton = new JButton("BROWN");
brownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "5";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,51,0));
clickedButton.setName("5");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
panel.add(redButton);
panel.add(yellowButton);
panel.add(blueButton);
panel.add(greenButton);
panel.add(purpleButton);
panel.add(brownButton);
add(panel);
pack();
}
private boolean checkBlockColours(ButtonColours frame, String possibleColour)
{
leftRowButtons = 0;
leftColumnButtons = 0;
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
// First we will check in ROW. for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
if (i != column)
{
JButton button = frame.buttons[row][i];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftRowButtons++;
}
}
// Now we will check in COLUMN, for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.ROW; i++)
{
if (i != row)
{
JButton button = frame.buttons[i][column];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftColumnButtons++;
}
}
return true;
}
private void fillRemaining(ButtonColours frame)
{
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
int emptyRow = -1;
int emptyColumn = -1;
if (leftRowButtons == 1)
{
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
JButton button = frame.buttons[row][i];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = row;
emptyColumn = i;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersRow(frame, row);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
if (leftColumnButtons == 1)
{
for (int i = 0; i < ButtonColours.ROW; i++)
{
JButton button = frame.buttons[i][column];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = i;
emptyColumn = column;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersColumn(frame, column);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
}
private void setButtonName(JButton button, int index)
{
switch(index)
{
case 0:
button.setName("0");
break;
case 1:
button.setName("1");
break;
case 2:
button.setName("2");
break;
case 3:
button.setName("3");
break;
case 4:
button.setName("4");
break;
case 5:
button.setName("5");
break;
}
}
private void disableListenersRow(ButtonColours frame, int row)
{
System.out.println("Disabled ROW : " + row);
for (int i = 0; i < ButtonColours.ROW; i++)
{
frame.buttons[row][i].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + row + " " + i);
}
}
private void disableListenersColumn(ButtonColours frame, int column)
{
System.out.println("Disabled COLUMN : " + column);
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
frame.buttons[i][column].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + i + " " + column);
}
}
}
Here is the output of this thingy :-)
(maybe use JColorChooser directly)
don't use two JFrames
use putClientProperty
use ButtonModel or MouseListener
use JOptionsPane put there JButtons that returns Color, or create JDialog(parent, true) with JButtons layed by GridLayout
One convenient and reliable way to alter a button's appearance in any L&F is to implement the Icon interface, as shown in this example.

Categories