How to add data to JTable - java

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.

Related

Reset Java field unresolved compilation problem

I'm trying to count the number of tries a user makes to guess a number in a java GUI program using swing.
I've created these variables to keep track of the number of tries:
JLabel lblNumberOfTries = new JLabel("Number of tries:");
lblNumberOfTries.setBounds(136, 219, 90, 13);
getContentPane().add(lblNumberOfTries);
txtNumberOfTries = new JTextField();
txtNumberOfTries.setBounds(223, 219, 42, 13);
getContentPane().add(txtNumberOfTries);
txtNumberOfTries.setColumns(10);
And I need to reset them when the game restarts. For some reason I can reset the java field but not the label:
txtNumberOfTries.setText(""); // this is ok
lblNumberOfTries.setText(""); // this gives an error
This is the error I'm getting:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
lblNumberOfTries cannot be resolved
at GuessingGame.newGame(GuessingGame.java:50)
at GuessingGame.main(GuessingGame.java:110)
This is the class and functions where the labels and fields are in my program:
import javax.swing.JFrame;
public class GuessingGame extends JFrame {
public GuessingGame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Tim's Hi-Lo Guessing Game");
getContentPane().setLayout(null);
JLabel lblTitle = new JLabel("Tim's Hi-Lo Guessing Game");
lblTitle.setFont(new Font("Tahoma", Font.BOLD, 15));
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setBounds(0, 10, 436, 32);
getContentPane().add(lblTitle);
JLabel lblGuessANumber = new JLabel("Guess a number between 1 and 100:");
lblGuessANumber.setBackground(new Color(240, 240, 240));
lblGuessANumber.setHorizontalAlignment(SwingConstants.RIGHT);
lblGuessANumber.setBounds(147, 54, 215, 13);
getContentPane().add(lblGuessANumber);
txtGuess = new JTextField();
txtGuess.addActionListener((ActionEvent e) -> {
checkGuess();
});
txtGuess.setHorizontalAlignment(SwingConstants.RIGHT);
txtGuess.setBounds(260, 122, 27, 19);
getContentPane().add(txtGuess);
txtGuess.setColumns(10);
JButton btnGuess = new JButton("Guess!");
btnGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkGuess();
}
});
btnGuess.setBounds(172, 121, 85, 21);
getContentPane().add(btnGuess);
lblOutput = new JLabel("Enter a number above and click Guess!");
lblOutput.setHorizontalAlignment(SwingConstants.CENTER);
lblOutput.setBounds(58, 196, 350, 13);
getContentPane().add(lblOutput);
JLabel lblNumberOfTries = new JLabel("Number of tries:");
lblNumberOfTries.setBounds(136, 219, 90, 13);
getContentPane().add(lblNumberOfTries);
txtNumberOfTries = new JTextField();
txtNumberOfTries.setBounds(223, 219, 42, 13);
getContentPane().add(txtNumberOfTries);
txtNumberOfTries.setColumns(10);
}
public void newGame() {
theNumber = (int) (Math.random() * 100 + 1);
txtNumberOfTries.setText("");
lblNumberOfTries.setText("");
}
}
What am I doing wrong?
Ok, so after seeing the full file, there are 2 main points:
You need to define a field private JLabel lblNumberOfTries; in the class
You also need to remove 'JLabel' from around line 98 in the GuessingGame constructor (the method defined public GuessingGame() is known as the constuctor) so that it becommes lblNumberOfTries = new JLabel("Number of tries:");. This will stop you from redeclaring the variable.
At some point, you're also going to want to add a private int field called numberOfTries

Outputting database data to a JTable

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...
...
}
...
}

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.

How can I put Jbuttons into arraylist with considering their name?

I have this code and I want to put all buttons in my page to in arraylist with considering their name if its name is for example btn_2 it should be the second element of the list.
It gives an error and says cannot cast field to Jbutton since my list type is Jbutton not field.his is not all my code just some of them but all code consist of ading panel then adding a button to panel also some labels.
getContentPane().setForeground(Color.DARK_GRAY);
getContentPane().setLocation(-405, -87);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
panelPOD1 = new JPanel();
panelPOD1.setBounds(65, 13, 353, 313);
panelPOD1.setBorder(new BevelBorder(BevelBorder.RAISED, Color.DARK_GRAY, null, null, null));
getContentPane().add(panelPOD1);
panelPOD1.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.DARK_GRAY, null, null, null));
panel.setBounds(10, 11, 59, 59);
panelPOD1.add(panel);
panel.setLayout(null);
btn_1 = new JButton();
btn_1.setText("");
btn_1.setEnabled(false);
btn_1.setBorder(new RoundedBorder());
btn_1.setBounds(17, 15, 26, 24);
panel.add(btn_1);
btn_3 = new JButton("");
btn_3.setEnabled(false);
btn_3.setForeground(SystemColor.textInactiveText);
btn_3.setBackground(SystemColor.activeCaption);
btn_3.setBounds(10, 15, 26, 24);
btn_3.setBorder(new RoundedBorder());
panel1.add(btn_3);
panel.setLayout(null);
btn_5 = new JButton("");
btn_5.setEnabled(false);
btn_5.setBounds(11, 15, 26, 24);
btn_5.setBorder(new RoundedBorder());
panel_1.add(btn_5);
btn_2 = new JButton("");
btn_2.setEnabled(false);
btn_2.setBounds(12, 15, 26, 24);
btn_2.setBorder(new RoundedBorder());
panel_2.add(btn_2);
btn_4 = new JButton("");
btn_4.setEnabled(false);
btn_4.setBounds(11, 15, 26, 24);
btn_4.setBorder(new RoundedBorder());
panel_3.add(btn_4);
JPanel panel_4 = new JPanel();
panel_4.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_4.setBounds(10, 81, 59, 59);
panelPOD1.add(panel_4);
panel_4.setLayout(null);
btn_6 = new JButton("");
btn_6.setEnabled(false);
btn_6.setBounds(10, 15, 26, 24);
btn_6.setBorder(new RoundedBorder());
panel_4.add(btn_6);
Integer search_index=0;
java.lang.reflect.Field[] fields;
Integer arrayIndex=0;
ArrayList<JButton> rockets;
boolean allFound=false;
while (!allFound)
{
for (int i =0;i<fields.length;i++)
{
if(fields[i].getName().equals("btn"+arrayIndex.toString()))
{
rockets.add(arrayIndex,fields[i]);
}
if (arrayIndex==50)
{
allFound = true;
}
}
}
Like everyone else here, I highly doubt whether you should approach the problem this way, but if you insist, this works:
final int NUMBER_OF_BUTTONS = 50;
final String PREFIX = "btn_";
Field[] fields = getClass().getDeclaredFields();
JButton[] rockets = new JButton[NUMBER_OF_BUTTONS];
for (Field field : fields) {
if(field.getName().startsWith(PREFIX)) {
int index = Integer.parseInt(field.getName().substring(PREFIX.length())) - 1;
rockets[index] = (JButton) field.get(this);
}
}
I assumed that your first button is called btn_1, hence the -1 for the index.
ArrayList<JButton> rockets = new ArrayList<JButton>();
btn_1 = new JButton();
btn_1.setText("");
btn_1.setEnabled(false);
btn_1.setBorder(new RoundedBorder());
btn_1.setBounds(17, 15, 26, 24);
rockets.add(btn_1);
panel.add(btn_1);
btn_2 = new JButton("");
btn_2.setEnabled(false);
btn_2.setBounds(12, 15, 26, 24);
btn_2.setBorder(new RoundedBorder());
rockets.add(btn_2);
panel_2.add(btn_2);
And if you rearrange (=swap?) Buttons in your layout, you simply swap the items in rocket
This way you won't need to create a seperate instance of a JButton if you change the code to reuse a single variable over an over. If you need to identify an instance, you should rather subclass JButton and add an identifier than relying on a variable name that is not visible inside the ArryList.

Using Multiple ActionListeners in Java Swing

My problem is that at the moment I am making a GUI for a game and this GUI has many buttons. I had a problem earlier in my code where the actionListener I was using was looking for events in two buttons in rapid succession, not giving enough time for the second button to perform and action and rendering it useless. I thought I overcame that by making the second button a different actionListener in an inner class
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
and now I'm trying to do the same for a third (and eventually fourth and fifth button
P1Roll.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
but it is throwing me all kinds of errors. As I am very new to swing, I am unsure how to proceed. Any tips on this, or anything in my code at all would be very much appreciated. :)
import java.awt.Font;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
public class GUI_Windows extends JFrame implements ActionListener {
public static void main(String[] args) {
new GUI_Windows();
Random rand1, rand2, rand3, rand4;
int dice1, dice2, dice3, dice4;
int numTurns = Turns.getValue();
rand1 = new Random();
rand2 = new Random();
rand3 = new Random();
rand4 = new Random();
dice1 = rand1.nextInt(6 - 1 + 1) + 1;
dice2 = rand2.nextInt(6 - 1 + 1) + 1;
dice3 = rand3.nextInt(6 - 1 + 1) + 1;
dice4 = rand4.nextInt(6 - 1 + 1) + 1;
}
Box MegaBox, box1, box2, box3, box4, box5, box6, box7, box8, box9, box10,
box11;
Box Minibox1, Minibox2, Minibox3, Minibox4, Minibox5, MiniMegaBox;
Box MegaBox2, box12, box13, box14, box15, box16, box17, box18, box19,
box20, box21, box22, box23;
JLabel TitleLabel, InstructionLabel, Instructions, SelectMode, LoG;
Border spacer1 = BorderFactory.createEmptyBorder(5, 5, 50, 5);
Border spacer2 = BorderFactory.createEmptyBorder(5, 60, 5, 0);
Border spacer3 = BorderFactory.createEmptyBorder(5, 0, 5, 60);
Border spacer4 = BorderFactory.createEmptyBorder(0, 0, 5, 45);
Border spacer5 = BorderFactory.createEmptyBorder(0, 0, 6, 0);
Border spacer6 = BorderFactory.createEmptyBorder(5, 10, 0, 70);
Border spacer7 = BorderFactory.createEmptyBorder(0, 0, 0, 35);
JRadioButton button1, button2;
JButton button3, button4;
JButton button5, button6;
static JSlider Turns;
public GUI_Windows() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
button3.doClick();
}
});
this.setTitle("Bottom Out!");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setResizable(false);
this.setLocation(500, 125);
this.setSize(350, 421);
MegaBox = Box.createVerticalBox();
box1 = Box.createVerticalBox();
box1.setBorder(spacer1);
box2 = Box.createVerticalBox();
box2.setBorder(spacer2);
box3 = Box.createHorizontalBox();
box4 = Box.createHorizontalBox();
box4.setBorder(spacer3);
box5 = Box.createVerticalBox();
box5.setBorder(spacer5);
box6 = Box.createHorizontalBox();
box7 = Box.createHorizontalBox();
box8 = Box.createHorizontalBox();
box9 = Box.createHorizontalBox();
box10 = Box.createHorizontalBox();
box10.setBorder(spacer7);
box11 = Box.createHorizontalBox();
box11.setBorder(spacer6);
button1 = new JRadioButton();
button1.addActionListener(this);
button2 = new JRadioButton();
button2.addActionListener(this);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
InstructionLabel = new JLabel("Instructions:");
InstructionLabel.setAlignmentY(0);
InstructionLabel.setFont(new Font("Arial", Font.BOLD, 15));
Instructions = new JLabel();
Instructions.setAlignmentY(0);
Instructions
.setText("<HTML>Each game will be 3 - 20 turns, with either One Player versus the Computer, or Two Players "
+ "versus each other. Each turn, you will roll two die, and then the two die are totaled up, and "
+ "multiplied by the number of the roll it is for that turn. If this total is equal to, or higher than the "
+ "total of your last scores in that turn, than you add those points to your score for that turn. Then you "
+ "may choose to roll again, or end your turn to lock in your points for that turn.</HTML>");
SelectMode = new JLabel("Select Mode:");
SelectMode.setFont(new Font("Arial", Font.BOLD, 15));
LoG = new JLabel("Select number of Turns:");
Turns = new JSlider(2, 20, 2);
Turns.setMajorTickSpacing(2);
Turns.setMinorTickSpacing(1);
Turns.setPaintTicks(true);
Turns.setPaintLabels(true);
Turns.setSnapToTicks(true);
button3 = new JButton("Quit");
button3.setVisible(true);
button3.addActionListener(this);
button4 = new JButton("Next");
button4.setVisible(true);
button4.addActionListener(this);
button5 = new JButton("Done");
button5.setVisible(true);
// button5.addActionListener(this);
button6 = new JButton("Done");
button6.setVisible(true);
button6.addActionListener(this);
ButtonGroup group1 = new ButtonGroup();
group1.add(button1);
group1.add(button2);
ButtonGroup group2 = new ButtonGroup();
group2.add(button3);
group2.add(button4);
box6.add(TitleLabel);
box7.add(InstructionLabel);
box7.add(Box.createHorizontalGlue());
box7.add(new JLabel(" "));
box8.add(Instructions);
box3.add(SelectMode);
box3.add(Box.createHorizontalGlue());
box3.add(new JLabel(" "));
box4.add(button1);
box4.add(new JLabel(" One Player"));
box4.add(Box.createHorizontalGlue());
box4.add(button2);
box4.add(new JLabel(" Two Players"));
box9.add(LoG);
box9.setBorder(spacer4);
box10.add(Turns);
box10.add(Box.createHorizontalGlue());
box10.add(new JLabel(" "));
box11.add(button3);
box11.add(Box.createHorizontalGlue());
box11.add(button4);
box1.add(box6);
box1.add(box7);
box1.add(box8);
box5.add(box3);
box5.add(box4);
box2.add(box5);
box2.add(box9);
box2.add(box10);
box2.add(box11);
MegaBox.add(box1);
MegaBox.add(box2);
this.add(MegaBox);
this.setVisible(true);
}
int onePlayer = 0;
int isDone = 0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button3) {
System.exit(0);
}
if (button1.isSelected()) {
onePlayer = 1;
} else if (button2.isSelected()) {
onePlayer = 2;
}
if (e.getSource() == button4 && onePlayer == 0) {
JOptionPane.showMessageDialog(button1,
"You must select the number of players!", "Try again!",
JOptionPane.WARNING_MESSAGE);
} else if (e.getSource() == button4 && onePlayer != 0) {
final JFrame pFrame = new JFrame();
pFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pFrame.setTitle("Bottom Out!");
pFrame.setResizable(false);
pFrame.setLocation(500, 125);
pFrame.setSize(250, 200);
JLabel EnterName1, EnterName2;
final JTextField NameBox1;
final JTextField NameBox2;
Border border1 = BorderFactory.createEmptyBorder(5, 25, 15, 25);
Border border2 = BorderFactory.createEmptyBorder(15, 25, 5, 25);
Border border3 = BorderFactory.createEmptyBorder(5, 0, 5, 0);
EnterName1 = new JLabel("Player 1, please enter your name:");
EnterName2 = new JLabel("Player 2, please enter your name:");
NameBox1 = new JTextField("Miller");
NameBox2 = new JTextField("Julian");
if (onePlayer == 1) {
NameBox2.setEditable(false);
NameBox2.setText("Watson");
}
Minibox1 = Box.createVerticalBox();
Minibox2 = Box.createVerticalBox();
Minibox3 = Box.createVerticalBox();
Minibox4 = Box.createHorizontalBox();
MiniMegaBox = Box.createVerticalBox();
Minibox1.add(EnterName1);
Minibox1.add(NameBox1);
Minibox1.setBorder(border1);
Minibox2.add(EnterName2);
Minibox2.add(NameBox2);
Minibox2.setBorder(border2);
Minibox3.add(Minibox1);
Minibox3.add(Minibox2);
Minibox4.add(new JLabel(" "));
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(button5);
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(new JLabel(" "));
Minibox4.setBorder(border3);
MiniMegaBox.add(Minibox3);
MiniMegaBox.add(Minibox4);
pFrame.add(MiniMegaBox);
pFrame.setVisible(true);
this.setVisible(false);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button5) {
Border spaceBorder1 = BorderFactory.createEmptyBorder(
45, 45, 15, 45);
Border spaceBorder2 = BorderFactory.createEmptyBorder(
15, 45, 30, 45);
Border spaceBorder3 = BorderFactory.createEmptyBorder(
5, 15, 5, 0);
Border spaceBorder4 = BorderFactory.createEmptyBorder(
5, 0, 10, 10);
Border spaceborder5 = BorderFactory.createEmptyBorder(
0, 0, 15, 0);
Border spaceborder6 = BorderFactory.createEmptyBorder(
15, 0, 0, 0);
JFrame gFrame = new JFrame();
gFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gFrame.setTitle("Bottom Out!");
gFrame.setResizable(false);
gFrame.setLocation(500, 125);
gFrame.setSize(350, 421);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman",
Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
box23 = Box.createHorizontalBox();
box23.add(TitleLabel);
box23.setBorder(spaceborder6);
box12 = Box.createHorizontalBox();
box12.setBorder(spaceBorder1);
box13 = Box.createHorizontalBox();
box13.setBorder(spaceBorder2);
box14 = Box.createHorizontalBox();
box14.setBorder(spaceborder5);
box15 = Box.createVerticalBox();
box16 = Box.createHorizontalBox();
box16.setBorder(spaceBorder3);
box17 = Box.createHorizontalBox();
box17.setBorder(spaceBorder3);
box18 = Box.createHorizontalBox();
box18.setBorder(spaceBorder3);
box19 = Box.createHorizontalBox();
box19.setBorder(spaceBorder3);
box20 = Box.createHorizontalBox();
box20.setBorder(spaceBorder3);
box21 = Box.createHorizontalBox();
box21.setBorder(spaceBorder4);
box22 = Box.createVerticalBox();
MegaBox2 = Box.createVerticalBox();
JLabel Player1, Player2, P1Score, P2Score;
JButton P1Roll, P2Roll, EndTurn;
JLabel TurnNum, TurnMax, TurnsRem, P1TScore, P2TScore, Winner;
Player1 = new JLabel(NameBox1.getText() + ":");
P1Score = new JLabel("Score");
P1Roll = new JButton("Roll!");
Player2 = new JLabel(NameBox2.getText() + ":");
P2Score = new JLabel("Score");
P2Roll = new JButton("Roll!");
EndTurn = new JButton("End Turn");
TurnNum = new JLabel("Turn Number: ");
TurnMax = new JLabel("Turn max: ");
TurnsRem = new JLabel("Turns left: ");
P1TScore = new JLabel("Player 1 Score: ");
P2TScore = new JLabel("Player 2 Score: ");
Winner = new JLabel("Player is Winning");
box12.add(Player1);
box12.add(Box.createHorizontalGlue());
box12.add(P1Score);
box12.add(Box.createHorizontalGlue());
box12.add(P1Roll);
box13.add(Player2);
box13.add(Box.createHorizontalGlue());
box13.add(P2Score);
box13.add(Box.createHorizontalGlue());
box13.add(P2Roll);
box14.add(new JLabel(" "));
box14.add(Box.createHorizontalGlue());
box14.add(EndTurn);
box14.add(Box.createHorizontalGlue());
box14.add(new JLabel(" "));
box15.add(box23);
box15.add(box12);
box15.add(box13);
box15.add(box14);
box16.add(TurnNum);
box16.add(Box.createHorizontalGlue());
box16.add(new JLabel(" "));
box17.add(TurnMax);
box17.add(Box.createHorizontalGlue());
box17.add(new JLabel(" "));
box18.add(TurnsRem);
box18.add(Box.createHorizontalGlue());
box18.add(new JLabel(" "));
box19.add(P1TScore);
box19.add(Box.createHorizontalGlue());
box19.add(new JLabel(" "));
box20.add(P2TScore);
box20.add(Box.createHorizontalGlue());
box20.add(new JLabel(" "));
box21.add(new JLabel(" "));
box21.add(Box.createHorizontalGlue());
box21.add(Winner);
box22.add(box16);
box22.add(box17);
box22.add(box18);
box22.add(box19);
box22.add(box20);
box22.add(box21);
MegaBox2.add(box15);
MegaBox2.add(box22);
gFrame.add(MegaBox2);
gFrame.setVisible(true);
pFrame.setVisible(false);
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
}
}
});
}
}}
From an initial reading of the code, it appears you're creating the anonymous ActionListener with incorrect syntax.
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
Should be
P1Roll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e)
{
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- )
{
}
});

Categories