Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
my progress bar is update only to 100%. i check with printing and it's seems everything run as it should be but the UI does not update according to the parameters in the printing check!
here is my Panel class. the main class create frame the adding the MyPanel i create:
public class MyPanel extends JPanel {
File[] DFLIST;
File DF[];
File INP;
File LOG;
JButton chooseDF = new JButton("Choose defect file");
JButton chooseLog = new JButton("Choose log file");
JButton chooseInp = new JButton("Choose inp file");
JButton analayze = new JButton("Analayze");
DefectFileReader[] dfReader;
Document[] docArray;
boolean DFloaded = false;
boolean LOGloaded = false;
boolean INPloaded = false;
Checkbox recipeName;
Checkbox inspectionDuration;
Checkbox area;
Checkbox numberOfDefects;
Checkbox numberOfDefectsPerDetector;
Checkbox sensetivityName;
Checkbox SlicesDetected;
private static int rowIndex = 2;
private static int cellIndex = 4;
FileOutputStream fos;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("analyze_result");
Row row = sheet.createRow(rowIndex);
Cell cell = row.createCell(cellIndex);
XSSFCellStyle csForFirstWrite = workbook.createCellStyle();
XSSFCellStyle csForSecondWrite = workbook.createCellStyle();
XSSFFont fontForBold = workbook.createFont();
XSSFFont fontNotForBold = workbook.createFont();
String totalDuration = "00:00:00";
private int currentFolder = 0;
//TwoRoot t;
JProgressBar pBar = new JProgressBar();
Frame frame = new Frame("Progress Bar");
MyprogressBar taskBar;
/* creating the main panel of the frame - divided to 3 parts. in the north pictures , in the west checkbox , in the east the file chooser */
public MyPanel(){
this.setLayout(new BorderLayout());
this.add(pictureInNorth() , BorderLayout.NORTH);
this.add(checkBoxPanel() , BorderLayout.WEST);
this.add(chooseFilesPanel() , BorderLayout.EAST);
//pBar.setForeground(Color.black);
//pBar.setStringPainted(true);
//this.add(pBar , BorderLayout.SOUTH);
}
/* creating the north panel with the picture */
private JPanel pictureInNorth(){
JPanel toReturn = new JPanel();
toReturn.setBackground(Color.black);
JButton analayzerPic = new JButton(new ImageIcon(new ImageIcon("C:/Users/uvalerx073037/workspace/Analayzer_GUI_Ver2/src/Images/vXqyQkOv.jpeg")
.getImage().getScaledInstance(600, 30,
java.awt.Image.SCALE_SMOOTH)));
analayzerPic.setBackground(Color.black);
toReturn.add(analayzerPic);
return toReturn;
}
/* creating the checkBox in the west */
private JPanel checkBoxPanel(){
recipeName = new Checkbox("Recipe Name" , false);
inspectionDuration = new Checkbox("Inspection Duration" , false);
area = new Checkbox("Area" , false);
numberOfDefects = new Checkbox("Number Of Defects" , false);
numberOfDefectsPerDetector = new Checkbox("Number Of Defects Per Detector", false);
sensetivityName = new Checkbox("Sensetivity Name", false);
SlicesDetected = new Checkbox("Slices were detected" , false);
JPanel toReturn = new JPanel();
toReturn.setLayout(new BoxLayout(toReturn, BoxLayout.Y_AXIS));
toReturn.add(recipeName);
toReturn.add(inspectionDuration);
toReturn.add(numberOfDefects);
toReturn.add(numberOfDefectsPerDetector);
toReturn.add(sensetivityName);
toReturn.add(SlicesDetected);
toReturn.add(area);
return toReturn;
}
/*creating the file chooser in the east */
private Box chooseFilesPanel(){
MyActionListener lis = new MyActionListener();
chooseDF.addActionListener(lis);
chooseInp.addActionListener(lis);
chooseLog.addActionListener(lis);
analayze.addActionListener(lis);
analayze.setForeground(Color.BLUE);
Box toReturn = Box.createVerticalBox();
toReturn.add(Box.createGlue());
toReturn.add(chooseDF);
toReturn.add(Box.createGlue());
toReturn.add(chooseLog);
toReturn.add(Box.createGlue());
toReturn.add(chooseInp);
toReturn.add(Box.createGlue());
toReturn.add(analayze).setSize(50,50);
return toReturn;
}
/* function to check after the user clicked on the analyze button if all the conditions are OK */
public Boolean isValidToStart(){
if(DFloaded == false && LOGloaded == false && INPloaded == false){
JOptionPane.showMessageDialog(null, "NO FILE WAS LOADED!!!", "User Error" , JOptionPane.ERROR_MESSAGE);
return false;
}
if(recipeName.getState() == false && inspectionDuration.getState() == false && area.getState() == false &&
numberOfDefects.getState() == false && numberOfDefectsPerDetector.getState() == false && sensetivityName.getState() == false){
JOptionPane.showMessageDialog(null , "NO CHECK BOX WAS MARKED!!!" + "\n" + "WHAT DATA WOULD YOU LIKE TO COLLECT?" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(area.getState() == true && (LOGloaded == false || DFloaded == false || INPloaded == false)){
JOptionPane.showMessageDialog(null , "IF YOU WANT TO COLLECT AERA YOU NEED TO CHOOSE INP + LOG + DEF" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(SlicesDetected.getState() == true && LOGloaded == false){
JOptionPane.showMessageDialog(null , "You need to load the LOG in order to get the amount of slices were detected!" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
else
return true;
}
/* build the row of the titles , only what the user marked in the check box */
private void firstWriteToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontForBold.setBold(true);
csForFirstWrite.setFont(fontForBold);
csForFirstWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.lightGray));
csForFirstWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForFirstWrite.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
if(recipeName.getState() == true){
row = sheet.createRow(rowIndex - 1);
row.createCell(cellIndex).setCellValue("Recipe Name: " + curDF.getRecipeName());
sheet.autoSizeColumn(cellIndex);
}
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex).setCellValue("inspection index");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
if(numberOfDefects.getState() == true){
row.createCell(cellIndex).setCellValue("Total Defects");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
toOtherFunc = curDF.getDetectorNames();
for(int i=0; i < toOtherFunc.size() ; i++){
row.createCell(cellIndex).setCellValue(toOtherFunc.get(i));
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
}
if(sensetivityName.getState() == true){
row.createCell(cellIndex).setCellValue("sensetivity Name");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(LOGloaded == true){
row.createCell(cellIndex).setCellValue("Slices were detected");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true){
row.createCell(cellIndex).setCellValue("Inspection Duration");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
for (Row row : sheet){
for (Cell cell_local : row){
cell_local.setCellStyle(csForFirstWrite);
}
}
System.out.println("row index is: " + rowIndex + "cell index is: " + cellIndex);
}
/* fill the excel in the data were collected */
private void writeToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontNotForBold.setBold(false);
csForSecondWrite.setFont(fontNotForBold);
csForSecondWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.white));
csForSecondWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForSecondWrite.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderTop(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderRight(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellIndex = 4;
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++).setCellValue("inspection_" + (rowIndex - 3));
if(numberOfDefects.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getTotalDefects());
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
int[] toPrintNumber = new int[toOtherFunc.size()];
toOtherFunc = curDF.getDetectorNames();
System.out.println(toOtherFunc);
toPrintNumber = curDF.getDefectPerDetector(toOtherFunc);
for(int i=0; i < toOtherFunc.size() ; i++)
row.createCell(cellIndex++).setCellValue(toPrintNumber[i]);
}
if(sensetivityName.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getSensetivityName());
if(LOGloaded == true){
LogFileReader logReader = new LogFileReader(LOG , curDF.getInspectionEndTime());
ArrayList<String> toLog = curDF.getRunsIndex();
String toPrint = "";
for(int i=0 ; i < toLog.size() ; i = i+2)
toPrint += toLog.get(i) + ": " + logReader.diagnozeLog(toLog.get(i+1)) + " ";
if(toPrint.equals(""))
row.createCell(cellIndex).setCellValue("The data of this run is not in this log!");
else
row.createCell(cellIndex).setCellValue(toPrint);
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true)
row.createCell(cellIndex++).setCellValue(curDF.inspectionDuration());
for (Row row : sheet){
if( row.getRowNum() > 2){
for (Cell cell_local : row){
cell_local.setCellStyle(csForSecondWrite);
}
}
}
System.out.println("row index is: " + rowIndex + " cell index is: " + cellIndex);
}
/* adding the inspection time of the current run to the total time */
public String sumTimes(String time1) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.printZeroAlways()
.appendHours()
.appendLiteral(":")
.appendMinutes()
.appendLiteral(":")
.appendSeconds()
.toFormatter();
org.joda.time.Period period1 = formatter.parsePeriod(time1);
org.joda.time.Period period2 = formatter.parsePeriod(totalDuration);
return formatter.print(period2.plus(period1).normalizedStandard());
}
public void initializeFrame(){
frame.setSize(300, 100);
pBar.setForeground(Color.black);
pBar.setStringPainted(true);
frame.add(pBar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyprogressBar extends SwingWorker<Void, Integer> {
JProgressBar pBar;
int max;
int currentFolder;
public MyprogressBar(JProgressBar curBar , int max , int currentFolder){
this.pBar = curBar;
this.max = max;
this.currentFolder = currentFolder;
}
public void done(){
}
#Override
protected Void doInBackground() throws Exception {
System.out.println("i'm in background");
double i = currentFolder;
double t = DFLIST.length;
double toSetInDouble = (i/t);
int toSet = (int) (toSetInDouble * 100);
pBar.setValue(toSet);
System.out.println(toSet);
repaint();
Thread.sleep(10);
publish(toSet);
return null;
}
}
/* adding listener to all of the buttons and check boxes */
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource() == chooseDF){
File directory;
FilenameFilter f = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.length()<=2;
}
};
FilenameFilter def = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".def");
}
};
JFileChooser chooser = new JFileChooser(System.getProperties().getProperty("user.dir"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
DFloaded = true;
directory = chooser.getSelectedFile();
File[] fileList = directory.listFiles(f);
Arrays.sort(fileList , new NaturalOrderComparator());
DFLIST = new File[fileList.length];
for(int i = 0 ; i<fileList.length ; i++){
File[] tmp = fileList[i].listFiles(def);
for(int j=0 ; j<tmp.length ; j++)
DFLIST[i] = tmp[j];
}
}
}
if(click.getSource() == chooseInp){
JFileChooser fc2 = new JFileChooser();
if (fc2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
INPloaded = true;
INP = fc2.getSelectedFile();
}
}
if(click.getSource() == chooseLog){
JFileChooser fc3 = new JFileChooser();
if(fc3.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
LOGloaded = true;
LOG = fc3.getSelectedFile();
}
}
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
initializeFrame();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for( ; currentFolder < DFLIST.length ; currentFolder++){
new MyprogressBar(pBar, 100, currentFolder + 1).execute();
frame.repaint();
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[currentFolder].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[currentFolder] = (Document) db.parse(DFLIST[currentFolder]);
docArray[currentFolder].getDocumentElement().normalize();
dfReader[currentFolder] = new DefectFileReader(DFLIST[currentFolder] , docArray[currentFolder]);
dfReader[currentFolder].getRunsIndex();
totalDuration = sumTimes(dfReader[currentFolder].inspectionDuration());
if(currentFolder==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(currentFolder!=0)
writeToExcel(dfReader[currentFolder] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[currentFolder] = null;
dfReader[currentFolder].clearDfReader();
docArray[currentFolder] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
#Udi it would have been really great if you could have pasted a structured code. However, with whatever code you pasted, here is an indicative solution using swingworker. You just need to call your whole actionPerformed() code from doInBackground() of swingworker. Hope it helps.
Moreover, I find the java docs of swingworker a very useful to understand how it works. Examples are very simple yet well explained.
https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html
// use this code inside actionPerformed()
new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
// all your code goes here
for( ; currentFolder < DFLIST.length ; currentFolder++){
double f = currentFolder + 1;
double t = DFLIST.length;
double currentPercentInDouble = (f / t);
int currentPercent = (int) (currentPercentInDouble * 100);
// send the current progress to progress bar. This needs to be updated to progress bar in process() method
publish(currentPercent)
}
// rest of the code
}
#Override
protected void process(List<V> chunks) {
// update the progress bar here
}
}.execute();
Related
How to take the values of the dynamic textfield?
I suppose to set number of textfields I want at beginning of my program and set the values in this fields and write it into txt file
// this is the foreach loop suppose to take the values and send them to addburst function
for( JTextField f : bt )
{
Burst b = new Burst();
b.addBurst(Integer.parseInt(f.getText()));
}
*addburst function
public boolean addBurst(int x) {
if (FManger.write(x, BurstFileName, true)) {
return true;
} else {
return false;
}
}
*Write Function
public boolean write(int Query, String FilePath, boolean appendType) {
PrintWriter writter = null;
try {
System.out.print("\nwritting in ! " + FilePath);
writter = new PrintWriter(new FileWriter(new File(FilePath),
appendType));
writter.println(Query);
System.out.println(" ... Done ! ");
return true;
} catch (IOException e) {
System.out.println(e);
} finally {
writter.close();
}
return false;
}
I added the dynamic textfields by the constructor
public FillData(int x) {
initComponents();
getContentPane().setBackground(Color.ORANGE);
PnoPanel.setLayout(new GridLayout(x,2));
BuPanel.setLayout(new GridLayout(x,2));
ArrPanel.setLayout(new GridLayout(x,2));
JLabel ProcessNumber[] = new JLabel[x];
JTextField BurstTime[] = new JTextField[x];
JTextField ArrivalTime[] = new JTextField[x];
for (int i = 0; i < x; i++)
{
ProcessNumber[i] = new JLabel(" Process "+(i+1));
BurstTime[i] = new JTextField();
ArrivalTime[i] = new JTextField();
PnoPanel.add(ProcessNumber[i]);
BuPanel.add(BurstTime[i]);
ArrPanel.add(ArrivalTime[i]);
}
}
x is the number of textfields
So I build a shell that looks like the following
After I click the change path button, I prompt for the path and then set the text. The problem is after doing so new text gets cut off if its too long like so.
I am using a Label to display the path, and the only method I'm using in the listener regarding the Laebl is the setText() method. Is there a way to not have this happen? I am using SWT and prefer to maintain the grid layout so I can have the 2 columns. Any info would be helpful. Thank you.
Here's the code
String unit[] = {"Pixil", "Inch"};
final CustomAttribute realWidth = new CustomAttribute(String.valueOf(obj.getGraph().getWidth(null)));
final CustomAttribute realHeight = new CustomAttribute(String.valueOf(obj.getGraph().getHeight(null)));
double[] sizes = obj.convertToSizes();
if(sizes != null){
realWidth.setValue(sizes[0]);
realHeight.setValue(sizes[1]);
}
final Shell shell = new Shell(d);
shell.setImage(ApplicationPlugin.getImage(ApplicationPlugin.QUATTRO_ICON));
shell.setLayout(new org.eclipse.swt.layout.GridLayout(2,true));
shell.setText(EDIT_IMG_WINDOW_TITLE);
//width info
final Label labelWidth = new Label(shell, SWT.HORIZONTAL);
final Text textWidth = new Text(shell,SWT.SINGLE | SWT.BORDER);
//height info
final Label labelHeight = new Label(shell, SWT.HORIZONTAL);
final Text textHeight = new Text(shell,SWT.SINGLE | SWT.BORDER);
//units info
final Combo unitCombo = new Combo (shell, SWT.READ_ONLY);
final Button ratioBox = new Button (shell, SWT.CHECK);
ratioBox.setText(EDIT_IMG_RADIO);
//path info
final Button pathButton = new Button (shell, SWT.PUSH);
pathButton.setText(EDIT_IMG_PATH);
final Label pathText = new Label(shell, SWT.HORIZONTAL);
pathText.setText(obj.getTextData()[0]);
Button change = new Button (shell, SWT.PUSH);
change.setText(EDIT_IMG_SAVE_BUTTON);
ModifyListener heightListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldHeight = realHeight.getDouble();
double newHeight = Double.parseDouble(textHeight.getText());
double oldWidth = Double.parseDouble(textWidth.getText());
if(unitCombo.getSelectionIndex() == 1){
newHeight = newHeight * designer.getPixilPerInch();
oldWidth = oldWidth * designer.getPixilPerInch();
}
realHeight.setValue(newHeight);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realWidth.setValue(sizes[0]);
else
realWidth.setValue(oldWidth);
if(realHeight.getDouble() > SheetCanvas.sheetYSize)
realHeight.setValue(SheetCanvas.sheetYSize);
if(realHeight.getDouble() < 1)
realHeight.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realHeight.getValue()) / oldHeight;
realWidth.setValue(String.valueOf(realWidth.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textWidth.setText(String.valueOf((int)Math.round(Double.parseDouble(realWidth.getValue()))));
else
textWidth.setText(String.valueOf(Double.parseDouble(realWidth.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
ModifyListener widthListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldWidth = realWidth.getDouble();
double newWidth = Double.parseDouble(textWidth.getText());
double oldHeight = Double.parseDouble(textHeight.getText());
if(unitCombo.getSelectionIndex() == 1){
newWidth = newWidth * designer.getPixilPerInch();
oldHeight = oldHeight * designer.getPixilPerInch();
}
realWidth.setValue(newWidth);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realHeight.setValue(sizes[1]);
else
realHeight.setValue(oldHeight);
if(realWidth.getDouble() > SheetCanvas.sheetYSize)
realWidth.setValue(SheetCanvas.sheetYSize);
if(realWidth.getDouble() < 1)
realWidth.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realWidth.getValue()) / oldWidth;
realHeight.setValue(String.valueOf(realHeight.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textHeight.setText(String.valueOf((int)Math.round(Double.parseDouble(realHeight.getValue()))));
else
textHeight.setText(String.valueOf(Double.parseDouble(realHeight.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
textHeight.addModifyListener(heightListener);
textWidth.addModifyListener(widthListener);
unitCombo.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
realImgListen = false;
if(unitCombo.getSelectionIndex() == 0){
textWidth.setText(String.valueOf((int)Math.rint(realWidth.getDouble())));
textHeight.setText(String.valueOf((int)Math.rint(realHeight.getDouble())));
}
else{
textWidth.setText(String.valueOf(realWidth.getDouble()/designer.getPixilPerInch()));
textHeight.setText(String.valueOf(realHeight.getDouble()/designer.getPixilPerInch()));
}
realImgListen = true;
}
});
change.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
Double width = realWidth.getDouble();
Double height = realHeight.getDouble();
String line1;
if(obj.getTextData() != null)
line1 = obj.getTextData()[0];
else
line1 = null;
String[] textData = {line1,null};
obj.setTextData(textData);
obj.storeSizingInfo(Math.rint(width), Math.rint(height),0);
designer.updateDataFromSource(settings);
designer.repaint();
updatePanelButtons();
shell.close();
}
});
pathButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//path button
String path = null;
path = getPathFromBrowser(FILE_CHOOSER_IMAGE_TITLE_STR,DEFAULT_PATH,acceptedImgFormats,null,SWT.OPEN);
pathText.setText(path);
if(path != null){
String[] paths = settings.getCustomImagePath();
int pathIndex = 0;
for(int i = 0; i < paths.length; i++){
if(obj.getTextData()[0].equals(paths[i]))
pathIndex = i;
}
paths[pathIndex] = path;
settings.setCustomImagePath(paths);
paths = settings.getCustomImageChoices();
paths[pathIndex] = getFileNameFromPath(path);
settings.setCustomImageChoices(paths);
designer.updateDataFromSource(settings);
String[] textData = obj.getTextData();
textData[0] = path;
if(textData.length > 1)
textData[1] = null;
obj.setTextData(textData);
}
}
});
textWidth.setTextLimit(7);
textHeight.setTextLimit(7);
labelWidth.setText(EDIT_IMG_WIDTH);
labelHeight.setText(EDIT_IMG_HEIGHT);
unitCombo.setItems(unit);
unitCombo.select(0);
ratioBox.setSelection(true);
org.eclipse.swt.graphics.Rectangle clientArea = shell.getClientArea();
unitCombo.setBounds(clientArea.x, clientArea.y, 300, 200);
shell.pack();
shell.open();
Shell shellTemp = SWT_AWT.new_Shell(d, designer);
Monitor primary = d.getPrimaryMonitor();
org.eclipse.swt.graphics.Rectangle bounds = primary.getBounds();
org.eclipse.swt.graphics.Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
shell.moveAbove(shellTemp);
shellTemp.dispose();
shell.addListener(SWT.Close, new Listener() {
#Override
public void handleEvent(Event event) {
editingImg();
}
});
realImgListen = false;
textWidth.setText(String.valueOf((int)Double.parseDouble(realWidth.getValue())));
textHeight.setText(String.valueOf((int)Double.parseDouble(realHeight.getValue())));
realImgListen = true;
The width of your columns is currently being set to the width of the widest control - probably 'Maintain Image Ratio'. If you set the the path text to anything longer than that it will be truncated.
You could set a width hint on the path control to set its size:
GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 100; // You choose the width
pathText.setLayoutData(data);
Note that you have specified that the columns are of equal width so this will add similar space to the first column. You might want to switch to unequal width columns.
Alternatively you can ask the Shell to recalculate the size after you set the new text. Just call:
shell.pack();
It looks like that you are redrawing the change path label components and you are not wrapping the label .
That why at the time of redrawing some part of the text is not visible.
Use warping or you can also increase the screen size
So Integer N here is controlled by a JComboBox basically a drop down menu 1-4. My problem is that I get a nullpointerexception error when I initially set N from the box..any ideas how to fix this? I tested it by printing out what N was in both actionlistener instances and it's null in the first one and it's correct in the second one.
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab10 extends JPanel
{
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2;
private JButton load, go,go2;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab10()
{
string = new StringBuilder();
string2 = new StringBuilder();
string3 = new StringBuilder();
string4 = new StringBuilder();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
textarea.setText("");
}
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab10());
frame.pack();
frame.setVisible(true);
}
}
Your question doesn't make sense as written:
Integer N = input.getSelectedIndex()+1;
System.out.println(N);
The println cannot possibly tell you that N is null.
If the expression on the RHS of the = executes without an exception, then N is guaranteed to be non-null. The getSelectedIndex() call returns an int, and the result of the addition will be an int. That will then be autoboxed to an Integer, and autoboxing can NEVER give you a null.
If the expression on the RHS of the = throws an exception, then the println statement won't be executed.
In other words, what you are describing is Impossible.
So what I think is actually happening is one of the following:
Your code is throwing a NullPointerException in the first statement because input is null, and you have misdiagnosed that as meaning that N is null.
This code is sufficiently different from your actual code that it is not possible to understand what is really going on.
You have made a mistake in the compiling / running / deploying of your code, such that you are running a stale binary.
Your code isn't compilable the way it is now. You can't have multiple public classes in the same file. Also, to access the selected index from a JComboBox, this is what your actionPerformed method should look like.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int n = cb.getSelectedIndex();
//etc
}
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");
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.