JScrollPane not working horizontally - java

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);

Related

One Row in One Page: Boxable

This is the code for this issue for you to check if there is any problem in the code.
Now the problem is when I limit the rows to 45 (this number fits in one page) every row will print in one page.
But, If I don't limit the rows and the row size (approximately 100-200), every row goes to new page in the PDF. The PDF page number goes to approximately equal to row numbers.
I have opened this issue in Boxable's git but it's not active so I came for help here.
Following are the files generated in both conditions:
LimitTemp.pdf
noLimitTemp.pdf
public class CSVtoPDF {
private float marginBetweenYElements = 10;
private float titleFontSize = 18;
private float fontSize = 8;
private float headerFontSize = 12;
private float header1FontSize = 14;
private float header2FontSize = 12;
private float headerCellHeight = 19;
private float dataCellHeight = 12;
private PDFont font = PDType1Font.HELVETICA;
private PDFont headerFont = PDType1Font.TIMES_BOLD;
List filteredData = new ArrayList();
ReportSettings rs = new ReportSettings();
String filePath, destPath, header1, header2, filename;
public CSVtoPDF(List data, Audit audit) throws IOException {
this.filteredData = data;
Date liveDate = new Date();
SimpleDateFormat format= new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
liveDate = Calendar.getInstance().getTime();
float headerCellHeight = 18;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
//page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
// PDRectangle.A4.getWidth()));
PDPageContentStream cos = new PDPageContentStream(doc, page);
/* Add page to PDDocument */
doc.addPage(page);
System.out.println("Inside Main csvtopdf");
//Draw Header
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
try {
String[] keys = prefs.keys();
//destPath = prefs.get("destpath", rs.getDestPath());
//filename = prefs.get("file_name", rs.getFileName());
//header1 = prefs.get("header1", rs.getHeader1());
//header2 = prefs.get("header2", rs.getHeader2());
} catch (BackingStoreException ex) {
System.err.println(ex);
}
header1= "Header 1";
header2= "Header 2";
cos.beginText();
cos.moveTextPositionByAmount(220, 810);
cos.setFont(headerFont, header1FontSize);
cos.drawString(header1);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 800);
cos.setFont(headerFont, header2FontSize);
cos.drawString(header2);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 790);
cos.setFont(headerFont, headerFontSize);
cos.drawString("Report: Filtered Audit Report");
cos.endText();
//cos.beginText();
// cos.moveTo(200, 30);
//cos.setFont(headerFont, headerFontSize);
// cos.drawString(header2);
//cos.endText();
/* Initialize DataTable */
float margin = 20;
float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
float yStart = yStartNewPage;
float bottomMargin = -800;
BaseTable table = new BaseTable(yStart, yStartNewPage,
bottomMargin, tableWidth, margin, doc, page, true, true);
Row<PDPage> dataRow = table.createRow(dataCellHeight);
for (int i = 0; i < data.size() - 1; i++) {
System.out.println(data.get(i));
}
drawTableData(table, dataCellHeight, 20, data, 1,doc,page);
table.draw();
File result;
if (Objects.isNull(destPath)) {
cos.close();
result = new File("temp.pdf");
} else {
result = new File(destPath);
}
System.out.println("befor save result");
doc.save(result);
System.out.println("after save result");
}
public void drawTableData(BaseTable table, float dataCellHeight, float
cellWidth, List<Audit> data, int style,PDDocument doc,PDPage page) {
String s;
Cell<PDPage> cell;
// for (int k = 0; k < data.size(); k++) {
System.out.println("inside drawtable for ");
for (int i = 0; i < data.size(); i++) { // add row
System.out.println("inside drawtable for " + i);
Audit atmp = data.get(i);
//if (i==35) {
// doc.addPage(page);
//}
Row<PDPage> sTableRow = table.createRow(dataCellHeight);
for (int j = 0; j <= 2; j++) { //add cell in the rows
if (j == 0) { // normal cells on right
s = atmp.getTimeStamp();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
//k++;
} else if (j == 1) { //big cells on left
s = atmp.getDiscription();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth + 50, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
// k++;
} else if (j == 2) { //top blank cell
//System.out.println("In j null and 0 " + j);
s = atmp.getUserID();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth - 10, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
//cell.setBottomBorderStyle(null);
setStyle(style, cell);
//k++;
}
}
table.addHeaderRow(sTableRow);
System.out.println(" row added ");
}
//}
}
public void setStyle(int type, Cell cell) {
// type : 0 as header, 1 as table body
if (type == 0) {
cell.setFont(headerFont);
//cell.setHeight(headerCellHeight);
cell.setFontSize(headerFontSize);
cell.setBottomPadding(3);
} else if (type == 1) {
cell.setTopPadding(1);
cell.setFont(font);
cell.setAlign(HorizontalAlignment.LEFT);
//cell.setHeight(dataCellHeight);
cell.setFontSize(fontSize);
cell.setBottomPadding(1);
}
}
I found a silly problem in my code. I am telling this so that someone else must not repeat this.
I treated every row of the data table as header row. So it went to new page.
To be specific. In the function drawTableData I removed table.addHeaderRow(sTableRow)

How to add a new sheet into an existing xls file

I need to add a new sheet with different methods and headers within the same workbook. I'm able to add the new sheet but how do add the separate methods and headers for the second sheet? Right now both sheets are duplicate copies. Basically How would I add different data to both sheets. Any help would be appreciated and I always accept the answers and also up vote.
public class ExcelWriter {
Logger log = Logger.getLogger(ExcelWriter.class.getName());
private HSSFWorkbook excel;
public ExcelWriter() {
excel = new HSSFWorkbook();
}
public HSSFWorkbook getWorkbook() {
return excel;
}
public void writeExcelFile(String filename, String[] columns, Object[][] data, HSSFCellStyle[] styles,
HSSFCellStyle columnsStyle, String[] header, String[] footer) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
HSSFSheet sheet = excel.createSheet("Daily Screening");
HSSFSheet sheet1 = excel.createSheet("Parcel Return");
int numHeaderRows = header.length;
createHeader(sheet,header,columns.length, 0);
createHeader(sheet1,header,columns.length, 0);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
createColumnHeaderRow(sheet1,columns,numHeaderRows,columnsStyle);
int rowCtr = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr;
else
rowCtr = rowCtr + 2;
createRow(sheet, data[i], rowCtr, styles);
}
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet1, data[i], rowCtr1, styles);
}
int totalRows = rowCtr1 + 1;
createHeader(sheet1,footer,columns.length, totalRows);
excel.write(out);
out.close();
}
private void createHeader(HSSFSheet sheet1, String[] header, int columns, int rowNum) {
for( int i = 0; i < header.length ; i++ ) {
HSSFRow row = sheet1.createRow(i + rowNum);
HSSFCell cell = row.createCell((short) 0);
String text = header[i];
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
HSSFCellStyle style = excel.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont arialBoldFont = excel.createFont();
arialBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
arialBoldFont.setFontName("Arial");
style.setFont(arialBoldFont);
if (!isEmpty(header[i]) && rowNum < 1) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
cell.setCellStyle(style);
sheet1.addMergedRegion( new Region(i+rowNum,(short)0,i+rowNum,(short)(columns-1)) );
}
}
private HSSFRow createColumnHeaderRow(HSSFSheet sheet, Object[] values, int rowNum, HSSFCellStyle style) {
HSSFCellStyle[] styles = new HSSFCellStyle[values.length];
for( int i = 0; i < values.length; i++ ) {
styles[i] = style;
}
return createRow(sheet,values,rowNum,styles);
}
private HSSFRow createRow(HSSFSheet sheet1, Object[] values, int rowNum, HSSFCellStyle[] styles) {
HSSFRow row = sheet1.createRow(rowNum);
for( int i = 0; i < values.length; i++ ) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(styles[i]);
try{
Object o = values[i];
if( o instanceof String ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
else if (o instanceof Double) {
Double d = (Double) o;
cell.setCellValue(d.doubleValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if (o instanceof Integer) {
Integer in = (Integer)o;
cell.setCellValue(in.intValue());
}
else if (o instanceof Long) {
Long l = (Long)o;
cell.setCellValue(l.longValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if( o != null ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return row;
}
public boolean isEmpty(String str) {
if(str.equals(null) || str.equals(""))
return true;
else
return false;
}
}
Report Generator Class
public class SummaryReportGenerator extends ReportGenerator {
Logger log = Logger.getLogger(SummaryReportGenerator.class.getName());
public SummaryReportGenerator(String reportDir, String filename) {
super( reportDir + filename + ".xls", reportDir + filename + ".pdf");
}
public String[] getColumnNames() {
String[] columnNames = {"ISC\nCode", "Total\nParcels", "Total\nParcel Hit\n Count",
"Filter Hit\n%", "Unanalyzed\nCount", "Unanalyzed\n%",
"Name\nMatch\nCount", "Name\nMatch\n%", "Pended\nCount",
"Pended\n%", "E 1 Sanction\nCountries\nCount", "E 1 Sanction\nCountries\n%", "Greater\nthat\n$2500\nCount", "Greater\nthat\n$2500\n%",
"YTD\nTotal Hit\nCount", "YTD\nLong Term\nPending", "YTD\nLong Term\n%"};
return columnNames;
}
public HSSFCellStyle getColumnsStyle(HSSFWorkbook wrkbk) {
HSSFCellStyle style = wrkbk.createCellStyle();
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont timesBoldFont = wrkbk.createFont();
timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
timesBoldFont.setFontName("Times New Roman");
style.setFont(timesBoldFont);
return style;
}
public Object[][] getData(Map map) {
int rows = map.size();// + 1 + // 1 blank row 1; // 1 row for the grand total;
int cols = getColumnNames().length;
Object[][] data = new Object[rows][cols];
int row = 0;
for (int i=0; i < map.size(); i++ ){
try{
SummaryBean bean = (SummaryBean)map.get(new Integer(i));
data[row][0] = bean.getIscCode();
data[row][1] = new Long(bean.getTotalParcelCtr());
data[row][2] = new Integer(bean.getTotalFilterHitCtr());
data[row][3] = bean.getFilterHitPrctg();
data[row][4] = new Integer(bean.getPendedHitCtr());
data[row][5] = bean.getPendedHitPrctg();
data[row][6] = new Integer(bean.getTrueHitCtr());
data[row][7] = new Integer(bean.getRetiredHitCtr());
data[row][8] = new Integer(bean.getSanctCntryCtr());
data[row][9] = new Integer(bean.getC25Ctr());
data[row][10] = new Integer(bean.getCnmCtr());
data[row][11] = new Integer(bean.getCndCtr());
data[row][12] = new Integer(bean.getCnlCtr());
data[row][13] = new Integer(bean.getCneCtr());
data[row][14] = new Integer(bean.getVndCtr());
data[row][15] = new Integer(bean.getCilCtr());
data[row][16] = new Integer(bean.getHndCtr());
data[row][17] = new Integer(bean.getCnrCtr());
++row;
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return data;
}
public String[] getHeader(String startDate, String endDate) {
Date today = new Date();
String reportDateFormat = Utils.formatDateTime(today, "MM/dd/yyyyHH.mm.ss");
String nowStr = Utils.now(reportDateFormat);
String[] header = {"","EXCS Daily Screening Summary Report ","",
"for transactions processed for the calendar date range",
"from " + startDate + " to " + endDate,
"Report created on " + nowStr.substring(0,10)+ " at "
+ nowStr.substring(10)};
return header;
}
public HSSFCellStyle[] getStyles(HSSFWorkbook wrkbk) {
int columnSize = getColumnNames().length;
HSSFCellStyle[] styles = new HSSFCellStyle[columnSize];
HSSFDataFormat format = wrkbk.createDataFormat();
for (int i=0; i < columnSize; i++){
styles[i] = wrkbk.createCellStyle();
if (i == 0){
styles[i].setAlignment(HSSFCellStyle.ALIGN_LEFT);
}else{
styles[i].setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
if (i == 1 || i == 2){
styles[i].setDataFormat(format.getFormat("#,###,##0"));
}
HSSFFont timesFont = wrkbk.createFont();
timesFont.setFontName("Times New Roman");
styles[i].setFont(timesFont);
}
return styles;
}
public String[] getFooter() {
String[] header = {"","Parcel Return Reason Code Reference","",
"DPM = Sender and/or recipient matches denied party",
"HND = Humanitarian exception not declared",
"CNM = Content not mailable under export laws",
"VND = Value of content not declared",
"CNR = Customer non-response",
"C25 = Content Value greater than $2500",
"CIL = Invalid license",
"C30 = More than one parcel in a calendar month",
"CNL = Content description not legible",
"CNE = Address on mailpiece not in English",
"RFN = Requires full sender and addressee names",
"DGS = Dangerous goods",
"R29 = RE-used 2976 or 2976A",
"ANE = PS Form 2976 or 2976A not in English",
"ICF = Incorrect Customs Declaration Form used",
"DPR = Declaration of purpose required",
"ITN = Internal Transaction Number (ITN), Export Exception/Exclusion Legend (ELL), or Proof of Filing Citation (PFC) is required",
"OTH = Other","",};
return header;
}
}
what you need is
HSSFSheet sheet = parentworkbookname.createSheet("Sample sheet2");

Plotting BarGraph according to month days dynamically using 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);
}
}
}

Selecting JTable row without user interaction

I want to select JTable zeroth row be selected by default
I am using following code but it gets the zeroth to be focused, not selected
jtblProduct.setCellSelectionEnabled(true);
jtblProduct.changeSelection(0, 0, false, false);
jtblProduct.requestFocus();
jtblProduct.scrollRectToVisible(new Rectangle(jtblProduct.getCellRect(0, 0, true)));
When I get the selected row by using the following code it returns -1, which means none selected.
jtblProduct.getSelectedRow()
Please provide me the way to select the zeroth row by default.
I haven't any issue with that, meaning
a) table.changeSelection(row, col, false, false);
or
b) table.getSelectedRow()
maybe everything depends of how is set value for ListSelectionModel
for better help sooner edit your question with a SSCCE
code
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
//Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
/*for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}*/
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
//DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 100));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 100));
sp2.setViewportView(jTable2);
/*final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 100));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);*/
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2);
JPanel panel1 = new JPanel();
//panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.setLayout(new GridLayout(2, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
//panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
System.out.println(table.getSelectedRow());
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableSelectionGood tableSelection = new TableSelectionGood();
}
});
}
}
Have you tried jtable.setRowSelectionInterval(..) ?
Addition from comment: also try jtable.addRowSelectionInterval(..).

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