I know there are already many topics on this issue but I promise you I have exhausted the search.
At the opening of my application, the "ExampleGUI" window should display, when a Calendar button is clicked a Calendar Frame pops up and the user chooses a date, which is represented as a String. This string, along with some other information, is passed back to the ExampleGUI, as a new ExampleGUI. It will then go to the method updateDate, which should display the date that the user chose on the current frame, as a JLabel. However, no matter what I try, the JLabel will not display or will not update. I know about SetText, it's not currently included in my code but I have tried it and it doesn't work. I know it is passing the date correctly because System.out.println will work fine. If you have any help I will be forever grateful I am officially stumped.
UPDATE
Added the most pared down code I could make -- sorry the Calendar is so long, I couldn't take much out but I promise it is not the problem you just need it to run the GUI where the problem resides.
Thanks!
CODE:
Runner Class:
import java.awt.EventQueue;
public class Runner {
public Runner() {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
GUI Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(source);
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
}else{
}
}
}
Calendar Class:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class Calndar extends JFrame {
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(String SoE) {
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(
new Object[][] { { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, },
new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date", "Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-" + returnedDAY);
return FinalDate;
}
public String getFinalDate(){
if(FinalDate.equals(null)){
String str = new String("None");
return str;
}else{
return FinalDate;
}
}
}
Your problem is here:
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE); // *****************
dispose();
}
}
});
You are creating a new GUI object, one completely distinct from the currently displayed GUI instance.
suggestions:
The new window should not be a JFrame but should be a modal JDialog. If it is a modal dialog, it will freeze the calling code from the point that it is set visible, and then that code will resume flow once the dialog is no longer visible.
Set this dialog visible from the original class, the GUI's ActionListener.
Don't have Calndar object change anything in GUI. Rather in its action listener store the selected date (if anything is selected) in a field, and dispose of the dialog.
Then the calling class, here GUI can query the Calndar object once it is no Calndar is longer visible, within GUI's select ActionListener, but after Calndar is set visible, and extract the selected date by calling a public getter method on the Calndar object.
Then GUI can use this information to update its visualized data.
Call revalidate and repaint after adding or removing components from a running GUI.
In the future, try to use only 1 file for your example program.
For example. Note in the code below major changes are commented with // !!:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.GregorianCalendar;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(GUI.this, source); // !!
startCal.setVisible(true); // !!
String finalDate = startCal.getFinalDate();
updateDate(finalDate, source); // !!
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
revalidate(); // !!
repaint(); // !!
} else {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
class Calndar extends JDialog { // !!
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(GUI gui, final String SoE) { // !!
super(gui, "Calndar Title", ModalityType.APPLICATION_MODAL); // !!
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(new Object[][] {
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, }, new String[] {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
// !! GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
// setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-"
+ returnedDAY);
return FinalDate;
}
public String getFinalDate() {
if (FinalDate.equals(null)) {
String str = new String("None");
return str;
} else {
return FinalDate;
}
}
}
Also:
I wouldn't add a JLabel when adding the date in the main GUI. Rather I'd create a JLabel field, add it to the GUI initially, and then simply set its text when the need arises.
Related
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();
ive searched online for the answer for a few hours now, so far i havent found anything helpful, i have a JDialog that is supposed to send an object back to the JPanel that called it, after running the code several times i noticed that the JPanel Constructor Finishes before i can press the Save button inside the JDialog,
my problem is this,
how do i pass the object from the JDialog to the JPanel and in which part of the Jpanel Code do i write it?
Here is the JPanel Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AquaPanel extends JPanel implements ActionListener
{
private JFrame AQF;
private BufferedImage img;
private HashSet<Swimmable> FishSet;
private int FishCount;
private AddAnimalDialog JDA;
public AquaPanel(AquaFrame AQ)
{
super();
FishCount=0;
this.setSize(800, 600);
this.AQF = AQ;
gui();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
// if(!FishSet.isEmpty())
// {
// Iterator ITR = FishSet.iterator();
//
// while(ITR.hasNext())
// {
// ((Swimmable) ITR.next()).drawAnimal(g);
// }
// }
}
private void AddAnim()
{
Swimmable test = null;
JDA = new AddAnimalDialog(test);
JDA.setVisible(true);//shows jdialog box needs to set to false on new animal
}
private void Sleep()
{
}
private void Wake()
{
}
private void Res()
{
}
private void Food()
{
}
private void Info()
{
}
private void gui()
{
JPanel ButtonPanel = new JPanel();
Makebuttons(ButtonPanel);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
ButtonPanel.setLayout(new GridLayout(1,0));
this.add(ButtonPanel,BorderLayout.SOUTH);
}
private void Makebuttons(JPanel ButtonPanel)
{
JButton Addanim = new JButton("Add Animal");
Addanim.setBackground(Color.LIGHT_GRAY);
Addanim.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AddAnim();
}
});
JButton Sleep = new JButton("Sleep");
Sleep.setBackground(Color.LIGHT_GRAY);
Sleep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Sleep();
}
});
JButton Wake = new JButton("Wake Up");
Wake.setBackground(Color.LIGHT_GRAY);
Wake.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Wake();
}
});
JButton Res = new JButton("Reset");
Res.setBackground(Color.LIGHT_GRAY);
Res.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Res();
}
});
JButton Food = new JButton("Food");
Food.setBackground(Color.LIGHT_GRAY);
Food.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Food();
}
});
JButton Info = new JButton("Info");
Info.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Info();
}
});
Info.setBackground(Color.LIGHT_GRAY);
JButton ExitAQP = new JButton("Exit");
ExitAQP.setBackground(Color.LIGHT_GRAY);
ExitAQP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ButtonPanel.add(Addanim);
ButtonPanel.add(Sleep);
ButtonPanel.add(Wake);
ButtonPanel.add(Res);
ButtonPanel.add(Food);
ButtonPanel.add(Info);
ButtonPanel.add(ExitAQP);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()=="Confirm Add")
{
if(JDA.GetDone())
{
FishSet.add(JDA.GetAnim()) ;
JOptionPane.showMessageDialog(this, JDA.GetAnim().getAnimalName());
}
}
}
public void setBackgr(int sel)
{
switch (sel)
{
case 0:
img=null;
this.setBackground(Color.WHITE);
break;
case 1:
img=null;
this.setBackground(Color.BLUE);
break;
case 2:
try {
img = ImageIO.read(new File("src/aquarium_background.jpg"));
} catch (IOException e) {
System.out.println("incorrect input image file path!!!!");
e.printStackTrace();
}
}
}
private void ConfirmAnimal()
{
if(JDA.GetAnim()!=null)
{
JOptionPane.showMessageDialog(this, "fish exists");
}
else
{
JOptionPane.showMessageDialog(this, "fish doesn't exists");
}
}
}
and the JDialog Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddAnimalDialog extends JDialog
{
private JTextField SizeField;
private JTextField HSpeedField;
private JTextField VSpeedField;
private int SelectedAnimal;
private int SelectedColor;
private Boolean IsDone;
private JButton SaveBTN;
Swimmable Animal;
public AddAnimalDialog(Swimmable Anim)
{
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
IsDone = false;
gui();
Anim = Animal;
}
private void gui()
{
this.setSize(new Dimension(400, 300));
JPanel panel = new JPanel();
this.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{151, 62, 63, 0};
gbl_panel.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel AnimName = new JLabel("Animal Type:");
GridBagConstraints gbc_AnimName = new GridBagConstraints();
gbc_AnimName.insets = new Insets(0, 0, 5, 5);
gbc_AnimName.gridx = 0;
gbc_AnimName.gridy = 1;
panel.add(AnimName, gbc_AnimName);
JComboBox AnimTypecomboBox = new JComboBox();
AnimTypecomboBox.addItem("Fish");
AnimTypecomboBox.addItem("Jellyfish");
GridBagConstraints gbc_AnimTypecomboBox = new GridBagConstraints();
gbc_AnimTypecomboBox.insets = new Insets(0, 0, 5, 5);
gbc_AnimTypecomboBox.anchor = GridBagConstraints.NORTH;
gbc_AnimTypecomboBox.gridx = 1;
gbc_AnimTypecomboBox.gridy = 1;
panel.add(AnimTypecomboBox, gbc_AnimTypecomboBox);
JLabel AnimSize = new JLabel("Size(between 20 to 320):");
GridBagConstraints gbc_AnimSize = new GridBagConstraints();
gbc_AnimSize.insets = new Insets(0, 0, 5, 5);
gbc_AnimSize.gridx = 0;
gbc_AnimSize.gridy = 2;
panel.add(AnimSize, gbc_AnimSize);
SizeField = new JTextField();
GridBagConstraints gbc_SizeField = new GridBagConstraints();
gbc_SizeField.insets = new Insets(0, 0, 5, 5);
gbc_SizeField.fill = GridBagConstraints.HORIZONTAL;
gbc_SizeField.gridx = 1;
gbc_SizeField.gridy = 2;
panel.add(SizeField, gbc_SizeField);
SizeField.setColumns(10);
JLabel HSpeed = new JLabel("Horizontal Speed(between 1 to 10):");
GridBagConstraints gbc_HSpeed = new GridBagConstraints();
gbc_HSpeed.insets = new Insets(0, 0, 5, 5);
gbc_HSpeed.gridx = 0;
gbc_HSpeed.gridy = 3;
panel.add(HSpeed, gbc_HSpeed);
HSpeedField = new JTextField();
GridBagConstraints gbc_HSpeedField = new GridBagConstraints();
gbc_HSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_HSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_HSpeedField.gridx = 1;
gbc_HSpeedField.gridy = 3;
panel.add(HSpeedField, gbc_HSpeedField);
HSpeedField.setColumns(10);
JLabel VSpeed = new JLabel("Vertical Speed(between 1 to 10):");
GridBagConstraints gbc_VSpeed = new GridBagConstraints();
gbc_VSpeed.insets = new Insets(0, 0, 5, 5);
gbc_VSpeed.gridx = 0;
gbc_VSpeed.gridy = 4;
panel.add(VSpeed, gbc_VSpeed);
VSpeedField = new JTextField();
GridBagConstraints gbc_VSpeedField = new GridBagConstraints();
gbc_VSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_VSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_VSpeedField.gridx = 1;
gbc_VSpeedField.gridy = 4;
panel.add(VSpeedField, gbc_VSpeedField);
VSpeedField.setColumns(10);
JLabel lblAnimalColor = new JLabel("Animal Color:");
GridBagConstraints gbc_lblAnimalColor = new GridBagConstraints();
gbc_lblAnimalColor.insets = new Insets(0, 0, 5, 5);
gbc_lblAnimalColor.gridx = 0;
gbc_lblAnimalColor.gridy = 5;
panel.add(lblAnimalColor, gbc_lblAnimalColor);
JComboBox ColorComboBox = new JComboBox();
ColorComboBox.setModel(new DefaultComboBoxModel(new String[] {"Red", "Magenta", "Cyan", "Blue", "Green"}));
GridBagConstraints gbc_ColorComboBox = new GridBagConstraints();
gbc_ColorComboBox.insets = new Insets(0, 0, 5, 5);
gbc_ColorComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_ColorComboBox.gridx = 1;
gbc_ColorComboBox.gridy = 5;
panel.add(ColorComboBox, gbc_ColorComboBox);
JButton btnAddAnimal = new JButton("Confirm Add");
GetInput(btnAddAnimal,AnimTypecomboBox,ColorComboBox);
GridBagConstraints gbc_btnAddAnimal = new GridBagConstraints();
gbc_btnAddAnimal.insets = new Insets(0, 0, 0, 5);
gbc_btnAddAnimal.gridx = 0;
gbc_btnAddAnimal.gridy = 9;
panel.add(btnAddAnimal, gbc_btnAddAnimal);
JButton btnClear = new JButton("Clear");
GridBagConstraints gbc_btnClear = new GridBagConstraints();
gbc_btnClear.gridx = 2;
gbc_btnClear.gridy = 9;
panel.add(btnClear, gbc_btnClear);
}
private Color Getcolor(Object obj)
{
Color clr=Color.RED;
if(obj instanceof String)
{
switch((String)obj)
{
case "Red":
clr = Color.RED;
break;
case "Magenta":
clr = Color.MAGENTA;
break;
case "Cyan":
clr = Color.CYAN;
break;
case "Blue":
clr = Color.BLUE;
break;
case "Green":
clr = Color.GREEN;
break;
}
}
return clr;
}
private Fish MakeFish(int size,Color col,int horSpeed,int verSpeed)
{
return new Fish(size,col,horSpeed,verSpeed);
}
private Jellyfish MakeJellyfish(int size,Color col,int horSpeed,int verSpeed)
{
return new Jellyfish(size,col,horSpeed,verSpeed);
}
public Swimmable GetAnim()
{
return Animal;
}
public Boolean GetDone()
{
return IsDone;
}
private void GetInput(JButton Jbtn,JComboBox type,JComboBox col)
{
Jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Fish"))
{
Color clr=Color.RED;
Object tmp = col.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeFish(size,clr,Hspeed,VSpeed);
}
else if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Jellyfish"))
{
Color clr=Color.RED;
Object tmp = type.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeJellyfish(size,clr,Hspeed,VSpeed);
}
IsDone=true;
Hide();
SaveBTN = Jbtn;
}
});
}
private void Hide()
{
this.setVisible(false);
}
public JButton GetBTN()
{
return SaveBTN;
}
}
So in short in the JDialog i need to get information from comboboxes and texfields and send that data to an object constructor, and on the "Save" button click i need to transfer the Object from the JDialog that i created with the constructor to the JPanel, how do i do it?
i realized i can send the JPanel to the JDialog and in the JDialog's code where i create the object, i modify the Jpanel's Hashset accordingly
from my MainFrame I create a internal Frame and add that to my desktop pane, but the internal Frame just won't show up. I tried to figure it out for 3 hours now and I kinda need some help with it. Before I implemented the observer pattern it just worked fine. So I thought it got something to do with that and changed some stuff and double checked the crucial code. No solution so far. I just realized how crappy my english is sometimes. Sorry for that!
The 2 code blocks are already shortened. Sorry that they are still pretty long. But I am just not sure where I made the mistake. If you need more code or anything else, just tell me. Thank you very much in advance.
This is the code of my main frame:
public class LangtonsAmeise extends JFrame implements ActionListener {
private JDesktopPane desk;
private JPanel panelButtons;
JMenuBar jmb;
JMenu file,modus;
JMenuItem load,save, exit, mSetzen,mMalen,mLaufen;
JSlider slider;
static int xInt, yInt,xFrame=450,yFrame=450;
static boolean bSetzen = false, bMalen = false, running = false;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText,status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
/* Those 4 lines work just fine. Internal Frame gets displayed.
JInternalFrame j = new JInternalFrame();
desk.add(j);
j.setSize(new Dimension(300,300));
j.setVisible(true);
*/
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
xField.setDocument(new IntegerDocument(2));
yField.setDocument(new IntegerDocument(2));
start = new JButton("Fenster erstellen");
stop = new JButton("Stopp");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(slider);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Aktueller Modus:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("Datei");
modus = new JMenu("Modus");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(save);
file.add(load);
file.addSeparator();
file.add(exit);
save.addActionListener(this);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(1000, 900));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
new popUpWindow(
"Sie müssen eine Zahl zwischen 2 und 99 angeben!!");
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, xInt, yInt);
s.addObserver(k);
addChild(k, this.getSize().width, this.getSize().height);
}
}
if (e.getActionCommand().equals("Stopp")) {
running=!running;
status.setText("Stopp");
}
}
public void addChild(JInternalFrame kind, int xPixel, int yPixel) {
// kind.setSize(370, 370);
kind.setLocation(randomGenerator.nextInt(xPixel - kind.getSize().height),
randomGenerator.nextInt(yPixel - kind.getSize().height - 100));
kind.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
desk.add(kind);
kind.setVisible(true);
kind.repaint();
kind.validate();
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
And this is my Internal Frame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
static int sleeptime;
state s;
ArrayList<JButton> jbArray = new ArrayList<>();
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
public static ArrayList<AmeiseThread> threadList = new ArrayList<>();
Color alteFarbe, neueFarbe;
JButton save, addAnt;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,int x, int y) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
setSize(new Dimension(xFrame, yFrame));
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(y, x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("Simulation speichern");
addAnt = new JButton("Ameise hinzufügen");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (threadList.size() >= 0) {
for (AmeiseThread t : threadList) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
sleeptime = 1000 / speed;
}
}
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
setVisible(true);
repaint();
validate();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Ameise hinzufügen")) {
threadList.add(new AmeiseThread(this));
threadList.get(threadList.size() - 1).start();
}
if (e.getActionCommand().equals("Simulation speichern")) {
OutputStream fos = null;
try {
fos = new FileOutputStream("test");
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(this );
} catch (IOException e1) {
System.err.println(e1);
} finally {
try {
fos.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
I think it is because you didn't set size for your JInternalFrame. In your code it is as a comment:
//kind.setSize(370, 370);
when I remove "//" it works for me.
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.
My code is still heavily in progress but my problem is that my class that extends JTable will not display in a JFrame. Here is my class that extends JTable. Secondly, I would like to know if the design option of making my LotteryTable an entirely new class a good idea.
At first, my LotteryDisplay contained a JTable which then was adjusted through a method tableSetup() which is now in LotteryTable.
public class LotteryTable extends JTable
{
private final String[] columnNames = {"Powerball Combos", "Odds of Winning", "Payout", "Number of Wins", "Win Frequency"};
JTable table;
public LotteryTable()
{
DefaultTableModel model = new DefaultTableModel(columnNames, 9);
table = new JTable(model)
{
public Class getColumnClass(int column)
{
if(column == 0)
return ImageIcon.class;
else
return String.class;
}
};
tableSetup();
setVisible(true);
}
public void tableSetup()
{
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
table.setDefaultRenderer(String.class, dtcr);
ImageIcon p = new ImageIcon("Icons/Powerball.png"); //Not important to my problem
ImageIcon w1p = new ImageIcon("Icons/WhiteplusPowerball.png");
ImageIcon w2P = new ImageIcon("Icons/2WhitePlusPowerball.png");
ImageIcon w3P = new ImageIcon("Icons/3WhitePlusPowerball.png");
ImageIcon w4P = new ImageIcon("Icons/4WhitePlusPowerball.png");
ImageIcon w5P = new ImageIcon("Icons/5WhitePlusPowerball.png");
ImageIcon w3 = new ImageIcon("Icons/3White.png");
ImageIcon w4 = new ImageIcon("Icons/4White.png");
ImageIcon w5 = new ImageIcon("Icons/5White.png");
table.setValueAt(p, 0, 0);
table.setValueAt(w1p, 1, 0);
table.setValueAt(w2P, 2, 0);
table.setValueAt(w3, 3, 0);
table.setValueAt(w3P, 4, 0);
table.setValueAt(w4, 5, 0);
table.setValueAt(w4P, 6, 0);
table.setValueAt(w5, 7, 0);
table.setValueAt(w5P, 8, 0);
table.setValueAt("1 in 55", 0, 1);
table.setValueAt("1 in 111", 1, 1);
table.setValueAt("1 in 706", 2, 1);
table.setValueAt("1 in 360", 3, 1);
table.setValueAt("1 in 12,245", 4, 1);
table.setValueAt("1 in 19,088", 5, 1);
table.setValueAt("1 in 648,976", 6,1);
table.setValueAt("1 in 5,153,633", 7, 1);
table.setValueAt("1 in 175,223,510", 8, 1);
for(int i = 0; i < 10; i++)
{
table.setRowHeight(i, table.getRowHeight(i) + 10);
}
for(int i = 0; i < columnNames.length; i++)
{
TableColumn column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(column.getPreferredWidth() + 80);
}
}
Here is the main class with the JPanel that is attempting to display my LotteryTable.
public class LotteryDisplay
{
private JFrame display;
private JPanel panel;
private LotteryTable table;
private static JCheckBox powerPlay;
public LotteryDisplay()
{
display = new JFrame("Powerball");
panel = new JPanel();
table = new LotteryTable();
powerPlay = new JCheckBox("Power Play");
panel.setPreferredSize(new Dimension(800, 300));
panel.add(powerPlay);
//JTableHeader header = table.getTableHeader(); //Not important to problem
//panel.add(header);
panel.add(table);
display.getContentPane().add(panel, BorderLayout.CENTER);
display.pack();
display.setVisible(true);
}
LotteryTable extends JTable, but then creates another JTable internally to itself which is never added to the any component capable of displaying it.
As to your second question...this arguable. I see no particular benefit in extending a JTable for the functionality you are adding. This could just as easily be achieved using a static configuration method which is passed a JTable
Working Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class LotteryTable {
public static void main(String[] args) {
new LotteryTable();
}
public LotteryTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTable table = new JTable();
configureLotteryTable(table);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static final String[] COLUMN_NAMES = {"Powerball Combos", "Odds of Winning", "Payout", "Number of Wins", "Win Frequency"};
public static void configureLotteryTable(JTable table) {
DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0) {
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = ImageIcon.class;
break;
default:
clazz = String.class;
break;
}
return clazz;
}
};
table.setModel(model);
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 55"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 111"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 706"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 360"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 12,245"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 19,088"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 648,976"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 5,153,633"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 175,223,510"});
}
}
I would spend some more time reading through How to use Tables to freshen up on some of the concepts ;)
Whatever you're trying to do with the inner
JTable, you should be doing on the parent LotteryTable.
For illustration purposes, I replaced the reference to table with this:
public class LotteryTable extends JTable {
private static final String[] COLUMN_NAMES = {
"Powerball Combos",
"Odds of Winning",
"Payout",
"Number of Wins",
"Win Frequency" };
public LotteryTable() {
super(new DefaultTableModel(COLUMN_NAMES, 9));
tableSetup();
setVisible(true);
}
#Override
public Class<?> getColumnClass(int column) {
if (column == 0)
return ImageIcon.class;
else
return String.class;
}
private void tableSetup() {
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
this.setDefaultRenderer(String.class, dtcr);
ImageIcon p = new ImageIcon("Icons/Powerball.png");
ImageIcon w1p = new ImageIcon("Icons/WhiteplusPowerball.png");
ImageIcon w2P = new ImageIcon("Icons/2WhitePlusPowerball.png");
ImageIcon w3P = new ImageIcon("Icons/3WhitePlusPowerball.png");
ImageIcon w4P = new ImageIcon("Icons/4WhitePlusPowerball.png");
ImageIcon w5P = new ImageIcon("Icons/5WhitePlusPowerball.png");
ImageIcon w3 = new ImageIcon("Icons/3White.png");
ImageIcon w4 = new ImageIcon("Icons/4White.png");
ImageIcon w5 = new ImageIcon("Icons/5White.png");
this.setValueAt(p, 0, 0);
this.setValueAt(w1p, 1, 0);
this.setValueAt(w2P, 2, 0);
this.setValueAt(w3, 3, 0);
this.setValueAt(w3P, 4, 0);
this.setValueAt(w4, 5, 0);
this.setValueAt(w4P, 6, 0);
this.setValueAt(w5, 7, 0);
this.setValueAt(w5P, 8, 0);
this.setValueAt("1 in 55", 0, 1);
this.setValueAt("1 in 111", 1, 1);
this.setValueAt("1 in 706", 2, 1);
this.setValueAt("1 in 360", 3, 1);
this.setValueAt("1 in 12,245", 4, 1);
this.setValueAt("1 in 19,088", 5, 1);
this.setValueAt("1 in 648,976", 6, 1);
this.setValueAt("1 in 5,153,633", 7, 1);
this.setValueAt("1 in 175,223,510", 8, 1);
for (int i = 0; i < 10; i++) {
this.setRowHeight(i, this.getRowHeight(i) + 10);
}
for (int i = 0; i < COLUMN_NAMES.length; i++) {
TableColumn column = this.getColumnModel().getColumn(i);
column.setPreferredWidth(column.getPreferredWidth() + 80);
}
}
}
I'd rather use a JFrame or JDialogand place a JPanel to display your JTable.