I have got a form in Java (Swing) loading large amount of data from the database. I want to display a progress bar while the program gets actually loaded.
How can i do it?
The code is as follows:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.applet.*;
import java.util.*;
import java.awt.Color;
public class bookshow extends JFrame implements MouseListener, ActionListener {
JPanel p1, p2, p3;
JLabel l1, l2, l3, l4;
ImageIcon image;
JButton b[] = new JButton[84];
JButton btnocc, btnbook, btnsel;
ResultSet rs;
private JMenuBar menuBar = new JMenuBar();
private JMenuItem exit, home, save;
private JMenu fileMenu, gotoMenu;
public int cnt = 0, x = 150, y = 90, i, j, put = 0, k = 0, avail = 1, point, x1, y1, count = 0, quan;
public static int prev_click = -1, xpos, ypos;
public static int prev[] = new int[5];
public static int pos[][] = new int[5][2];
public String movname, movdate, movtime;
public bookshow() {
avail = 1;
try {
String sql = "Select * from Pass";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
rs = s.executeQuery(sql);
while (rs.next()) {
movname = rs.getString("movname");
movdate = rs.getString("movdate");
movtime = rs.getString("movtime");
quan = Integer.parseInt(rs.getString("Quantity"));
}
} catch (Exception ex) {
System.out.println(ex);
}
try {
String sql = "Delete from Pass";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
s.executeUpdate(sql);
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
setTitle("Select Ticket");
setDefaultCloseOperation(EXIT_ON_CLOSE);
p1 = new JPanel();
getContentPane().add(p1);
p1.setLayout(null);
p1.setBackground(Color.white);
setJMenuBar(menuBar);
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
exit = new JMenuItem("Exit");
exit.addActionListener(this);
fileMenu.add(exit);
exit.setAccelerator(KeyStroke.getKeyStroke('E', Event.CTRL_MASK));
save = new JMenuItem("Save");
save.addActionListener(this);
fileMenu.add(save);
save.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK));
gotoMenu = new JMenu("Go To");
menuBar.add(gotoMenu);
home = new JMenuItem("Home");
//exit.addActionListener(this);
gotoMenu.add(home);
home.setAccelerator(KeyStroke.getKeyStroke('H', Event.CTRL_MASK));
p2 = new JPanel();
p2.setLayout(null);
p2.setBackground(Color.lightGray);
p2.setBounds(100, 50, 500, 20);
p1.add(p2);
l1 = new JLabel("GOLD");
l1.setBounds(240, 0, 100, 20);
p2.add(l1);
l1.setBackground(Color.red);
try {
String sql = "Select * from Book";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
rs = s.executeQuery(sql);
while (rs.next()) {
String getname = rs.getString("MovName");
String getdate = rs.getString("MovDate");
String gettime = rs.getString("MovTime");
if (movname.equalsIgnoreCase(getname) && movdate.equals(getdate) && movtime.equals(gettime)) {
put = 1;
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 14; j++) {
point = 0;
b[cnt] = new JButton();
b[cnt].setBounds(x, y, 20, 20);
b[cnt].setBackground(Color.white);
p1.add(b[cnt]);
if (put == 0) {
try {
String sql = "Insert into Book values('" + movname + "','" + movtime + "','" + movdate + "'," + x + "," + y + ",1)";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
s.executeUpdate(sql);
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
} else {
try {
String sql = "Select * from Book";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
rs = s.executeQuery(sql);
while (rs.next()) {
String getname = rs.getString("MovName");
String getdate = rs.getString("MovDate");
String gettime = rs.getString("MovTime");
avail = Integer.parseInt(rs.getString("Avail"));
if (movname.equalsIgnoreCase(getname) && movdate.equals(getdate) && movtime.equals(gettime)) {
k++;
if (avail == 0 && k == (cnt + 1)) {
b[cnt].setBackground(Color.red);
point = 1;
b[cnt].setEnabled(false);
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
if (point == 0) {
b[cnt].addMouseListener(this);
}
cnt++;
x = x + 30;
k = 0;
}
x = 150;
y = y + 40;
}
y = 300;
x = 150;
p3 = new JPanel();
p3.setLayout(null);
p3.setBackground(Color.lightGray);
p3.setBounds(100, 260, 500, 20);
p1.add(p3);
l2 = new JLabel("ECONOMY");
l2.setBounds(220, 0, 100, 20);
p3.add(l2);
l2.setBackground(Color.red);
for (i = 1; i <= 2; i++) {
for (j = 1; j <= 14; j++) {
point = 0;
b[cnt] = new JButton();
b[cnt].setBounds(x, y, 20, 20);
b[cnt].setBackground(Color.white);
p1.add(b[cnt]);
if (put == 0) {
try {
String sql = "Insert into Book values('" + movname + "','" + movtime + "','" + movdate + "'," + x + "," + y + ",1)";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
s.executeUpdate(sql);
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
} else {
try {
String sql = "Select * from Book";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
rs = s.executeQuery(sql);
while (rs.next()) {
String getname = rs.getString("MovName");
String getdate = rs.getString("MovDate");
String gettime = rs.getString("MovTime");
avail = Integer.parseInt(rs.getString("Avail"));
if (movname.equalsIgnoreCase(getname) && movdate.equals(getdate) && movtime.equals(gettime)) {
k++;
if (avail == 0 && k == (cnt + 1)) {
b[cnt].setBackground(Color.red);
point = 1;
b[cnt].setEnabled(false);
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
if (point == 0) {
b[cnt].addMouseListener(this);
}
cnt++;
x = x + 30;
k = 0;
}
x = 150;
y = y + 40;
}
image = new ImageIcon("screen.jpg");
l3 = new JLabel(image);
l3.setBounds(70, y + 20, 600, 54);
p1.add(l3);
l4 = new JLabel("Seat to Occupy");
l4.setBounds(140, 490, 100, 15);
p1.add(l4);
btnocc = new JButton();
btnocc.setBounds(260, 490, 15, 15);
btnocc.setBackground(Color.white);
p1.add(btnocc);
l4 = new JLabel("Booked seat");
l4.setBounds(320, 490, 80, 15);
p1.add(l4);
btnbook = new JButton();
btnbook.setBounds(410, 490, 15, 15);
btnbook.setBackground(Color.red);
p1.add(btnbook);
l4 = new JLabel("Current selection");
l4.setBounds(460, 490, 100, 15);
p1.add(l4);
btnsel = new JButton();
btnsel.setBounds(570, 490, 15, 15);
btnsel.setBackground(Color.green);
p1.add(btnsel);
setSize(770, 650);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
Cursor mycursor = new Cursor(Cursor.HAND_CURSOR);
setCursor(mycursor);
}
public void mouseExited(MouseEvent e) {
Cursor mycursor = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(mycursor);
}
public void mouseClicked(MouseEvent e) {
int row, col, ex;
for (i = 0; i < cnt; i++) {
if (e.getSource().equals(b[i])) {
if (count < quan) {
prev[count] = i;
b[prev[count]].setBackground(Color.green);
row = i / 14;
col = i % 14;
x1 = 150 + (30 * col);
if (row >= 0 && row <= 3) {
y1 = 90 + (40 * row);
} else {
y1 = 300 + (40 * (row - 4));
}
pos[count][0] = x1;
pos[count][1] = y1;
count++;
} else {
ex = prev[0];
b[ex].setBackground(Color.white);
for (int j = 0; j <= (count - 1); j++) {
prev[j] = prev[j + 1];
pos[j][0] = pos[j + 1][0];
pos[j][1] = pos[j + 1][1];
}
prev[count - 1] = i;
row = i / 14;
col = i % 14;
x1 = 150 + (30 * col);
if (row >= 0 && row <= 3) {
y1 = 90 + (40 * row);
} else {
y1 = 300 + (40 * (row - 4));
}
pos[count - 1][0] = x1;
pos[count - 1][1] = y1;
for (int j = 0; j <= (count - 1); j++) {
b[prev[j]].setBackground(Color.green);
}
count = quan;
}
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
if (count != quan) {
JOptionPane.showMessageDialog(null, "Please select the exact numbers of seat", "Error", JOptionPane.ERROR_MESSAGE);
} else {
for (i = 0; i < count; i++) {
try {
String sql = "Update Book set Avail=0 where MovName='" + movname + "' AND MovDate='" + movdate + "' AND MovTime='" + movtime + "' AND X=" + pos[i][0] + " AND y=" + pos[i][1] + " ";
String url = "jdbc:odbc:tbs";
Connection con = DriverManager.getConnection(url);
Statement s = con.createStatement();
s.executeUpdate(sql);
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
setVisible(false);
bookmain bm = new bookmain();
}
}
}
}
public static void main(String args[]) {
bookshow mm = new bookshow();
}
}
Java progress bar tutorial should help.
Another example can be found in SwingWorker java docs entry.
Instead of calling the nextPrimeNumber() it could be in your case processNextBook().
To work out the progress you could use a similar idea as bellow changing to the variables to something meaningful in your code eg. setProgress(100 * booksProcessed.size() / books.size());
The code bellow should give you the basic idea how to achieve what your looking for.
class PrimeNumbersTask extends
SwingWorker<List<Integer>, Integer> {
PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
//initialize
}
#Override
public List<Integer> doInBackground() {
while (! enough && ! isCancelled()) {
number = nextPrimeNumber();
publish(number);
setProgress(100 * numbers.size() / numbersToFind);
}
}
return numbers;
}
#Override
protected void process(List<Integer> chunks) {
for (int number : chunks) {
textArea.append(number + "\n");
}
}
}
JTextArea textArea = new JTextArea();
final JProgressBar progressBar = new JProgressBar(0, 100);
PrimeNumbersTask task = new PrimeNumbersTask(textArea, N);
task.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer)evt.getNewValue());
}
}
});
JProgressBar is your choice
Here is a short, self-contained example of using SwingWorker to query a database and update a JProgressBar.
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
Every time a new swing windows opens in code that is executed in a for loop.
I have some code that is runned in a for loop.
The for loop gives every time a new value to my multidimensional array.
But, every time my for loop creates open's a new windows but does not close the old window.
How can I solve this issues? I want to close the old windows and refresh my window with the new actual values or that only one Windows is opened and that the new values of the for loop refreshes the values inside the table based on the multidimensional array names data.
Because now more than 200 (every second a new windows is opened) windows are opened and after 1 minute I don’t see new values appearing on my window and the computer freezes.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.Timer;
public class UAppWin {
private static final int Status_COL = 1;
String[][] data = new String[3][3];
int dptr;
String[] cols = { "Feature", "Status", "Value" };
public UAppWin(String label, int nphases) {
System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
}
void newCycle(int phasenr) {
System.out.println("UApp =============================");
dptr = 0;
}
void addEntry(int index, double tim, String label, int status, double dval) {
System.out.println("Uapp [" + index + "] " + label + "(" + status + ") " + dval);
data[dptr][0] = label;
data[dptr][1] = "" + status;
data[dptr][2] = "" + dval;
dptr++;
}
void addMessage(String msg) {
System.out.println("Uapp alert: " + msg);
// rode balk met bericht
}
void deleteMessage() {
}
void endCycle() {
System.out.println("UApp =============================");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
}
});
}
private JTable getTable() {
DefaultTableModel model = new DefaultTableModel(data, cols);
return new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(300, 150);
}
};
}
private static JTable getNewRenderedTable(final JTable table) {
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
String Status = (String) table.getModel().getValueAt(row, Status_COL);
if ("0".equals(Status)) {
setBackground(Color.GREEN);
setForeground(Color.BLACK);
} else if ("2".equals(Status)) {
setBackground(Color.RED);
setForeground(Color.BLACK);
} else {
setBackground(Color.YELLOW);
setForeground(Color.BLACK);
}
return this;
}
});
return table;
}
}
The second part of the code edited:
public class HmOpIntf {
static final String DFLT_IP_ADDR = "127.0.0.1";
static final int DFLT_IP_PORT = 9502;
static final int DFLT_MB_UNIT = 1;
static final int DFLT_POLL_TM = 2;
public static ModbusClient connectPLC(String ipAddr, int port, int unitNr)
{
ModbusClient mc = null;
System.out.println("Connecting to " + ipAddr + " port " + port + " unit " + unitNr);
try {
mc = new ModbusClient(ipAddr, port);
mc.Connect();
mc.setUnitIdentifier((byte)unitNr);
mc.WriteSingleCoil(0, true);
} catch (Exception e) {
System.err.println("*** connectPLC: exception caught");
return null;
}
System.out.println("Connected!");
return mc;
}
public static void disconnectPLC(ModbusClient mc)
{
mc = null;
}
public static String MyConvertRegistersToString(int[] regs, int startIx, int len) {
char[] ca = new char[len];
for (int i = 0; i < len; i++) {
ca[i] = (char) regs[startIx + i];
}
return new String(ca);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ModbusClient mc = null;
String ipAddr = DFLT_IP_ADDR;
int ipPort = DFLT_IP_PORT;
int mbUnit = DFLT_MB_UNIT;
int pollTime = DFLT_POLL_TM;
int tlBase = 2000; /* Offset in PLC's holding registry */
int tlBlocksz = 84;
String[] tlLabel = {"T4 mould", "T injection valve"}; /* Default */
int trafLightNum = tlLabel.length;
String[] colors = { "green", "yellow", "red" };
int status;
// Notifications.infoBox("Hello world!", "Welcome message");
if (args != null && args.length > 0) {
if (args.length < 4) {
System.err.println("*** Error (" + args.length +"): arguments are: ip-addr port unit polltime label-1 ...");
System.exit(1);
}
ipAddr = args[0];
ipPort = Integer.parseInt(args[1]);
mbUnit = Integer.parseInt(args[2]);
pollTime = Integer.parseInt(args[3]);
}
if (args.length > 4) {
trafLightNum = args.length - 4;
tlLabel = new String[trafLightNum];
for (int i = 0; i < trafLightNum; i++) {
tlLabel[i] = args[i + 4];
}
}
// Scope sc = new Scope();
// sc.runScope();
if ((mc = connectPLC(ipAddr, ipPort, mbUnit)) == null) {
System.out.println("*** Failed to connect to PLC");
System.exit(1);
}
TrafficLight tlLast = null;
int[] values = new int[tlBlocksz];
TrafficLight[] tl = new TrafficLight[trafLightNum];
Scope[] sc = new Scope[trafLightNum];
Notifications nots = new Notifications(trafLightNum);
int locX, locY;
for (int i = 0; i < tl.length; i++) {
tl[i] = new TrafficLight();
tl[i].setLbl(tlLabel[i]);
tl[i].setVisible(true);
if (tlLast != null) {
locX = tlLast.getLocation().x;
locY = tlLast.getLocation().y + tlLast.getHeight();
} else {
locX = tl[i].getLocation().x;
locY = tl[i].getLocation().y;
}
tl[i].setLocation(locX, locY);
sc[i] = new Scope(tlLabel[i], locX + tl[i].getWidth(), locY, 320, 290 /* tl[i].getHeight()-80 */ );
sc[i].setGrid(10, 5);
tlLast = tl[i];
}
UAppWin uw = new UAppWin("RTM Facility", 5);
int phase = 1;
// tl2.setVisible(true); tl2.setLocation(tl.getWidth(), 0);
try {
double t = 0.0;
int[] dreg = new int[2];
for (;;) {
uw.newCycle(phase);
for (int i = 0; i < tl.length; i++) {
values = mc.ReadHoldingRegisters(tlBase + i * tlBlocksz, values.length);
status = values[0];
if (status >= 0 && status < colors.length) {
// System.out.println(i + ": " + colors[status]);
if (status == 0) tl[i].greenOn();
else if (status == 1) tl[i].yellowOn();
else tl[i].redOn();
}
else
System.out.println("Status value " + i + " out of range: " + status);
dreg[0] = values[1]; dreg[1] = values[2];
double dval = (double) ModbusClient.ConvertRegistersToFloat(dreg);
sc[i].addValue(t, dval);
sc[i].drawSignal();
// w.addEntry(int i, float t, String label, int status (o = groen, 1 = yellow, 2 = red), float dval);
uw.addEntry(i, t, tlLabel[i], status, dval);
int msglen = values[3];
if (msglen > 0) {
String msg = MyConvertRegistersToString(values, 4, msglen);
System.out.println("DEBUG: received message for " + tlLabel[i] + ": " + msg);
nots.notify(i, msg);
uw.addMessage(msg);
}
else {
nots.notify(i, null);
uw.deleteMessage();
}
// System.out.println("Received for set " + i + ": status=" + status + " dval=" + dval + " msglen=" + msglen);
}
uw.endCycle();
t += 1.0;
Thread.sleep(pollTime * 500);
}
} catch (Exception e) {
System.out.println("*** Failed to communicate with PLC - exit");
System.exit(1);
}
try {
mc.Disconnect();
} catch (IOException e) {
System.out.println("*** Failed to disconnect from PLC");
}
}
}
The UappWin seems to be tied to a window. So when you create it, also create a JFrame. Then nothing else would need to change except the run method and declaring the JFrame.
public class UAppWin {
private JFrame frame;
public UAppWin(String label, int nphases) {
//System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
JLabel label = new JLabel("UApp \"" + label + "\" (" + nphases + " phases)");
frame = new JFrame("title");
frame.add(label);
frame.setVisible(true);
}
Then when you create the window.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
frame.setContentPane( new JScrollPane( getNewRenderedTable( getTable() ) );
frame.setVisible(true);
}
});
I am trying to make a JFrame program that interfaces a binary-decimal-hexadecimal converter with buttons. A part of this, I would like to draw circles to represent binary numbers in a row of circles with a filled circle representing a one and an empty circle representing a zero. However, when I try to call repaint to draw anything, it does not execute the paintComponent() method, which I know because it does not perform the print statement inside of it. Full code below:
package e2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
public class DecBin extends JPanel {
String theText = "IT WORKS";
int style = Font.BOLD; // bold only
Font font = new Font("Arial", style, 40);
DecBin() {
JFrame f = new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
Font font = new Font("Arial", style, 40);
JLabel textLabel = new JLabel(theText);
textLabel.setFont(font);
JButton b = new JButton("DectoBin");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToBin(num) + " in binary";
textLabel.setText(theText);
}
});
f.add(b);
JButton d = new JButton("BintoDec");
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
System.out.print("The decimal form of " + msg + " is " + binToDec(msg));
theText = msg + " is " + binToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(d);
JButton hd = new JButton("hexToDec");
hd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a hexadecimal number");
theText = msg + " is " + hexToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(hd);
JButton dh = new JButton("DectoHex");
dh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToHex(num) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(dh);
JButton bh = new JButton("BinToHex");
bh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
theText = msg + " is " + decToHex(binToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(bh);
JButton hb = new JButton("HexToBin");
hb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a Hexadecimal number");
theText = msg + " is " + decToBin(hexToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(hb);
JButton c = new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.add(textLabel, BorderLayout.SOUTH);
f.setVisible(true);
}
public static void main(String[] args) {
new DecBin();
}
static String decToBin(int d) {
StringBuilder binary = new StringBuilder("");
while (d != 0) {
binary.insert(0, d % 2);
d = d / 2;
}
return binary.toString();
}
static int binToDec(String b) {
int total = 0;
int x;
for (int i = b.length(); i > 0; i--) {
x = Integer.parseInt(Character.toString(b.charAt(i - 1)));
if (x == 1) {
total += Math.pow(2, b.length() - i);
}
}
return total;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
static String decToHex(int d) {
StringBuilder Hex = new StringBuilder("");
while (d != 0) {
int remainder = d % 16;
if (remainder < 10) {
Hex.insert(0, d % 16);
} else if (remainder == 10) {
Hex.insert(0, 'A');
} else if (remainder == 11) {
Hex.insert(0, 'B');
} else if (remainder == 12) {
Hex.insert(0, 'C');
} else if (remainder == 13) {
Hex.insert(0, 'D');
} else if (remainder == 14) {
Hex.insert(0, 'E');
} else if (remainder == 15) {
Hex.insert(0, 'F');
}
d = d / 16;
}
return Hex.toString();
}
static int hexToDec(String b) {
int total = 0;
int len = b.length();
for (int i = len - 1; i >= 0; i--) {
if (b.charAt(i) == 'A') {
total += 10 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'B') {
total += 11 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'C') {
total += 12 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'D') {
total += 13 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'E') {
total += 14 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'F') {
total += 15 * Math.pow(16, len - i - 1);
} else {
total += Character.getNumericValue(b.charAt(i)) * Math.pow(16, len - i - 1);
}
}
return total;
}
}
Pertinent code in my opinion is:
DecBin() {
JFrame f=new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000,1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton c =new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.setVisible(true);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
public static void main(String[] args) {
new DecBin();
}
I have spent hours researching this and have yet to find a solution that will get "painted components" to print.
You do not appear to be adding your DecBin panel to any other UI element. It therefore has no reason to be painted.
You should avoid initializing JFrames inside the constructor of your JPanel child class - it should really be the other way around. That will make things easier to understand (and to debug).
Firstly, I would like to say I am not asking for an answer more so advice so I can learn from this problem. Every time I run my code I get Array Index Out of Bounds on Line 254 of the ArrayOperations java file.
if (SearchKey == tempArray[middle])
I have added as many checks as I possibly can to this code and also have commented it as much as possible for your ease. Once again I am looking for advice on this not just a direct answer if possible. The Error always seems to give me the negative version of 1/2 of my data items
ex: 100,000 data items, Array Index Out of Bounds: -49,999.
import javax.swing.*;
// File-related imports
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class ArrayOperations
{
// File Parameters
String DataFilePath;
String DataFileName;
String KeysFilePath;
String KeysFileName;
int NumberOfDataItems;
int NumberOfKeys;
int N;
int BucketHashArraySize;
int NoBuckets;
//Array
int[] OriginalArray = new int[1000000];
int[] SortedArray = new int[1000000];
int[] HashedArray = new int[2000000];
int[] BucketHashedArray = new int[2000000];
int[] KeysArray = new int[1000000];
long SSAverageAccessTime;
long SSAverageCompSuc;
long SSAverageCompFailed;
long SSNumberKeysSuc;
long SSNumberKeysFailed ;
long BSAverageAccessTime;
long BSAverageCompSuc ;
long BSAverageCompFailed;
long BSNumberKeysSuc ;
long BSNumberKeysFailed ;
long HSAverageAccessTime;
long HSAverageCompSuc ;
long HSAverageCompFailed;
long HSNumberKeysSuc ;
long HSNumberKeysFailed ;
public ArrayOperations()
{
// File Parameters
DataFilePath = null;
DataFileName = null;
KeysFilePath = null;
KeysFileName = null;
NumberOfDataItems=0;
NumberOfKeys =0;
N =0;
BucketHashArraySize = 0;
NoBuckets =0;
// Statistics
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
}
public void ReadDataFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
DataFilePath = chooser.getSelectedFile().getPath();
DataFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (DataFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(DataFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
OriginalArray[index] = integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfDataItems = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfDataItems = 0;
}
public void ReadKeysFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Keys File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
KeysFilePath = chooser.getSelectedFile().getPath();
KeysFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (KeysFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(KeysFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
KeysArray[index]= integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfKeys = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfKeys = 0;
}
public void SequentialSearch()
{
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d<NumberOfDataItems; d++)
{
TotalNumberOfComparisons++;
if (SearchKey == OriginalArray[d])
{
found = true;
}
if (found)break;
}
if(found)
{
SSAverageCompSuc = SSAverageCompSuc + TotalNumberOfComparisons;
SSNumberKeysSuc ++;
}
else
{
SSAverageCompFailed = SSAverageCompFailed + TotalNumberOfComparisons;
SSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
SSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
SSAverageAccessTime = 0;
if(SSNumberKeysSuc != 0)
SSAverageCompSuc = Math.round (SSAverageCompSuc / SSNumberKeysSuc) ;
else
SSAverageCompSuc = 0;
if (SSNumberKeysFailed != 0)
SSAverageCompFailed = Math.round (SSAverageCompFailed / SSNumberKeysFailed) ;
else
SSNumberKeysFailed = 0;
return;
}
public void BinarySearch()
{
// makes a temporary array the length of the number of data items we gave it int[] tempArray = new int[NumberOfDataItems];
// copies a portion of the original array (origionalArray = new int[1000000] above) that has the data inputs
// we are copying only the portion of the original array the was given the data inputs when we opened the data item .txt
for (int i = 0; i < NumberOfDataItems; i ++)
{
tempArray[i]=OriginalArray[i];
}
// takes the temporary array and sorts it
java.util.Arrays.sort(tempArray);
BSAverageAccessTime = 0;
BSAverageCompSuc = 0;
BSAverageCompFailed = 0;
BSNumberKeysSuc = 0;
BSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
int low = 0;
int high = tempArray.length-1;
// sets the midpoint
int middle = (low-high)/2;
for(int k = 0; k<NumberOfKeys; k++)
{
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d< Math.log(tempArray.length -1); d++)
{
TotalNumberOfComparisons++;
// makes sure low doesn't go out of bounds
if (low < 0)
{
low = 0;
}
// make sure high doesn't go out of bounds
if(high >= tempArray.length)
{
high = tempArray.length-1;
}
// checks the midpoint against the key we are using
if (SearchKey == tempArray[middle])
{
found = true;
}
// makes sure that if the midpoint doesn't equal the key we get false
else
if (low == high && SearchKey != tempArray[middle])
{
found = false;
}
// if the key is greater than the middle we check the upper portion
else
if (SearchKey > tempArray[middle])
{
low = (middle +1);
}
// if the key is less than the middle we check the lower portion
else
if (SearchKey < tempArray[middle])
high = (middle -1);
if (found)break;
}
if(found)
{
BSAverageCompSuc = BSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
BSAverageCompFailed = BSAverageCompFailed + TotalNumberOfComparisons;
BSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
BSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
BSAverageAccessTime = 0;
if(BSNumberKeysSuc != 0)
BSAverageCompSuc = Math.round (BSAverageCompSuc / BSNumberKeysSuc) ;
else
BSAverageCompSuc = 0;
if (BSNumberKeysFailed != 0)
BSAverageCompFailed = Math.round (BSAverageCompFailed / BSNumberKeysFailed) ;
else
BSNumberKeysFailed = 0;
return;
}
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
}
public int FindPrime()
{
return 0;
}
public void Initialize()
{
}
public void BHSearch()
{
}
}
Here is the Java GUI Code:
// GUI-related imports
import java.awt.*;
import java.awt.event.*;
// File-related imports
import java.io.IOException;
public class Project04 extends Frame implements ActionListener
{
ArrayOperations arr = new ArrayOperations();
String command = "";
public static void main(String[] args)
{
Frame frame = new Project04();
frame.setResizable(false);
frame.setSize(900,620);
frame.setVisible(true);
}
public Project04()
{
setTitle("Search Routines");
// Create Menu Bar and menu items
MenuBar mb = new MenuBar();
setMenuBar(mb);
// Create Menu Group Labeled "File"
Menu FileMenu = new Menu("File");
// Add it to Menu Bar
mb.add(FileMenu);
// Create Menu Items
// Add action Listener
// Add to "File" Menu Group
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
FileMenu.add(miOpen);
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
FileMenu.add(miExit);
// Create Menu Group Labeled "File"
Menu SearchMenu = new Menu("Search");
// Add it to Menu Bar
mb.add(SearchMenu);
// Create Menu Items
// Add action Listener
// Add to "Search" Menu Group
MenuItem miSequentialSearch = new MenuItem("Sequential Search");
miSequentialSearch.addActionListener(this);
SearchMenu.add(miSequentialSearch);
MenuItem miBinarySearch = new MenuItem("Binary Search");
miBinarySearch.addActionListener(this);
SearchMenu.add(miBinarySearch);
MenuItem miHashedSearch = new MenuItem("Hashed Search");
miHashedSearch.addActionListener(this);
SearchMenu.add(miHashedSearch);
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// register listeners
this.addWindowListener(l);
this.addComponentListener(k);
}
//******************************************************************************
// called by windows manager whenever the application window performs an action
// (select a menu item, close, resize, ....
//******************************************************************************
public void actionPerformed (ActionEvent ev)
{
// figure out which command was issued
command = ev.getActionCommand();
// take action accordingly
if("Open".equals(command))
{
try
{
arr.ReadDataFile();
arr.ReadKeysFile();
}
catch (IOException ioe)
{
System.exit(0);
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
else
if("Sequential Search".equals(command))
{
arr.SequentialSearch();
repaint();
}
if("Binary Search".equals(command))
{
arr.BinarySearch();
repaint();
}
if("Hashed Search".equals(command))
{
arr.HashedSearch();
repaint();
}
if("Bucket Hashed Search".equals(command))
{
arr.BHSearch();
repaint();
}
}
//********************************************************
// called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (arr.DataFileName != null)
{
g.drawString("File -- "+arr.DataFileName+" -- was successfully opened", 300, 200);
g.drawString("Number of Data Items = "+Integer.toString(arr.NumberOfDataItems), 330, 250);
}
else
{
g.drawString("NO Data File is Open", 300, 200);
}
if (arr.KeysFileName != null)
{
g.drawString("File -- "+arr.KeysFileName+" -- was successfully opened", 300, 300);
g.drawString("Number of Keys = "+Integer.toString(arr.NumberOfKeys), 330, 350);
}
else
{
g.drawString("NO Keys File is Open", 300, 300);
}
return;
}
if("Sequential Search".equals(command) || "Binary Search".equals(command)||
"Hashed Search".equals(command) || "Bucket Hashed Search".equals(command) )
{
g.drawRect(100, 100, 700, 420);
g.drawString("Experiment", 135, 200);
g.drawLine(250,100,250,520);
g.drawString("Data File Attributes -- "+Integer.toString(arr.NumberOfDataItems)+" Data Items", 450, 130);
g.drawString("Key File Attributes -- "+Integer.toString(arr.NumberOfKeys)+" Keys", 450, 155);
g.drawLine(250,175,800,175);
g.drawString("Measured Criteria", 475,190 );
g.drawLine(250,215,800,215);
g.drawString("Successful Search", 410, 230);
g.drawString("Unccessful Search", 640, 230);
g.drawLine(360,245,800,245);
g.drawLine(100,310,800,310);
g.drawString("Sequential Search", 110, 325);
g.drawLine(100,340,800,340);
g.drawString("Average", 285, 260);
g.drawString("Access", 285, 275);
g.drawString("Time", 290, 290);
g.drawLine(360,215,360,520);
g.drawString("#", 400, 260);
g.drawString("Keys", 400, 275);
g.drawString("Found", 390, 290);
g.drawLine(470,245,470,520);
g.drawString("Average", 500, 260);
g.drawString("No. Of", 500, 275);
g.drawString("Comparisons", 485, 290);
g.drawLine(580,215,580,520);
g.drawString("# ", 620, 260);
g.drawString("Keys", 620, 275);
g.drawString("Not Found", 600, 290);
g.drawLine(690,245,690,520);
g.drawString("Average", 720, 260);
g.drawString("No. Of", 720, 275);
g.drawString("Comparisons", 700, 290);
g.drawString(Long.toString(arr.SSAverageAccessTime), 255, 325);
g.drawString(Long.toString(arr.SSNumberKeysSuc), 365, 325);
g.drawString(Long.toString(arr.SSAverageCompSuc), 475, 325);
g.drawString(Long.toString(arr.SSNumberKeysFailed), 585, 325);
g.drawString(Long.toString(arr.SSAverageCompFailed), 695, 325);
g.drawString("Binary Search", 110, 355);
g.drawLine(100,370,800,370);
g.drawString(Long.toString(arr.BSAverageAccessTime), 255, 355);
g.drawString(Long.toString(arr.BSNumberKeysSuc), 365, 355);
g.drawString(Long.toString(arr.BSAverageCompSuc), 475, 355);
g.drawString(Long.toString(arr.BSNumberKeysFailed), 585, 355);
g.drawString(Long.toString(arr.BSAverageCompFailed), 695, 355);
g.drawString("Hashed Search", 110, 385);
g.drawLine(100,400,800,400);
g.drawString(Long.toString(arr.HSAverageAccessTime), 255, 385);
g.drawString(Long.toString(arr.HSNumberKeysSuc), 365, 385);
g.drawString(Long.toString(arr.HSAverageCompSuc), 475, 385);
g.drawString(Long.toString(arr.HSNumberKeysFailed), 585, 385);
g.drawString(Long.toString(arr.HSAverageCompFailed), 695, 385);
// add code to display results for other searches
}
}
}
You are doing a wrong calculation
change below:
int middle = (low-high)/2;
to:
int middle = (high-low)/2;
low is always less than high so you are getting a negative number and that negative index will not exist in your array.
Although I have not checked any other possible problems or the algorithm's validity, the above is the solution to the problem you are having
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.