Setting foreground colour specific index of JComboBox - java

Changing foreground colour of a specified index of items in a JComboBox.
Eg,
if (number <= 1) { set the first item of the JComboBox to Red. }
Any way to do this without using CellRenderer? Never ever used CellRenderer before, no experience at all..
Already looked at these sites:
Changing a color chooser button's background color in Java,
Multiple Colors for Each Item in JComboBox, Colored jcombobox with colored items and focus
3rd one seems to be the most useful but no idea on how to implement..
Thank you.
Codes For Frame:
public class CreateBedForm extends JFrame {
private JPanel contentPane;
private JTextField textFieldPatientID;
private JTextField textFieldPatientName;
private JComboBox comboBoxAllocateBed;
private JComboBox comboBoxDpt;
private String bedStatusF = "Available";
private String selectedDepartment = "";
private int bedsAvailCardio;
private int bedsAvailOncology;
private int bedsAvailOrtho;
private int bedsAvailPediatric;
String[] departments = {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"};
Color comboBoxColour = new Color(0, 204, 0);
Color[] colorsForMain = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, comboBoxColour};
Color[] colorsForCardiothoracic = {Color.BLACK, Color.RED, comboBoxColour, comboBoxColour, comboBoxColour};
Color[] colorsForOncology = {Color.BLACK, comboBoxColour, Color.RED, comboBoxColour, comboBoxColour};
Color[] colorsForOrthopaedic = {Color.BLACK, comboBoxColour, comboBoxColour, Color.RED, comboBoxColour};
Color[] colorsForPediatric = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, Color.RED};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
CreateBedForm frame = new CreateBedForm("", "", "");
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CreateBedForm(String val1, String val2, String admissionID) {
setTitle("Assign Bed");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPatientId = new JLabel("Patient ID:");
lblPatientId.setBounds(42, 52, 71, 16);
contentPane.add(lblPatientId);
JLabel lblPatientName = new JLabel("Patient Name:");
lblPatientName.setBounds(42, 97, 96, 16);
contentPane.add(lblPatientName);
textFieldPatientID = new JTextField();
textFieldPatientID.setEditable(false);
textFieldPatientID.setBounds(138, 49, 116, 22);
contentPane.add(textFieldPatientID);
textFieldPatientID.setColumns(10);
textFieldPatientName = new JTextField();
textFieldPatientName.setEditable(false);
textFieldPatientName.setBounds(138, 94, 116, 22);
contentPane.add(textFieldPatientName);
textFieldPatientName.setColumns(10);
JLabel lblAllocatedBed = new JLabel("Allocated Bed:");
lblAllocatedBed.setBounds(42, 183, 96, 16);
contentPane.add(lblAllocatedBed);
comboBoxAllocateBed = new JComboBox();
comboBoxAllocateBed.setBounds(138, 180, 71, 22);
contentPane.add(comboBoxAllocateBed);
JLabel lblNewLabel = new JLabel("Department:");
lblNewLabel.setBounds(42, 142, 96, 16);
contentPane.add(lblNewLabel);
JButton btnAssignBed = new JButton("Assign Bed");
btnAssignBed.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Adding
String patientID = textFieldPatientID.getText();
String patientName = textFieldPatientName.getText();
String selectedDepartment = comboBoxDpt.getSelectedItem().toString();
String selectedBed = comboBoxAllocateBed.getSelectedItem().toString();
ChangeBed cb = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);
ChangeBedControl cbc = new ChangeBedControl();
cbc.processAssignBeds(cb, selectedBed);
//Updating
bedStatusF = "Unavailable";
ChangeBed cb2 = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);
ChangeBedControl cbc2 = new ChangeBedControl();
cbc2.processAssignBeds2(cb2, selectedBed, bedStatusF);
dispose();
File desktop = new File(System.getProperty("user.home"), "/Desktop");
Document document = new Document(PageSize.A4.rotate());
com.itextpdf.text.Font font1 = FontFactory.getFont("Verdana", 25, Font.BOLD);
com.itextpdf.text.Font font2 = FontFactory.getFont("Verdana", 15, Font.BOLD);
Paragraph p = new Paragraph(("Patient Admission Details"), font1);
Paragraph p1 = new Paragraph(("Admission ID"), font2);
Paragraph p2 = new Paragraph(("Patient ID"), font2);
Paragraph p3 = new Paragraph(("Patient Name"), font2);
Paragraph p4 = new Paragraph(("Date and Time Admitted"), font2);
Paragraph p5 = new Paragraph(("Reason"), font2);
Paragraph p6 = new Paragraph(("Date and Time Discharged"), font2);
Paragraph pp = new Paragraph(("Bed Allocation Details"), font1);
Paragraph p01 = new Paragraph(("Bed ID"), font2);
Paragraph p02 = new Paragraph(("Department"), font2);
try {
PageSize.A4.rotate();
PdfWriter.getInstance(document, new FileOutputStream(desktop + "/" + textFieldPatientName.getText() + " Admission.pdf"));
document.open();
document.add(p);
PdfPTable table = new PdfPTable(6);
table.setWidthPercentage(102);
PdfPCell cell1 = new PdfPCell();
cell1.addElement(p1);
PdfPCell cell2 = new PdfPCell();
cell2.addElement(p2);
PdfPCell cell3 = new PdfPCell();
cell3.addElement(p3);
PdfPCell cell4 = new PdfPCell();
cell4.addElement(p4);
PdfPCell cell5 = new PdfPCell();
cell5.addElement(p5);
PdfPCell cell6 = new PdfPCell();
cell6.addElement(p6);
AdmissionInfoControl aic1 = new AdmissionInfoControl();
ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();
admissionList = aic1.processGetAdmissionInfoView(admissionID);
PdfPCell ell1;
PdfPCell ell2;
PdfPCell ell3;
PdfPCell ell4;
PdfPCell ell5;
PdfPCell ell6;
for (int i = 0; i < admissionList.size(); i++) {
ell1 = new PdfPCell(new Paragraph(admissionList.get(i).getAdmissionID()));
ell2 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientID()));
ell3 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientName()));
ell4 = new PdfPCell(new Paragraph(admissionList.get(i).getDateAdmitted()));
ell5 = new PdfPCell(new Paragraph(admissionList.get(i).getReason()));
ell6 = new PdfPCell(new Paragraph(admissionList.get(i).getDateDischarged()));
table.setSpacingBefore(30f);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(ell1);
table.addCell(ell2);
table.addCell(ell3);
table.addCell(ell4);
table.addCell(ell5);
table.addCell(ell6);
}
document.add(table);
document.add(pp);
PdfPTable table2 = new PdfPTable(2);
table2.setHorizontalAlignment(Element.ALIGN_LEFT);
table2.setWidthPercentage(50);
PdfPCell cell01 = new PdfPCell();
cell01.addElement(p01);
PdfPCell cell02 = new PdfPCell();
cell02.addElement(p02);
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = cbc.processGetBedsEdit(textFieldPatientID.getText());
PdfPCell ell01;
PdfPCell ell02;
for (int i = 0; i < bedList.size(); i++) {
ell01 = new PdfPCell(new Paragraph(bedList.get(i).getBedID()));
ell02 = new PdfPCell(new Paragraph(bedList.get(i).getDepartment()));
table2.setSpacingBefore(30f);
table2.addCell(cell01);
table2.addCell(cell02);
table2.addCell(ell01);
table2.addCell(ell02);
}
document.add(table2);
document.close();
JOptionPane.showMessageDialog(null, "Admission PDF has been successfully created.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
}
});
btnAssignBed.setBounds(288, 303, 116, 25);
contentPane.add(btnAssignBed);
comboBoxDpt = new JComboBox();
comboBoxDpt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String departmentSelection = comboBoxDpt.getSelectedItem().toString();
ChangeBedControl cbcS = new ChangeBedControl();
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = cbcS.processGetAvailBedsEdit(bedStatusF, departmentSelection);
comboBoxAllocateBed.removeAllItems();
for (int i = 0; i < bedList.size(); i++) {
comboBoxAllocateBed.addItem(bedList.get(i).getBedID());
}
}
});
//comboBoxDpt.setModel(new DefaultComboBoxModel(new String[] {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"}));
comboBoxDpt = new JComboBox();
ComboBoxRenderer renderer = new ComboBoxRenderer(comboBoxDpt);
renderer.setColorsForMain(colorsForMain);
renderer.setDepartments(departments);
comboBoxDpt.setRenderer(renderer);
comboBoxDpt.setBounds(138, 139, 153, 22);
contentPane.add(comboBoxDpt);
ChangeBedControl cbc = new ChangeBedControl();
ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();
admissionList = cbc.processGetChangeBedCreate(val1, val2);
for (int i = 0; i < admissionList.size(); i++) {
textFieldPatientID.setText(admissionList.get(i).getPatientID());
textFieldPatientName.setText(admissionList.get(i).getPatientName());
}
//=============Distinct Feature=============
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
int selectedIndex = comboBoxDpt.getSelectedIndex() ;
String departmentComboBox;
ChangeBedControl cbc2 = new ChangeBedControl();
bedList = cbc2.processCountBedsAvailableDpt1();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailCardio = bedList.get(i).getRowCountAvail();
}
if (bedsAvailCardio <= 3) {
}
ChangeBedControl cbc4 = new ChangeBedControl();
bedList = cbc4.processCountBedsAvailableDpt2();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailOncology = bedList.get(i).getRowCountAvail();
}
if (bedsAvailOncology <= 3) {
}
ChangeBedControl cbc6 = new ChangeBedControl();
bedList = cbc6.processCountBedsAvailableDpt3();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailOrtho = bedList.get(i).getRowCountAvail();
}
if (bedsAvailOrtho <= 3) {
}
ChangeBedControl cbc8 = new ChangeBedControl();
bedList = cbc8.processCountBedsAvailableDpt4();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailPediatric = bedList.get(i).getRowCountAvail();
}
if (bedsAvailPediatric <= 3) {
}
}
}
Codes for ComboBoxRenderer Class:
public class ComboBoxRenderer implements ListCellRenderer{
private Color comboBoxColour;
private Color[] colorsForMain;
private Color[] colorsForCardiothoracic;
private Color[] colorsForOncology;
private Color[] colorsForOrthopaedic;
private Color[] colorsForPediatric;
private String[] departments;
public ComboBoxRenderer() {};
public ComboBoxRenderer(JComboBox comboBoxDpt) {
}
public String[] getDepartments() {
return departments;
}
public void setDepartments(String[] departments) {
this.departments = departments;
}
public Color getComboBoxColour() {
return comboBoxColour;
}
public void setComboBoxColour(Color comboBoxColour) {
this.comboBoxColour = comboBoxColour;
}
public Color[] getColorsForMain() {
return colorsForMain;
}
public void setColorsForMain(Color[] colorsForMain) {
this.colorsForMain = colorsForMain;
}
public Color[] getColorsForCardiothoracic() {
return colorsForCardiothoracic;
}
public void setColorsForCardiothoracic(Color[] colorsForCardiothoracic) {
this.colorsForCardiothoracic = colorsForCardiothoracic;
}
public Color[] getColorsForOncology() {
return colorsForOncology;
}
public void setColorsForOncology(Color[] colorsForOncology) {
this.colorsForOncology = colorsForOncology;
}
public Color[] getColorsForOrthopaedic() {
return colorsForOrthopaedic;
}
public void setColorsForOrthopaedic(Color[] colorsForOrthopaedic) {
this.colorsForOrthopaedic = colorsForOrthopaedic;
}
public Color[] getColorsForPediatric() {
return colorsForPediatric;
}
public void setColorsForPediatric(Color[] colorsForPediatric) {
this.colorsForPediatric = colorsForPediatric;
}
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return list;
}
}

If you look at the second link you provided you can see the following line of code:
static Color[] colors = {Color.BLUE, Color.GRAY, Color.RED};
Each index of the colors array matches the index of the String objects in the JComboBox.
In your case, because you want the first index to be red, you would make the first index of the color array to be red:
static Color[] colors = {Color.BLUE, Color.RED, Color.BLUE}; //Index # 1 is red.

Related

JTable not updating/refreshing when new model is set with data

Hey so I have a problem with my JTable where it is not updating the table when I set its model to a new one with data within it. I have checked and all the arrays have data values within them, coming from another class. The cData array has all the right strings and values. But it doesnt seem to update. Here is the code, I commented where I think it is going wrong:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class DetentionStats extends JPanel
{
private JLabel title, houseTitle;
private JPanel leftPanel, rightPanel, dormPanel, housePanel, dormButtonPanel, dormStatsPanel, ADormPanel, BDormPanel, CDormPanel, DDormPanel;
private JButton ADorm, BDorm, CDorm, DDorm, Update;
private JTable statsList, houseList;
private JScrollPane statsListScroll, houseListScroll;
private final int numberOfColumns = 4;
private String[] statsColumnNames = {"Name", "Reason"};
private String[] houseColumnNames = {"Name","Reason","Dorm","Completed"};
private ArrayList<Detention> completedDetentions;
private DefaultTableModel statsTable, updateCompleted, houseTable, aDormModel, bDormModel, cDormModel, dDormModel;
public DetentionStats()
{
completedDetentions = new ArrayList<Detention>();
title = new JLabel("Statistics");
title.setFont(new Font("Arial", Font.BOLD, 24));
title.setHorizontalAlignment(JLabel.CENTER);
title.setVerticalAlignment(JLabel.CENTER);
setLayout(new BorderLayout());
ADorm = new JButton("A Dorm");
DormListener aDormListener = new DormListener();
ADorm.addActionListener(aDormListener);
aDormModel = new DefaultTableModel(statsColumnNames, 0);
ADormPanel = new JPanel();
ADormPanel.add(ADorm);
ADormPanel.setPreferredSize(new Dimension(100, 50));
ADormPanel.setBackground(Color.lightGray);
BDorm = new JButton("B Dorm");
DormListener bDormListener = new DormListener();
BDorm.addActionListener(bDormListener);
bDormModel = new DefaultTableModel(statsColumnNames, 0);
BDormPanel = new JPanel();
BDormPanel.add(BDorm);
BDormPanel.setPreferredSize(new Dimension(100, 50));
BDormPanel.setBackground(Color.lightGray);
CDorm = new JButton("C Dorm");
DormListener cDormListener = new DormListener();
CDorm.addActionListener(cDormListener);
cDormModel = new DefaultTableModel(statsColumnNames, 0);
CDormPanel = new JPanel();
CDormPanel.add(CDorm);
CDormPanel.setPreferredSize(new Dimension(100, 50));
CDormPanel.setBackground(Color.lightGray);
DDorm = new JButton("D Dorm");
DormListener dDormListener = new DormListener();
DDorm.addActionListener(dDormListener);
dDormModel = new DefaultTableModel(statsColumnNames, 0);
DDormPanel = new JPanel();
DDormPanel.add(DDorm);
DDormPanel.setPreferredSize(new Dimension(100, 50));
DDormPanel.setBackground(Color.lightGray);
dormButtonPanel = new JPanel();
dormButtonPanel.setLayout(new GridLayout(2,2));
dormButtonPanel.add(ADormPanel);
dormButtonPanel.add(BDormPanel);
dormButtonPanel.add(CDormPanel);
dormButtonPanel.add(DDormPanel);
dormButtonPanel.setBackground(Color.lightGray);
//--------------------------------------------------------------------------------------------------------------------------
statsTable = new DefaultTableModel(statsColumnNames, 0);
statsList = new JTable(statsTable);
statsListScroll = new JScrollPane(statsList);
statsList.setPreferredScrollableViewportSize(new Dimension(470,260));
dormStatsPanel = new JPanel();
dormStatsPanel.add(statsListScroll);
dormStatsPanel.setBackground(Color.lightGray);
dormPanel = new JPanel();
dormPanel.setLayout(new GridLayout(2,1));
dormPanel.add(dormButtonPanel);
dormPanel.add(dormStatsPanel);
//---------------------------------------------------------------------------------------------------------------------------
houseTitle = new JLabel("Completed Detentions");
houseTitle.setFont(new Font("Arial", Font.BOLD, 14));
houseTitle.setHorizontalAlignment(JLabel.CENTER);
houseTitle.setVerticalAlignment(JLabel.CENTER);
Update = new JButton("Update");
UpdateListener uListener = new UpdateListener();
Update.addActionListener(uListener);
houseTable = new DefaultTableModel(houseColumnNames, 0);
houseList = new JTable(houseTable);
houseListScroll = new JScrollPane(houseList);
houseList.setPreferredScrollableViewportSize(new Dimension(470,540));
housePanel = new JPanel();
housePanel.setLayout(new BorderLayout());
housePanel.setBackground(Color.lightGray);
housePanel.add(Update, BorderLayout.EAST);
housePanel.add(houseTitle, BorderLayout.CENTER);
housePanel.add(houseListScroll, BorderLayout.SOUTH);
leftPanel = new JPanel();
leftPanel.add(dormPanel);
leftPanel.setBackground(Color.lightGray);
rightPanel = new JPanel();
rightPanel.add(housePanel);
rightPanel.setBackground(Color.lightGray);
add(title, BorderLayout.NORTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
setPreferredSize(new Dimension(1050,670));
setBackground(Color.lightGray);
setVisible(true);
}
public void completeDetention(Detention d)
{
completedDetentions.add(d);
updateCompletedDetentions();
dormSort();
}
private void dormSort()
{
Object[][] dData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
if(d.getDorm() == Detention.Dorm.aDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
aDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
bDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
cDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
dDormModel = new DefaultTableModel(dData, statsColumnNames);
}
}
}
private void updateCompletedDetentions()
{
Object[][] cData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
//-------------------------------------------
cData[i][0] = d.getName();
//-------------------------------------------
cData[i][1] = d.getReason();
//-------------------------------------------
if(d.getDorm() == Detention.Dorm.aDorm)
{
cData[i][2] = "A Dorm";
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
cData[i][2] = "B Dorm";
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
cData[i][2] = "C Dorm";
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
cData[i][2] = "D Dorm";
}
else
{
cData[i][2] = "No Dorm Selected";
}
//-------------------------------------------
cData[i][3] = new Boolean(true);
}
//this is where it is going wrong (i think)
updateCompleted = new DefaultTableModel(cData, houseColumnNames);
houseList.setModel(updateCompleted);
}
private class UpdateListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
updateCompletedDetentions();
dormSort();
}
}
private class DormListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == ADorm)
{
statsList.setModel(aDormModel);
}
else if(source == BDorm)
{
statsList.setModel(bDormModel);
}
else if(source == CDorm)
{
statsList.setModel(cDormModel);
}
else if(source == DDorm)
{
statsList.setModel(dDormModel);
}
}
}
}
Runnable example:
public class Table extends JPanel
{
private DefaultTableModel updateTable;
private String[] columnNames = {"Name","Last Name","Location"};
private JTable table;
public Table()
{
defaultTable = new JTable(columnNames, 0);
table = new JTable(defaultTable);
}
public void update()
{
Object[][] data = new Object[array.size()][numberOfColumns];
for(int i = 0; i < array.size(); i++)
{
Detention c = detentionArray.get(i)
data[i][0] = c.getFirstName();
data[i][1] = c.getLastName();
data[i][2] = c.getLocation();
}
updateTable = new DefaultTableModel(data, columnNames);
table.setModel(updateTable);
}
}
You might need to use this as last line in updateCompletedDetentions() method.
fireTableDataChanged();

Previous instance of table appends to the newly invoked table. The page should show only one table

When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}

Filtering a JTable in a Java program

I have a little problem about filtering a JTable.
Updating, Adding and Filtering stocks are working fine. When I add stocks, of course it will display on the table. Same with filtering, when I search any letter or word it will display or not depending if the searched product is available.
The problem is like this, when I tried to delete a specific product, it won't delete and an error will be shown as stated below. The error is about the changing of cell colors.
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at javax.swing.JTable.getValueAt(JTable.java:2719)
at javax.swing.JTable.prepareRenderer(JTable.java:5720)
at VapeShop.Inventory$1.prepareRenderer(Inventory.java:55)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at javax.swing.JComponent.paintComponent(JComponent.java:777)
at javax.swing.JComponent.paint(JComponent.java:1053)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5217)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1532)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1455)
at javax.swing.RepaintManager.paint(RepaintManager.java:1252)
at javax.swing.JComponent._paintImmediately(JComponent.java:5165)
at javax.swing.JComponent.paintImmediately(JComponent.java:4976)
at javax.swing.RepaintManager$3.run(RepaintManager.java:811)
at javax.swing.RepaintManager$3.run(RepaintManager.java:794)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:794)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:769)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:718)
at javax.swing.RepaintManager.access$1100(RepaintManager.java:62)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1680)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I tried removing the code about changing the cell colors but there still an error without stating what line it was. So I don't know what to do about it.
The error code is shown below:
Inventory.java:55 is the "Component c = super.prepareRenderer(r, data, columns);"
itemTable = new JTable(model){
public boolean isCellEditable(int data, int columns){
return false; //Cell Uneditable
}
public Component prepareRenderer(TableCellRenderer r, int data, int columns){ //Changing of Cell Colors
Component c = super.prepareRenderer(r, data, columns);
if(data % 2 == 0)
c.setBackground(Color.WHITE);
else
c.setBackground(Color.LIGHT_GRAY);
if(isCellSelected(data, columns))
c.setBackground(Color.GREEN);
return c;
}
};
This is the code of filtering my table:
else if(btnSource==btnSearch){
String getSearch = txtSearch.getText();
if(rowCount==0){
JOptionPane.showMessageDialog(null,"Inventory is Empty.","Note!",JOptionPane.ERROR_MESSAGE);
}
else{
sorter.setRowFilter (RowFilter.regexFilter (getSearch));
sorter.setSortKeys (null);
}
}
That's just my problem. I'm not sure if the problem is about filtering or deleting my table because if I remove the code about filtering, the program works fine but when I put it back again, error will be prompted.
Here is the full code:
package VapeShop;
import static VapeShop.Style.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Inventory extends JFrame{
static JPanel inventoryview;
JLabel bg, lblInventory;
JTextField txtInventory, txtSearch;
static JTable itemTable;
JButton btnSearch, btnAdd, btnBuy, btnDelete,
btnUpdate, btnLogout;
JScrollPane scrollPane;
final TableRowSorter sorter;
static Object[][] data = new Object[0][6];
static String[] columns = new String[6];
public Inventory(){
bg = new JLabel(new ImageIcon("C:\\Users\\DPdieciocho\\Documents\\NetBeansProjects\\Database 2\\src\\Images\\bg.png"));
add(bg);
inventoryview = new JPanel();
inventoryview.setLayout(null);
inventoryview.setOpaque(true);
inventoryview.setBorder(border);
inventoryview.setBackground(Color.DARK_GRAY);
inventoryview.setBounds(128, 85, 750, 400);
bg.add(inventoryview);
lblInventory = new JLabel("Inventory");
lblInventory.setFont(font5);
lblInventory.setForeground(Color.white);
lblInventory.setBounds(270, -2, 250, 45);
inventoryview.add(lblInventory);
txtInventory = new JTextField();
txtInventory.setBounds(-1, -1, 750, 50);
txtInventory.setEditable(false);
txtInventory.setOpaque(false);
txtInventory.setBorder(border);
inventoryview.add(txtInventory);
columns = new String[] {"No. of Stock", "Product Code", "Item", "Category", "Type", "Class", "Price (PHP)"};
DefaultTableModel model = new DefaultTableModel (data, columns);
itemTable = new JTable(model){
public boolean isCellEditable(int data, int columns){
return false; //Cell Uneditable
}
public Component prepareRenderer(TableCellRenderer r, int data, int columns){ //Changing of Cell Colors
Component c = super.prepareRenderer(r, data, columns);
if(data % 2 == 0)
c.setBackground(Color.WHITE);
else
c.setBackground(Color.LIGHT_GRAY);
if(isCellSelected(data, columns))
c.setBackground(Color.GREEN);
return c;
}
};
sorter = new TableRowSorter (model);
itemTable.setRowSorter (sorter);
itemTable.getTableHeader().setReorderingAllowed(false); //Undraggable Columns
itemTable.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); //Selecting a Single Row Only
scrollPane = new JScrollPane(itemTable);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(2, 80, 747, 320);
inventoryview.add(scrollPane);
buttons();
String e_smoke = "Images/smoke.png";
java.net.URL imgURL = getClass().getClassLoader().getResource(e_smoke);
ImageIcon smoke = new ImageIcon(imgURL);
JLabel lblImage = new JLabel(smoke);
lblImage.setBounds(0, 0, 1280, 500);
bg.add(lblImage);
ActionListener listener = new ButtonListener();
btnBuy.addActionListener(listener);
btnUpdate.addActionListener(listener);
btnSearch.addActionListener(listener);
btnAdd.addActionListener(listener);
btnDelete.addActionListener(listener);
btnLogout.addActionListener(listener);
}
public void buttons(){
String search = "Images/search.png";
java.net.URL imgURL = getClass().getClassLoader().getResource(search);
ImageIcon searchthis = new ImageIcon(imgURL);
txtSearch = new JTextField();
txtSearch.setFont(font6);
txtSearch.setBorder(border1);
txtSearch.setHorizontalAlignment(JTextField.CENTER);
txtSearch.setForeground(Color.BLACK);
txtSearch.setBounds(485, 55, 175, 20);
inventoryview.add(txtSearch);
btnSearch = new JButton(searchthis){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnSearch.setBounds(665, 53, 22, 22);
btnSearch.setFocusable(false);
btnSearch.setBackground(Color.gray);
btnSearch.setBorderPainted(false);
btnSearch.setToolTipText("Search Item");
btnSearch.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnSearch.setOpaque(false);
inventoryview.add(btnSearch);
String add = "Images/add.png";
java.net.URL imgURL1 = getClass().getClassLoader().getResource(add);
ImageIcon addthis = new ImageIcon(imgURL1);
btnAdd = new JButton(addthis){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnAdd.setBounds(693, 53, 22, 22);
btnAdd.setFocusable(false);
btnAdd.setBackground(Color.gray);
btnAdd.setBorderPainted(false);
btnAdd.setToolTipText("Add new Item");
btnAdd.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnAdd.setOpaque(false);
inventoryview.add(btnAdd);
String delete = "Images/delete.png";
java.net.URL imgURL3 = getClass().getClassLoader().getResource(delete);
ImageIcon deletethis = new ImageIcon(imgURL3);
btnDelete = new JButton(deletethis){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnDelete.setBounds(720, 53, 22, 22);
btnDelete.setFocusable(false);
btnDelete.setBackground(Color.gray);
btnDelete.setBorderPainted(false);
btnDelete.setToolTipText("Delete Item");
btnDelete.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnDelete.setOpaque(false);
inventoryview.add(btnDelete);
String buy = "Images/buy.png";
java.net.URL imgURL2 = getClass().getClassLoader().getResource(buy);
ImageIcon buythis = new ImageIcon(imgURL2);
btnBuy = new JButton(buythis){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnBuy.setBounds(10, 53, 22, 22);
btnBuy.setFocusable(false);
btnBuy.setBackground(Color.gray);
btnBuy.setBorderPainted(false);
btnBuy.setToolTipText("Buy new Item");
btnBuy.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnBuy.setOpaque(false);
inventoryview.add(btnBuy);
String update = "Images/update.png";
java.net.URL imgURL4 = getClass().getClassLoader().getResource(update);
ImageIcon updatethis = new ImageIcon(imgURL4);
btnUpdate = new JButton(updatethis){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnUpdate.setBounds(38, 53, 22, 22);
btnUpdate.setFocusable(false);
btnUpdate.setBackground(Color.gray);
btnUpdate.setBorderPainted(false);
btnUpdate.setToolTipText("Update Quantity");
btnUpdate.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnUpdate.setOpaque(false);
inventoryview.add(btnUpdate);
String out = "Images/logout.png";
java.net.URL imgURL5 = getClass().getClassLoader().getResource(out);
ImageIcon logout = new ImageIcon(imgURL5);
btnLogout = new JButton(logout){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setForeground(Color.BLACK);
tip.setBackground(Color.WHITE);
tip.setFont(font4);
return tip;
}
};
btnLogout.setBounds(965, 500, 18, 22);
btnLogout.setBackground(Color.gray);
btnLogout.setBorderPainted(false);
btnLogout.setToolTipText("Log out");
btnLogout.setCursor(new Cursor(Cursor.HAND_CURSOR));
btnLogout.setOpaque(false);
bg.add(btnLogout);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
Object btnSource = e.getSource();
int rowCount = itemTable.getRowCount();
int rowCheck = itemTable.getSelectedRow();
if(btnSource==btnBuy){
dispose();
new BuyItem().run();
}
else if(btnSource==btnUpdate){
if(rowCount==0){
JOptionPane.showMessageDialog(null,"Inventory is Empty.","Note!",JOptionPane.ERROR_MESSAGE);
}
else if(rowCheck<0){
JOptionPane.showMessageDialog(null,"Select the item to be updated.","Note!",JOptionPane.ERROR_MESSAGE);
}
else{
new UpdateItem().run();
}
}
else if(btnSource==btnSearch){
String getSearch = txtSearch.getText();
if(rowCount==0){
JOptionPane.showMessageDialog(null,"Inventory is Empty.","Note!",JOptionPane.ERROR_MESSAGE);
}
else{
sorter.setRowFilter (RowFilter.regexFilter (getSearch));
sorter.setSortKeys (null);
}
}
else if(btnSource==btnAdd){
dispose();
new AddItem().run();
}
else if(btnSource==btnDelete){
if(rowCount==0){
JOptionPane.showMessageDialog(null,"Inventory is Empty.","Note!",JOptionPane.ERROR_MESSAGE);
}
else if(rowCheck<0){
JOptionPane.showMessageDialog(null,"Select the item to be deleted.","Note!",JOptionPane.ERROR_MESSAGE);
}
else{
Object[][] temp = new Object[data.length-1][7];
for(int i=0; i<rowCheck; i++){
temp[i][0] = data[i][0];
temp[i][1] = data[i][1];
temp[i][2] = data[i][2];
temp[i][3] = data[i][3];
temp[i][4] = data[i][4];
temp[i][5] = data[i][5];
temp[i][6] = data[i][6];
}
for(int i=rowCheck+1; i<data.length; i++){
temp[i-1][0] = data[i][0];
temp[i-1][1] = data[i][1];
temp[i-1][2] = data[i][2];
temp[i-1][3] = data[i][3];
temp[i-1][4] = data[i][4];
temp[i-1][5] = data[i][5];
temp[i-1][6] = data[i][6];
}
data=temp;
itemTable.setModel(new DefaultTableModel(data, columns));
}
}
else if(btnSource==btnLogout){
int selected = JOptionPane.showConfirmDialog(null,"Are you sure you want to Sign out?","Confirm Sign Out",JOptionPane.YES_NO_OPTION);
if(selected == JOptionPane.YES_OPTION){
dispose();
new Admin().run();
}
else if(selected ==JOptionPane.NO_OPTION){
}
}
}
}
public void run(){
setSize(1000, 562);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public static void main(String[] args){
new Inventory().run();
}
}
I don't know how to fix this because this is my first time in using JTable.
Your delete method seems way too complicated. All you need to do use is use the removeRow(..) method of the DefaultTableModel.
The code would be something like:
//int index = table.getSelectedIndex();
int index = table.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.removeRow( table.convertRowIndexToModel( index );
If this doesn't help than post a proper SSCCE based on the tutorial example, not your current code.

Application not displaying GUI and won't quit Java

So I'm creating a game in Java and I ran into a little problem. Whenever I run the application the GUI does not show on the screen and the only way to close the application is to use the Windows Task Manager. In the application, you choose a username and click an enter button which creates a new window in which the game is played. But after you click the button, none of the GUI loads and you can't close the application.
Basically, when you click the button, a method is called that disposes the current window and starts the game window. The code for that method is below:
public void login(String name) {
String[] args={};
dispose();
SingleplayerGUI.main(args);
}
And here is the code of the SingleplayerGUI class:
public SingleplayerGUI(String userName, Singleplayer sp) {
this.userName = userName;
setResizable(false);
setTitle("Console Clash Singleplayer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e1) {
e1.printStackTrace();
}
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 28, 815, 30, 7 }; // SUM = 880
gbl_contentPane.rowHeights = new int[] { 25, 485, 40 }; // SUM = 550
contentPane.setLayout(gbl_contentPane);
history = new JTextPane();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret) history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 2;
scrollConstraints.gridheight = 2;
scrollConstraints.weightx = 1;
scrollConstraints.weighty = 1;
scrollConstraints.insets = new Insets(0, 0, 5, -64);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 25);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(txtMessage, gbc_txtMessage);
chat = new JTextPane();
chat.setEditable(false);
JScrollPane chatscroll = new JScrollPane(chat);
caret = (DefaultCaret) chat.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints chatscrollConstraints = new GridBagConstraints();
chatscrollConstraints.insets = new Insets(0, 0, 5, 5);
chatscrollConstraints.fill = GridBagConstraints.BOTH;
chatscrollConstraints.gridx = 0;
chatscrollConstraints.gridy = 0;
chatscrollConstraints.gridwidth = 2;
chatscrollConstraints.gridheight = 2;
chatscrollConstraints.weightx = 1;
chatscrollConstraints.weighty = 1;
chatscrollConstraints.insets = new Insets(150, 600, 5, -330);
contentPane.add(chatscroll, chatscrollConstraints);
chatMessage = new JTextField();
final String name = this.userName;
chatMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
chatconsole(name + ": " + chatMessage.getText());
}
}
});
GridBagConstraints gbc_chatMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(000, 600, 000, -330);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(chatMessage, gbc_txtMessage);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 275);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
gbc_btnSend.weightx = 0;
gbc_btnSend.weighty = 0;
contentPane.add(btnSend, gbc_btnSend);
list = new JList();
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 600, 330, -330);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
gbc_list.gridwidth = 2;
gbc_list.gridheight = 2;
JScrollPane p = new JScrollPane();
p.setViewportView(list);
contentPane.add(p, gbc_list);
list.setFont(new Font("Verdana", 0, 24));
System.out.println("HEY");
setVisible(true);
new SwingWorker<Void, String>() {
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()) {
String line = s.nextLine();
publish(line);
}
return null;
}
#Override protected void process(java.util.List<String> chunks) {
for (String line : chunks) {
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), line + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
}
}.execute();
Singleplayer spp = new Singleplayer();
Singleplayer.startOfGame();
setVisible(true);
}
public static void console(String message, Color color) {
txtMessage.setText("");
try {
StyledDocument doc = history.getStyledDocument();
Style style = history.addStyle("", null);
StyleConstants.setForeground(style, color);
doc.insertString(doc.getLength(), message + "\r\n", style);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void console(String message) {
txtMessage.setText("");
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public void chatconsole(String message) {
chatMessage.setText("");
try {
Document doc = chat.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void single() {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
public static void main(String[] args) {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
And the singleplayer class:
public static void startOfGame(){
System.out.println("HEY");
SingleplayerGUI.console("Welcome to Console Clash Pre Alpha Version 1!");
SingleplayerGUI.console("Created by Drift");
SingleplayerGUI.console("Published by Boring Games");
SingleplayerGUI.console("");
SingleplayerGUI.console("");
menuScreen();
}
static void menuScreen() {
Scanner scan = new Scanner(System.in);
System.out.println("To play the game, type 'start'. To quit, type 'quit'.");
String menu = scan.nextLine();
if (menu.equals("start")) {
start();
} else if (menu.equals("quit")) {
quit();
} else {
menuScreen();
}
}
private static void quit() {
SingleplayerGUI.console("You quit the game.");
}
private static void start() {
SingleplayerGUI.console("You started the game.");
}
So far I've figured out that the problem most likey occurs when adding the outPipe to the console. Would I be able to fix this or am I just not able to use outPipes with this application?
Thanks in advance for your help.
The setVisible() method is invoked twice.. Remove the second setVisible() call after the Singleplayer.startOfGame(); line in SingleplayerGUI constructor.

Exception in Text Analysis depending on length of a chosen value of JComboBox

I'm very surprised of this superior site!
My Goal is to get a .txt-file, read it in, cut it in single strings depending on which "windowsize" is chosen (how many characters, chosen by a jcombobox) and list it by frequency.
With debugging, it stops where the comment is marked.
I can't eliminate those thrown exceptions:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at xxxx.Babbles_GUI.windowSize(Babbles_GUI.java:247) at
xxxx.Babbles_GUI.actionPerformed(Babbles_GUI.java:203) at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at
java.awt.Component.processEvent(Component.java:6140) at
java.awt.Container.processEvent(Container.java:2083) at
java.awt.Component.dispatchEventImpl(Component.java:4737) at
java.awt.Container.dispatchEventImpl(Container.java:2141) at
java.awt.Component.dispatchEvent(Component.java:4565) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127) at
java.awt.Window.dispatchEventImpl(Window.java:2482) at
java.awt.Component.dispatchEvent(Component.java:4565) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684) at
java.awt.EventQueue.access$000(EventQueue.java:85) at
java.awt.EventQueue$1.run(EventQueue.java:643) at
java.awt.EventQueue$1.run(EventQueue.java:641) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:657) at
java.awt.EventQueue$2.run(EventQueue.java:655) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:654) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Code
public class Analysis {
/**
* #param file
*/
public static void analyze(File file, int windowSize) {
ArrayList<String> splittedText = new ArrayList<String>();
System.out.println(windowSize);
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line);
splittedText.add(line);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String wholeString = buf.toString();
// for (int i = 0; i < wholeString.length(); i += (Babbles_GUI
// .WindowSize())) {
// splittedText.add(wholeString.substring(
// i,
// Math.min(i + (Babbles_GUI.WindowSize()),
// wholeString.length())));
// }
// for (int i = 0; (i < wholeString.length()-(Babbles_GUI.WindowSize())); i += Babbles_GUI.WindowSize()) {
// splittedText.add(wholeString.substring(i, Math.min(Babbles_GUI.WindowSize()+i, wholeString.length())));
// }
for(int i = 0; i<wholeString.length()-(windowSize); i++){
splittedText.add(wholeString.substring(i, i+windowSize));
}
System.out.println("error");
Set<String> unique = new HashSet<String>(splittedText);
for (String key : unique) {
Babbles_GUI.txtAnalysis.append(Collections.frequency(splittedText,
key) + "x " + key + "\t" + "\t");
}
Babbles_GUI.txtLog.append("Text analyzed with WindowSize "
+ windowSize + "\n");
}
}
Babbles_GUI
public class Babbles_GUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JFileChooser fc1;
JButton btnFileCh;
JButton btnOutput;
JLabel lblBtnLabel;
static JTextArea txtLog;
static JTextArea txtOrig;
static JTextArea txtAnalysis;
JTextArea txtGenerated;
static JComboBox cbxWindowSize;
BorderLayout borderlayout;
JScrollPane ScrLog;
private JPanel pnWest;
private JPanel pnEast;
private JPanel pnNorth;
private JPanel pnCenter;
private JPanel pnSouth;
static int numberofchars;
public Babbles_GUI(String title) {
this.setTitle(title);
this.setSize(1200, 2400);
this.createUI();
this.setVisible(true);
this.setResizable(false);
this.pack();
this.setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width - this
.getSize().width) / 2, (Toolkit.getDefaultToolkit()
.getScreenSize().height - this.getSize().height) / 2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
private void createUI() {
btnFileCh = new JButton("Open...");
// btnFileCh.setForeground(Color.BLACK);
btnFileCh.setFont(new Font("Monospaced", Font.PLAIN, 14));
btnFileCh.setPreferredSize(new Dimension(100, 20));
btnFileCh.addActionListener(this);
lblBtnLabel = new JLabel("Number of letters to shuffle: ");
lblBtnLabel.setFont(new Font("Monospaced", Font.BOLD, 14));
lblBtnLabel.setForeground(Color.WHITE);
txtLog = new JTextArea();
txtLog.setBackground(getBackground());
txtLog.setBackground(Color.BLACK);
txtLog.setForeground(Color.WHITE);
txtLog.setWrapStyleWord(true);
txtLog.setLineWrap(true);
txtLog.setFont(new Font("Monospaced", Font.PLAIN, 13));
JScrollPane spTxtlog = new JScrollPane(txtLog);
spTxtlog.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
spTxtlog.setBorder(BorderFactory.createMatteBorder(5, 0, 0, 0,
Color.RED));
txtOrig = new JTextArea();
txtOrig.setEditable(false);
txtOrig.setWrapStyleWord(true);
txtOrig.setLineWrap(true);
txtOrig.setBackground(Color.BLACK);
txtOrig.setForeground(Color.WHITE);
txtOrig.setFont(new Font("Monospaced", Font.PLAIN, 15));
txtOrig.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.BLUE));
txtAnalysis = new JTextArea();
txtAnalysis.setEditable(false);
txtAnalysis.setWrapStyleWord(true);
txtAnalysis.setLineWrap(true);
txtAnalysis.setBackground(Color.BLACK);
txtAnalysis.setForeground(Color.WHITE);
txtAnalysis.setFont(new Font("Monospaced", Font.PLAIN, 15));
txtAnalysis.setBorder(new EmptyBorder(20, 0, 0, 20));
JScrollPane spTxtAn = new JScrollPane(txtAnalysis);
spTxtAn.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.GREEN));
btnOutput = new JButton("Generate");
btnOutput.addActionListener(this);
btnOutput.setForeground(Color.BLACK);
btnOutput.setFont(new Font("Monospaced", Font.PLAIN, 14));
btnOutput.setPreferredSize(new Dimension(100, 20));
String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
"WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
JComboBox cbxWindowSize = new JComboBox(item);
cbxWindowSize.setFont(new Font("Monospaced", Font.PLAIN, 14));
cbxWindowSize.setPreferredSize(new Dimension(200, 20));
Box bxLeft = Box.createHorizontalBox();
bxLeft.add(lblBtnLabel);
bxLeft.add(cbxWindowSize);
Box bxCenter = Box.createHorizontalBox();
bxCenter.add(btnFileCh);
Box bxRight = Box.createHorizontalBox();
bxRight.add(btnOutput);
txtGenerated = new JTextArea();
txtGenerated.setEditable(false);
txtGenerated.setBackground(Color.BLACK);
txtGenerated.setForeground(Color.WHITE);
txtGenerated.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.YELLOW));
pnWest = new JPanel();
pnEast = new JPanel();
pnNorth = new JPanel();
pnCenter = new JPanel();
pnSouth = new JPanel();
pnWest.setLayout(new BorderLayout());
pnWest.setBorder(new EmptyBorder(0, 0, 0, 10));
pnWest.setBackground(Color.BLACK);
pnEast.setLayout(new BorderLayout());
pnEast.setBorder(new EmptyBorder(0, 10, 0, 0));
pnEast.setBackground(Color.BLACK);
pnNorth.setLayout(new FlowLayout(FlowLayout.LEFT));
pnNorth.setBackground(Color.BLACK);
pnCenter.setLayout(new BorderLayout());
pnCenter.setBackground(Color.BLACK);
pnSouth.setLayout(new BorderLayout());
try {
this.fc1 = new JFileChooser();
fc1.setFileFilter(new FileNameExtensionFilter(null, "txt"));
} catch (IllegalArgumentException e) {
txtOrig.append("");
txtLog.append("File format must be .txt" + "\n");
}
pnNorth.add(bxLeft);
pnNorth.add(bxCenter);
pnNorth.add(bxRight);
pnSouth.add(spTxtlog, BorderLayout.SOUTH);
pnWest.add(txtOrig, BorderLayout.CENTER);
pnWest.setPreferredSize(new Dimension(400, 700));
pnCenter.add(spTxtAn, BorderLayout.CENTER);
pnCenter.setPreferredSize(new Dimension(400, 700));
pnEast.add(txtGenerated, BorderLayout.CENTER);
pnEast.setPreferredSize(new Dimension(400, 700));
borderlayout = new BorderLayout();
borderlayout.setHgap(30);
borderlayout.setVgap(3);
setBackground(Color.BLACK);
getContentPane().setLayout(borderlayout);
getContentPane().add(pnEast, BorderLayout.EAST);
getContentPane().add(pnWest, BorderLayout.WEST);
getContentPane().add(pnNorth, BorderLayout.NORTH);
getContentPane().add(pnCenter, BorderLayout.CENTER);
getContentPane().add(pnSouth, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnFileCh) {
int returnVal = fc1.showOpenDialog(Babbles_GUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc1.getSelectedFile();
txtLog.append(file.getName() + " opened" + "\n");
printOrigFile(file);
//DEBUG-STOP**********************************
Analysis.analyze(file, windowSize());
} else {
txtLog.append("Open command cancelled by user" + "\n");
}
txtLog.setCaretPosition(txtLog.getDocument().getLength());
}
}
public static void main(String[] args) {
new Babbles_GUI("Babbles Exercise David Huser");
}
/**
* #param file
* #return
*/
public String printOrigFile(File file) {
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
txtOrig.setText(buf.toString());
return (buf.toString());
}
public int windowSize() {
if (cbxWindowSize.getSelectedItem().equals("WindowSize 1")) {
numberofchars = 1;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 2")) {
numberofchars = 2;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 3")) {
numberofchars = 3;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 4")) {
numberofchars = 4;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 5")) {
numberofchars = 5;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 6")) {
numberofchars = 6;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 7")) {
numberofchars = 7;
}
return numberofchars;
}
}
You have an object that is null in windowSize(). Are you sure cbxWindowSize is initialized?
The other possibility is that there is no selected item. getSelectedItem() will return null in that case. You need to check this instead of immediately calling equals() on the result.
Edit:
String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
"WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
JComboBox cbxWindowSize = new JComboBox(item);
This defines a new local variable and initializes it. The local variable is hiding the class variable with the same name. Remove JComboBox from the beginning of the line.

Categories