Outputting database data to a JTable - java

I've been trying to follow the information here and and the code here and I'm having some difficulty.
The database query works and I've outputted it successfully to console. Following the above guides I've since added some code that puts the ResultSet data into the required Vectors. This is my code:
public class Reports extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField dateFromYYYY;
private JTextField dateFromMM;
private JTextField dateFromDD;
private JTextField dateToYYYY;
private JTextField dateToMM;
private JTextField dateToDD;
private JTextField ownerNameInput;
private JTextField petNameInput;
private JTextField doctorNameInput;
private JCheckBox isPaid = new JCheckBox("Is Paid");
public static JTable table;
public static boolean printTable = true;
private String printHeader;
// Static Variables
private final static String BOOKINGS_TABLES = "FROM Doctor, Pet, Treatment, Visit ";
/**
* Create the frame.
*/
private void SearchFrame() {
setTitle("Generate a Report");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 981, 551);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblWhatWouldYou = new JLabel("What would you like a report for?");
lblWhatWouldYou.setBounds(36, 10, 200, 50);
contentPane.add(lblWhatWouldYou);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(260, 60, 690, 370);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
private void DateFields(){
// From Date
//Year
JLabel lblFromDate = new JLabel("From dd:");
lblFromDate.setBounds(20, 180, 165, 25);
contentPane.add(lblFromDate);
JLabel lblFromYear = new JLabel("yyyy:");
lblFromYear.setBounds(180, 180, 165, 25);
contentPane.add(lblFromYear);
dateFromYYYY = new JTextField();
dateFromYYYY.setBounds(210, 180, 40, 25);
contentPane.add(dateFromYYYY);
//Month
JLabel lblFromMonth = new JLabel("mm:");
lblFromMonth.setBounds(128, 180, 165, 25);
contentPane.add(lblFromMonth);
dateFromMM = new JTextField();
dateFromMM.setBounds(155, 180, 20, 25);
contentPane.add(dateFromMM);
dateFromDD = new JTextField();
dateFromDD.setBounds(100, 180, 20, 25);
contentPane.add(dateFromDD);
// To Date
//Year
JLabel lblToDate = new JLabel("To dd:");
lblToDate.setBounds(20, 210, 165, 25);
contentPane.add(lblToDate);
JLabel lblToYear = new JLabel("yyyy:");
lblToYear.setBounds(180, 210, 165, 25);
contentPane.add(lblToYear);
dateToYYYY = new JTextField();
dateToYYYY.setBounds(210, 210, 40, 25);
contentPane.add(dateToYYYY);
//Month
JLabel lblToMonth = new JLabel("mm:");
lblToMonth.setBounds(128, 210, 165, 25);
contentPane.add(lblToMonth);
dateToMM = new JTextField();
dateToMM.setBounds(155, 210, 20, 25);
contentPane.add(dateToMM);
dateToDD = new JTextField();
dateToDD.setBounds(100, 210, 20, 25);
contentPane.add(dateToDD);
}
private void PetName(){
JLabel lblPetName = new JLabel("Pet Name:");
lblPetName.setBounds(20, 90, 165, 25);
contentPane.add(lblPetName);
petNameInput = new JTextField();
petNameInput.setBounds(100, 90, 150, 25);
contentPane.add(petNameInput);
}
private void OwnerName(){
JLabel lblOwnerName = new JLabel("Owner Name:");
lblOwnerName.setBounds(20, 120, 165, 25);
contentPane.add(lblOwnerName);
ownerNameInput = new JTextField();
ownerNameInput.setBounds(100, 120, 150, 25);
contentPane.add(ownerNameInput);
}
private void DoctorName(){
JLabel lblDoctorName = new JLabel("Doctor Name:");
lblDoctorName.setBounds(20, 150, 165, 25);
contentPane.add(lblDoctorName);
doctorNameInput = new JTextField();
doctorNameInput.setBounds(100, 150, 150, 25);
contentPane.add(doctorNameInput);
}
private void IsPaidCheckBox(){
isPaid.setBounds(155, 250, 97, 25);
contentPane.add(isPaid);
}
public void Bookings() {
// Local variables
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Instantiate the frame
SearchFrame();
// Set search fields
PetName();
OwnerName();
DoctorName();
IsPaidCheckBox();
DateFields();
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String queryString00 = "";
String queryString01 = "SELECT pet.petname AS [Pet Name], pet.ownerName AS [Owner Name], doctor.doctorName AS [Doctor Name], visit.visitDate AS [Visit Date], treatment.treatmentName AS [Treatment Name], visit.ispaid AS [Is Paid] ";
String queryString03 = "WHERE Visit.petID = Pet.petID ";
String queryString02 = " GROUP BY visitID;";
// build the query
if(!(petNameInput.getText().equals("")))
queryString00 = queryString01 + BOOKINGS_TABLES + queryString03 + "AND petname LIKE " + "'%" + petNameInput.getText() + "%'";
else queryString00 = queryString01 + BOOKINGS_TABLES + queryString03;
if(!(ownerNameInput.getText().equals("")))
queryString00 = queryString00 + "AND ownername LIKE " + "'%" + ownerNameInput.getText() + "%'";
if(!(doctorNameInput.getText().equals("")))
queryString00 = queryString00 + "AND doctorname LIKE " + "'%" + doctorNameInput.getText() + "%'";
if(!(dateFromYYYY.getText().equals(""))){
String fromString = dateFromYYYY.getText() + "-" + dateFromMM.getText() + "-" + dateFromDD.getText();
queryString00 = queryString00 + " AND visitdate >= '" + fromString + "'";
}
if(!(dateToYYYY.getText().equals(""))){
String toString = dateToYYYY.getText() + "-" + dateToMM.getText() + "-" + dateToDD.getText();
queryString00 = queryString00 + " AND visitdate <= '" + toString + "'";
}
if(isPaid.isSelected())
queryString00 = queryString00 + " AND ispaid = 'Y'";
queryString00 = queryString00 + queryString02;
// System.out.println(queryString00);
DatabaseConnection db = new DatabaseConnection();
db.openConn();
// Get query
ResultSet rs = db.getSearch(queryString00);
ResultSetMetaData md = null;
// Set up vectors for table output
// Output query to screen (Much of the following code is adapted from http://www.camick.com/java/source/TableFromDatabase.java)
try{
md = rs.getMetaData();
int columnCount = md.getColumnCount();
// Get column names
for(int i = 1; i <= columnCount; i++)
columnNames.addElement(md.getColumnName(i));
while(rs.next()){
// System.out.printf("%-15s%-15s%-15s%-15s%-15s%-15s\n", rs.getString("Pet Name"), rs.getString("Owner Name"), rs.getString("Doctor Name"), rs.getString("Visit Date"), rs.getString("Treatment Name"), rs.getString("Is Paid"));
Vector<Object> row = new Vector<Object>(columnCount);
for(int i = 1; i <= columnCount; i++)
row.addElement(rs.getObject(i));
data.addElement(row);
}
}
catch (SQLException e) {
e.printStackTrace();
}
db.closeConn();
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
/**
*
*/
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
});
btnSearch.setBounds(36, 460, 165, 25);
contentPane.add(btnSearch);
JLabel resultLabel = new JLabel("Reports will be printed below");
resultLabel.setBounds(515, 10, 312, 50);
contentPane.add(resultLabel);
JButton printReport = new JButton("Print Report");
printReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String resultLabelPrint = resultLabel.getText();
MessageFormat footer = new MessageFormat(resultLabelPrint);
MessageFormat header = new MessageFormat(printHeader);
boolean complete =table.print(JTable.PrintMode.FIT_WIDTH, header , footer );
if (complete) {
/* show a success message */
} else {
/*show a message indicating that printing was cancelled */
}
} catch (PrinterException pe) {
/* Printing failed, report to the user */
}
}
});
printReport.setBounds(473, 460, 227, 25);
contentPane.add(printReport);
}
}
The final part of the code, which I believe out puts to the table, gives me some weird errors.
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
The first line gives me a syntax error on the semi-colon (;), specifically, Syntax error on token ";", invalid AssignmentOperator. I get the same when I try the 'model' variable.
When I uncomment the last two lines I get 'Syntax error on token ".", { expected' and the Eclipse demands another closing { despite there not being a corresponding opening }. If I add it then I get more errors.
I suspect this has something to do with the class structure of the code that I'm trying to follow but I'm having no luck in following those either.
All I want to do is to take the information that I have and output it in the table which is already there. How do I do this?

You're not showing all the error messages nor the complete error messages (please fix this). The most important one is the, Cannot refer to the non-final local variable data defined in an enclosing scope message. So make the variables final -- one problem solved.
public void Bookings() {
// Local variables
final Vector<Object> columnNames = new Vector<Object>(); //!! made final
final Vector<Object> data = new Vector<Object>();
The other problem is that this code:
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
Is being called outside of any and all methods. You need to match up your curly braces carefully.
Question that confuses me about your code though -- why create a TableModel and not use it as a model for your JTable?

scrollPane is not a global instance.
Move JScrollPane scrollPane out of your method SearchFrame() and place it into your list of instance variables for the class.
That is only your immediate and first issue, your other issue is that your are attempting to access instance variables defined in Reports within the scope of 2x nested anonymous classes.
You should parametarize your GUI methods to accept the components for injection into the panels.
public class Reports extends JFrame {
JScrollPane scrollPane;
...
private void SearchFrame() {
scrollPane = new JScrollPane ();
}
...
public void Bookings() {
scrollPane...
...
}
...
}

Related

How do I make a JButton hit the enter key when pressed?

So in my code, I have 2 JTextField inputs that need input for the rest of the program to work. Both of them contain variables that cannot be left empty for the rest of the program to work. The problem is that whenever you enter something into the text field, you have to press enter in the end and that process is not that straightforward in the program as you are not able to see whether or not you have already pressed enter without looking into the console.
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame2.setTitle("Multiplayer");
frame2.setVisible(true);
JLabel labelM = new JLabel("Geben sie eine Höhstzahl ein:");
JTextField hZahl = new JTextField();
JLabel labelN= new JLabel("Mit wie vielen Rateversuchen wollen sie spielen?");
JTextField rVers = new JTextField();
JButton b = new JButton("Submit");
Now I want the JButton b to press enter for both text field hZahl and rVers when pushed. How do I achieve that?
This is what button bdoes so far:
ActionListener buttonlistener3 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if((arr[0] > 0) && (arr[1] > 0)){
frame3.setTitle("1 Player Game");
frame3.setVisible(true);
JLabel labelB = new JLabel("Erraten sie die Zahl:");
JTextField rVers1 = new JTextField();
labelB.setBounds(50, 105, 400, 70);
rVers1.setBounds(45, 150, 100, 30);
frame3.add(labelB);
frame3.add(rVers1);
rVers1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("Rateversuch: " + rVers1.getText());
int r = Integer.parseInt(rVers1.getText());
arr[2] = r;
System.out.println("werte " + arr[1] +" " + arr[3] +" " + r);
if(arr[1] == 1){
JLabel lv = new JLabel("Letzer Versuch!");
lv.setBounds(50, 50, 400, 70);
lv.setForeground(Color.red);
frame4.add(lv);
}
tru = arr[3] == arr[2];
if(r < arr[3]){
labelB.setText("Die Gesuchte Zahl ist größer.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(r > arr[3]){
labelB.setText("Die Gesuchte Zahl ist kleiner.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(tru){
frame4.setVisible(true);
JLabel cor = new JLabel("Richtig!");
JLabel win = new JLabel("Sie haben Gewonnen");
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.red);
frame4.add(cor);
frame4.add(win);
}
System.out.println("werte neu " + arr[1] +" " + arr[3] +" " + r);
}
});
}
}
};
b.addActionListener(buttonlistener3);
}
};

Getting a java;23 error; saying '{' is expected but brackets look fine to me [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
please help getting "java:23 error: '{' expected" to me the brackets look right, appreciate the help!
is there something else that I am missing? I've only just started getting into writing code and so far have loved it. I've done c# and visual basics as well as now taking Java.
//Pizza applet to assist customers when ordering pizza
//I had to make a pizza during this assignment :)
//Import packages
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PizzaShop extends JApplet
{
//Declare variables
private int intBold;
private JCheckbox tomatoCB, grennPepperCB, blackOliveCB;
private JCheckBox MushroomCB, extraCheeseCB, pepperoniCB, sausageCB;
private JRadioButton smallRB, mediumRB, largeRB;
private JRadioButton thinRB, halfRB, panPizzaRB;
private ButtonGroup sizeBG, typeBG;
private JTextArea textArea;
private Jbutton processB;
private JLabel orderL;
private EventHandler eHandler;
}
public class PizzaShop()
{
public void init()
{
//Set up layout
Container c = getContentPane();
c.setLayout(null);
eHandler = new EventHandler();
//Establish checkboxes
tomatoCB = new JCheckBox("Tomato");
greenPepperCB = new JCheckBox("Green Pepper");
blackOliveCB = new JCheckBox("Black Olive");
mushroomCB = new JCheckBox("Mushroom");
extraCheeseCB = new JCheckBox("Extra Cheese");
pepperoniCB = new JCheckBox("Pepperoni");
sausageCB = new JCheckBox("Sausage");
//Set size and location
tomatoCB.setSize(100, 25);
greenPepperCB.setSize(100, 25);
blackOliveCB.setSize(100, 25);
mushroomCB.setSize(100, 25);
extraCheeseCB.setSize(100, 25);
pepperoniCB.setSize(100, 25);
sausageCB.setSize(100, 25);
tomatoCB.setLocation(50, 85);
greenPepperCB.setLocation(50, 110);
blackOliveCB.setLocation(50, 135);
mushroomCB.setLocation(50, 160);
extraCheeseCB.setLocation(50, 185);
pepperoniCB.setLocation(50, 210);
sausageCB.setLocation(50, 235);
//Add CheckBox to layout
c.add(tomatoCB);
c.add(greenPepperCB);
c.add(blackOliveCB);
c.add(mushroomCB);
c.add(extraCheeseCB);
c.add(pepperoniCB);
c.add(sausageCB);
//Set pizza size radio buttons
smallRB = newJRadioButton("Small $6.50");
mediumRB = newJRadioButton("Medium $8.50");
largeRB = newJRadioButton("Large: $10.00");
//Set size and location of pizza buttons
smallRB.setSize(100, 25);
mediumRB.setSize(100, 25);
largeRB.setSize(100, 25);
smallRB.setLocation(225, 90);
mediumRB.setLocation(225, 130);
largeRB.setLocation(225, 170);
//Set group for pizza size
sizeBG = new ButtonGroup();
sizeBG.add(smallRB);
sizeBG.add(mediumRB);
sizeBG.add(largeRB);
c.add(smallRB);
c.add(mediumRB);
c.add(largeRB);
//Set pizza type
thinRB = new JRadioButton("Thin Crust");
halfRB = newJRadioButton("Medium Crust");
panPizzaRB = new JRadioButton("Pan");
//Set pizza type size and location
thinRB.setSize(100, 25);
halfRB.setSize(100, 25);
panRB.setSize(100, 25);
thinRB.setLocation(370, 90);
half.setLocation(370, 130);
PanRB.setLocation(370, 170);
//Set type of pizza to button group
typeBG = new ButtonGroup();
typeBG.add(thinRB);
typeBG.add(halfRB);
typeBG.add(panRB);
c.add(thinRB);
c.add(halfRB);
c.add(panRB);
//Add process button set size and location and activate event
processB = new JButton("Process Order");
processB.setSize(200, 30);
processB.setLocation(210, 220);
c.add(processB);
processB.addActionListener(eHandler);
//Add label for output and set size and location
orderL = new JLabel("Your Order:");
orderL.setSize (100, 30);
orderL.setLocation(40, 270);
c.add(orderL);
textArea = new JTextArea();
textArea.setVisible(true);
textArea.setSize(450, 110);
textArea.setLocation(40, 300);
c.add(textArea);
}
public void paint(Graphics g)
{
super.paint(g);
//Set text for welcome greeting
g.setColor(Color.red);
g.setFont(new Font("Times New Roman", intBold, 24));
g.drawString("Welcome to Home Style Pizza Shop", 30, 30);
//Set text for each topping
g.setFont(new Font("Times New Roman", intBold, 24));
g.drawString("Each Topping: $1.50", 40, 80);
g.drawRect(30, 60, 150, 210);
//Set text for pizza size and type
g.drawString("Pizza Size", 220, 80);
g.drawRect(210, 60, 130, 150);
g.drawString("Pizza Type", 370, 80);
g.drawRect(360, 60, 130, 150);
}
private class EventHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//Declare variables
double amountDue = 0.0;
String str = " ";
//See whats checked in pizza type
if (e.getSource() == processB);
{
str = str + "Pizza Type:";
if (thinRB.isSelected())
str = str + "Thin Crust \n";
else if (halfRB.isSelected())
str = str + " Medium Crust \n";
else if (panRB.isSelected())
str = str + "Pan Crust \n";
}
str = str + "Pizza Size: ";
//See what's checked in pizza size
if(smallRB.isSelected())
{
str = str + "Small \n";
amountDue = amountDue + 6.50;
}
else if (mediumRB.isSelected())
{
str = str + "Medium \n";
amountDue = amountDue + 8.50;
}
else if (largeRB.isSelected())
{
str = str + "Large \n";
amountDue = smountDue = 10.00;
}
str = str + "Toppings: ";
//Check toppings add 1.50 each per checked box
if (tomatoCB.isSelected())
{
str = str + "Tomato, ";
amountDue = amountDue + 1.50;
}
if (greenPepperCB.isSelected())
{
str = str + "Green Pepper, ";
amountDue = amountDue + 1.50;
}
if (blackOliveCB.isSelected())
{
str = str + "Black Olive, ";
amountDue = amountDue + 1.50;
}
if (mushroomCB.isSelected())
{
str = str + "Mushroom, ";
amountDue = amountDue + 1.50;
}
if (extraCheeseCB.isSelected())
{
str = str + "Extra Cheese, ";
amountDue = amountDue + 1.50;
}
if (pepperoniCB.isSelected())
{
str = str + "Pepperoni, ";
amountDue = amountDue + 1.50;
}
if (sausageCB.isSelected())
{
str = str + "Sausage, ";
amountDue = amountDue + 1.50;
}
//Display order
str = str + "\nAmount Due: $" = amountDue;
textArea.setText(str);
}
}
}
The } after private EventHandler eHandler; will close the class definition, which is not what you are wanting.
Also public class PizzaShop() { would be wrong and not needed. Maybe you are thinking of a constructor?
I suggest that you use a IDE like eclipse which allows you to click on menu items to create classes etc.
Your closing brace on line 22 is finishing the class definition and the code after that seems to be trying to re-start it. Get rid of it. You should have:
private JLabel orderL;
private EventHandler eHandler;
public void init() { ...
There is an extra closing brace before
public class PizzaShop()
And I presume the above line is meant to be a constructor, not another class declaration:
public PizzaShop() {
}
You can't have the same class defined twice in a file, in fact each class should probably be in another file (or it needs to be an inner class of some kind) -
public class PizzaShop extends JApplet
{
//Declare variables
private int intBold;
private JCheckbox tomatoCB, grennPepperCB, blackOliveCB;
private JCheckBox MushroomCB, extraCheeseCB, pepperoniCB, sausageCB;
private JRadioButton smallRB, mediumRB, largeRB;
private JRadioButton thinRB, halfRB, panPizzaRB;
private ButtonGroup sizeBG, typeBG;
private JTextArea textArea;
private Jbutton processB;
private JLabel orderL;
private EventHandler eHandler;
} // <-- Here
public class PizzaShop() // <-- we just did this class.

How to add data to JTable

I'm still a little new to Java and a complete noob to Gui's. I can't for the life of me figure out how to add the data from my String array into the Jtable. I tried to read the docs on oracle but it was not making sense to me for my particular situation. If you guys could please point me in the right direction I would appreciate it. Also I'm retrieving my array data from a file. Not sure if that makes a difference.
public class TemplateGui extends JFrame {
private JTable tableHotelSecurity, securityFlagsTable;
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textField;
private static String [] sortedRoles_Flags,finalFlagsArr,finalHSArr;
private static String finalFlags="",finalHS="",column;
public TemplateGui(){
super("Galaxy Template Generator V1.0");
getContentPane().setForeground(new Color(0, 0, 0));
getContentPane().setLayout(null);
getContentPane().setBackground(new Color(51, 51, 51));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 170, 189, 186);
getContentPane().add(scrollPane);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane_1.setBounds(222, 170, 372, 186);
getContentPane().add(scrollPane_1);
//radio buttons
JRadioButton rdbtnNewRadioButton = new JRadioButton("Central User ");
rdbtnNewRadioButton.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnNewRadioButton.setBackground(Color.WHITE);
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setBounds(222, 75, 127, 36);
getContentPane().add(rdbtnNewRadioButton);
final JRadioButton rdbtnPropertyUser = new JRadioButton("Property User");
rdbtnPropertyUser.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnPropertyUser.setBackground(Color.WHITE);
buttonGroup.add(rdbtnPropertyUser);
rdbtnPropertyUser.setBounds(222, 38, 127, 34);
getContentPane().add(rdbtnPropertyUser);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.BOLD, 18));
textField.setBounds(10, 35, 53, 34);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblHotelSecurity = new JLabel("Hotel Security (H S)");
lblHotelSecurity.setHorizontalAlignment(SwingConstants.CENTER);
lblHotelSecurity.setFont(new Font("Tahoma", Font.BOLD, 13));
lblHotelSecurity.setBounds(10, 144, 189, 23);
lblHotelSecurity.setBackground(new Color(204, 204, 204));
lblHotelSecurity.setOpaque(true);
getContentPane().add(lblHotelSecurity);
JLabel label = new JLabel("Security Flags (S F)");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.BOLD, 13));
label.setBounds(222, 144, 372, 23);
label.setBackground(new Color(204, 204, 204));
label.setOpaque(true);
getContentPane().add(label);
JLabel lblEnterTemplateCode = new JLabel("ENTER TEMPLATE CODE");
lblEnterTemplateCode.setForeground(new Color(255, 255, 255));
lblEnterTemplateCode.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEnterTemplateCode.setBounds(10, 9, 175, 23);
getContentPane().add(lblEnterTemplateCode);
JLabel lblSelectUserRole = new JLabel("SELECT USER ROLE LEVEL");
lblSelectUserRole.setForeground(new Color(255, 255, 255));
lblSelectUserRole.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSelectUserRole.setBounds(222, 13, 195, 14);
getContentPane().add(lblSelectUserRole);
//Submit button action
Button button = new Button("Generate Template");
button.setFont(new Font("Dialog", Font.BOLD, 12));
button.setBackground(new Color(102, 255, 102));
button.setForeground(Color.BLACK);
button.setBounds(467, 83, 127, 41);
getContentPane().add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Query excell = new Query();
//get template text
String template = textField.getText().toUpperCase();
System.out.println(template);
if(rdbtnPropertyUser.isSelected()){
try {
//property user was selected
excell.runProcess(1);
System.out.println("you selected Property user");
} catch (IOException e) {
System.out.println("Error occured on line 70 Interface Class");
}
}
else{
try {
//Central User was selected
excell.runProcess(2);
System.out.println("you selected central user");
} catch (IOException e) {
System.out.println("Error occured on line 79 Interface Class");
}
}
System.out.println("NOW WERE HERE");
//get static variables from Excel Query
for(int i = 0; i< Query.sortedGF.length; i++)
{
if(Query.sortedGF[i].contains(template)){
sortedRoles_Flags =Query.sortedGF[i].split(" ");
System.out.println("THIS RAN"+" :"+i);
break;
}
}
System.out.println("NOW WERE HERE 103 " +Query.securityFlags.length);
//add data to table
int j=0;
int sizeOfFlags = Query.securityFlags.length;
System.out.println("Size Of the Flags is:"+" "+sizeOfFlags);
System.out.println("Size Of the Flags is:"+" "+sortedRoles_Flags.length);
//Add HS to FinalHS Variable only if Yes
for(int i=0;i< sortedRoles_Flags.length-sizeOfFlags;i++)
{
if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y"))
{
System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]);
finalHS += Query.hotelSecurity[i]+" ";
System.out.println("Hotel security:"+" "+finalHS);
}
}
//add Security Flags to Final Flags
for(int i=(sortedRoles_Flags.length-sizeOfFlags);i< sortedRoles_Flags.length;i++)
{
finalFlags += Query.securityFlags[j]+": "+ sortedRoles_Flags[i]+" + ";
j++;
}
//Leave open just incase they would prefer a text file for template in which case we just write it
System.out.println(finalFlags);
System.out.println(finalHS);
//Convert to String Arrays in order to add to our JTable
finalFlagsArr= finalFlags.split("\\+");
finalHSArr = finalHS.split(" ");
}
});
//content to be in the table
DefaultTableModel modelH = new DefaultTableModel();
tableHotelSecurity = new JTable(modelH);
scrollPane.setViewportView(tableHotelSecurity);
DefaultTableModel modelS = new DefaultTableModel();
securityFlagsTable = new JTable(modelS);
scrollPane_1.setViewportView(securityFlagsTable);
}
}
Follow this tutorial:
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
The main idea is, that swing is built on the principles of MVC architecture. What that means for you is that the component that is responsible for displaying the table (JTable), and the component that knows what is in the table (TableModel) are separated. You somehow need to pass the model to the table. You can either use the DefaultTableModel, which is what you did, or define your own model that implements the interface TableModel.
For the first, you need to pass in an array to the constructor of DefaultTableModel.
For the latter you need to implement methods that - among others - query data at certain positions, but this is worth considering only if the out of the box stuff does not do it for you.
On a side note about error messages: if you are serious about programming, don't get used to bad patterns. They might seem easier now, but they are ill-advised for a reason. They usually don't scale well from a hello-world size project to a full blown project developed by multiple people. Stacktrace is your friend. Use a logger instead of sysout. It will be easier for you in the long run if you get used to good practices now.

Listbox in Java

I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox.
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method.
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use:
lb2.getSelectedItem();
which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows:
Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.

Java Program error (TextField)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class NICCode extends JFrame {
NICCode() {
setSize(600, 250);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
// JPanel
JPanel labelPanel = new JPanel(new FlowLayout(1));
JPanel leftBodyPanel = new JPanel(new GridLayout(3, 1));
JPanel bodyPanel = new JPanel(new GridLayout(3, 1));
JPanel buttonPanel = new JPanel(new FlowLayout(2));
JPanel textFieldPanel = new JPanel(new FlowLayout(0));
// JLabel
JLabel titleLabel = new JLabel("Find Your Birthday By NIC");
titleLabel.setFont(new Font("", 1, 25));
JLabel myLabel = new JLabel("CSG");
myLabel.setFont(new Font("", 1, 10));
JLabel enterNicLabel = new JLabel("Enter Your NIC :");
JLabel yourBirthDayLabel = new JLabel("Your Birth Day :");
JLabel yourGenderLabel = new JLabel("Gender :");
JLabel printBirthDayLabel = new JLabel("Your Birth Day");
JLabel printGenderLabel = new JLabel("Your Gender");
// JTextField
JTextField nicText = new JTextField(25);
nicText.setText("920000000V");
// JButton
JButton searchAgainButton = new JButton("Search Again");
JButton exitButton = new JButton("Exit");
// adds
add("North", labelPanel);
add("West", leftBodyPanel);
add("South", buttonPanel);
add(bodyPanel);
labelPanel.add(titleLabel);
leftBodyPanel.add(enterNicLabel);
leftBodyPanel.add(yourBirthDayLabel);
leftBodyPanel.add(yourGenderLabel);
textFieldPanel.add(nicText);
bodyPanel.add(textFieldPanel);
bodyPanel.add(printBirthDayLabel);
bodyPanel.add(printGenderLabel);
buttonPanel.add(myLabel);
buttonPanel.add(searchAgainButton);
buttonPanel.add(exitButton);
setVisible(true);
// pack();
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
String sex = "";
int year = Integer.parseInt(yearText);
int date = Integer.parseInt(dateText);
int month = 0;
if (date > 500) {
sex = "Feamale";
date -= 500;
} else {
sex = "Male";
}
int datesOfMonths[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int i = 0; i < 12; i++) {
date = date - datesOfMonths[i];
month = i;
if (date < datesOfMonths[i + 1]) {
break;
}
}
if (month > 0) {
month += 1;
}
}
}
I just created a program for find birthday from nic. I couldn't fix this compile error.
I created a JTextField to get Nic, then I added substring methods to get the needed numbers to find nic. Unfortunately the substring methods can't find textField. It shows error as 'cannot find symbol'. It's a TextField. Why can't the method find that TextField.?
The message:
cannot find symbol
Is not referring to the text field, but the method substring(..) which does not exist for JTextField. But something like..
textField.getText().substring(...);
..probably will work, since getText() returns a String and String has that method.
Change
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
to
String yearText = nicText.getText().substring(0, 2);
String dateText = nicText.getText().substring(2, 5);

Categories