Java AbstractTableModel: getValueAt does not use updated data - java
I have a Java application with four card panels. In the first panel, I receive data for the first geographic point, in the second and third -- for the other two points, and in the fourth panel, I have a JTable that displays extracted information about these three points.
The following code can be used to compile the application. On each Card panel, try to click the button next to the JTextfield to add the data.
Package models
Class AppSingleton
public class AppSingleton
{
private static AppSingleton instance = null;
public List<List<String>> flightPlanShared = new ArrayList<List<String>>(){{
add(Arrays.asList(""));
add(Arrays.asList(""));
add(Arrays.asList(""));
}};
private AppSingleton()
{
}
public static AppSingleton getInstance()
{
if(instance == null)
{
instance = new AppSingleton();
}
return instance;
}
}
Class Model_Flightplan
import java.util.ArrayList;
import java.util.List;
import presenters.Presenter;
import views.View_MainFrame;
public class Model_Flightplan
{
AppSingleton appSingleton = AppSingleton.getInstance( );
private Presenter presenter;
private View_MainFrame viewMainFrame;
public Model_Flightplan(View_MainFrame viewMainFrame)
{
this.viewMainFrame = viewMainFrame;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public void addDepartureAirport()
{
List<String> component = new ArrayList<>();
component.add("KLAS");
component.add("KLAS");
component.add("KLAS");
appSingleton.flightPlanShared.set(0, component);
}
public void addDestinationAirport()
{
List<String> component = new ArrayList<>();
component.add("KLAX");
component.add("KLAX");
component.add("KLAX");
appSingleton.flightPlanShared.set( (appSingleton.flightPlanShared.size() - 2), component);
}
public void addAlternateAirport()
{
List<String> component = new ArrayList<>();
component.add("KSEA");
component.add("KSEA");
component.add("KSEA");
appSingleton.flightPlanShared.set( (appSingleton.flightPlanShared.size() - 1), component);
}
}
Class Model_TableWindsAloft
package models;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class Model_TableWindsAloft extends AbstractTableModel
{
String[] columnNames = {"ICAO","Name","Type"};
private List<List<String>> tableData = new ArrayList<>();
public Model_TableWindsAloft(List<List<String>> tableData)
{
this.tableData = tableData;
System.out.println("CONSTRUCTOR? "+tableData);
}
#Override
public int getRowCount()
{
System.out.println("DATA COUNT? "+tableData.size());
return(tableData.size());
}
#Override
public int getColumnCount() {
return(columnNames.length);
}
#Override
public String getColumnName(int column)
{
return columnNames[column] ;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
System.out.println("WHAT IS DATA 1? "+tableData);
List<String> data = tableData.get(rowIndex);
System.out.println("WHAT IS DATA 2? "+data);
if(data.size()>=3)
{
switch(columnIndex)
{
case 0:
return data.get(0);
case 1:
return data.get(1);
case 2:
return data.get(2);
default:
return null;
}
}
else
{
return null;
}
}
}
Package presenters
Class Presenter
package presenters;
import java.awt.CardLayout;
import models.Model_Flightplan;
import views.View_MainFrame;
public class Presenter
{
private final View_MainFrame viewMainFrame;
private final Model_Flightplan model;
public Presenter(View_MainFrame viewMainFrame, Model_Flightplan model)
{
this.viewMainFrame = viewMainFrame;
this.model = model;
}
public void displayTabDep()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDep");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDeparture.setEnabled(false);
}
public void displayTabDest()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDest");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDestination.setEnabled(false);
}
public void displayTabAlt()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardAlt");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlAlternate.setEnabled(false);
}
public void displayTabWindsAloft()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
public void addDeparture()
{
model.addDepartureAirport();
}
public void addDestination()
{
model.addDestinationAirport();
}
public void addAlternate()
{
model.addAlternateAirport();
}
}
Package views
Class View_MainFrame
package views;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import models.AppSingleton;
import presenters.Presenter;
public class View_MainFrame
{
AppSingleton appSingleton = AppSingleton.getInstance( );
private Presenter presenter;
private JPanel panelContext;
private JFrame frame;
public JPanel pnlDep;
public JPanel pnlDest;
public JPanel pnlAlt;
public JPanel pnlWindsAloft;
public JPanel panelButtons;
public JButton btnFlightplan;
public JPanel panelButtonsAdd;
public JButton btnFlightplanDummy;
public JPanel pnlDepAirport;
private JButton btnAddDep;
private javax.swing.JPanel pnlDestAirport;
public JButton btnAddDest;
private javax.swing.JPanel pnlAltAirport;
public JButton btnAddAlt;
private javax.swing.JPanel pnlWindsAloftInfo;
private javax.swing.JPanel pnlWindsAloftTable;
public JButton btnPnlDeparture;
public JButton btnPnlDestination;
public JButton btnPnlAlternate;
public JButton btnPnlWindsAloft;
public View_MainFrame()
{
createUI();
}
private void createUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("iGoDispatch IXEG Boeing-733");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new javax.swing.BoxLayout(frame.getContentPane(), javax.swing.BoxLayout.Y_AXIS));
Dimension frameSize = new Dimension(1050,700);
Dimension frameSizeMin = new Dimension(500,200);
frame.setPreferredSize(frameSize);
frame.setMinimumSize(frameSizeMin);
createPanelButtons();
createPanelButtonsAdd();
createPanelDeparture();
createPanelDestination();
createPanelAlternate();
pnlWindsAloft = new JPanel();
pnlWindsAloft.setLayout(new java.awt.BorderLayout());
createPanelWindsAloft();
setPanelContext(new JPanel());
getPanelContext().setLayout(new java.awt.CardLayout());
frame.getContentPane().add(getPanelContext(), java.awt.BorderLayout.SOUTH);
getPanelContext().add(pnlDep, "cardDep");
getPanelContext().add(pnlDest, "cardDest");
getPanelContext().add(pnlAlt, "cardAlt");
getPanelContext().add(pnlWindsAloft, "cardWindsAloft");
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public JPanel getPanelContext() {
return panelContext;
}
public void setPanelContext(JPanel panelContext) {
this.panelContext = panelContext;
}
private void createPanelButtons()
{
panelButtons = new JPanel();
panelButtons.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelButtons.setLayout(new java.awt.GridLayout(1, 0));
Dimension panelButtonsMinSize = new Dimension(1050,60);
panelButtons.setMinimumSize(panelButtonsMinSize);
btnFlightplan = new JButton();
btnFlightplan.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
btnFlightplan.setText("Flightplan");
btnFlightplan.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnFlightplan.setIconTextGap(5);
btnFlightplan.setMaximumSize(new java.awt.Dimension(70, 70));
btnFlightplan.setMinimumSize(new java.awt.Dimension(70, 70));
btnFlightplan.setPreferredSize(new java.awt.Dimension(70, 70));
btnFlightplan.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnFlightplan.addActionListener((java.awt.event.ActionEvent evt) ->
{
getPresenter().displayTabDep();
});
panelButtons.add(btnFlightplan);
frame.getContentPane().add(panelButtons, java.awt.BorderLayout.NORTH);
}
private void createPanelButtonsAdd()
{
panelButtonsAdd = new JPanel();
panelButtonsAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
frame.getContentPane().add(panelButtonsAdd, java.awt.BorderLayout.CENTER);
panelButtonsAdd.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
// Dummy button
btnFlightplanDummy = new JButton();
btnFlightplanDummy.setAlignmentY(0.0F);
btnFlightplanDummy.setEnabled(false);
btnFlightplanDummy.setVisible(false);
btnFlightplanDummy.setMaximumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setMinimumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setPreferredSize(new java.awt.Dimension(50, 50));
panelButtonsAdd.add(btnFlightplanDummy);
addButtonsFlightplan();
}
public void addButtonsFlightplan()
{
removeButtons();
Dimension buttonDim = new Dimension(50, 50);
Font buttonFont = new Font("Helvetica", Font.PLAIN, 10);
btnPnlDeparture = new JButton("DEP");
btnPnlDeparture.setPreferredSize(buttonDim);
btnPnlDeparture.setFont(buttonFont);
btnPnlDeparture.setVisible(true);
btnPnlDeparture.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabDep();
});
panelButtonsAdd.add(btnPnlDeparture);
btnPnlDestination = new JButton("ARR");
btnPnlDestination.setPreferredSize(buttonDim);
btnPnlDestination.setFont(buttonFont);
btnPnlDestination.setVisible(true);
btnPnlDestination.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabDest();
});
panelButtonsAdd.add(btnPnlDestination);
btnPnlAlternate = new JButton("ALT");
btnPnlAlternate.setPreferredSize(buttonDim);
btnPnlAlternate.setFont(buttonFont);
btnPnlAlternate.setVisible(true);
btnPnlAlternate.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabAlt();
});
panelButtonsAdd.add(btnPnlAlternate);
btnPnlWindsAloft = new JButton("WINDS");
btnPnlWindsAloft.setPreferredSize(buttonDim);
btnPnlWindsAloft.setFont(buttonFont);
btnPnlWindsAloft.setVisible(true);
btnPnlWindsAloft.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabWindsAloft();
});
panelButtonsAdd.add(btnPnlWindsAloft);
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void removeButtons()
{
panelButtonsAdd.removeAll();
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void createPanelDeparture()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlDep = new JPanel();
pnlDep.setLayout(new java.awt.BorderLayout());
pnlDepAirport = new JPanel();
pnlDepAirport.setLayout(new java.awt.GridBagLayout());
btnAddDep = new JButton();
btnAddDep.setText("ADD");
btnAddDep.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddDep.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddDep.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddDep.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addDeparture();
SwingUtilities.invokeLater(() ->
{
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDepAirport.add(btnAddDep, gridBagConstraints);
pnlDep.add(pnlDepAirport);
}
private void createPanelDestination()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlDest = new JPanel();
pnlDest.setLayout(new java.awt.BorderLayout());
pnlDestAirport = new javax.swing.JPanel();
pnlDestAirport.setLayout(new java.awt.GridBagLayout());
btnAddDest = new javax.swing.JButton();
btnAddDest.setText("jButton1");
btnAddDest.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddDest.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddDest.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddDest.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addDestination();
SwingUtilities.invokeLater(() ->
{
//displayValues();
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDestAirport.add(btnAddDest, gridBagConstraints);
pnlDest.add(pnlDestAirport);
}
private void createPanelAlternate()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlAlt = new JPanel();
pnlAlt.setLayout(new java.awt.BorderLayout());
pnlAltAirport = new JPanel();
pnlAltAirport.setLayout(new java.awt.GridBagLayout());
btnAddAlt = new JButton();
btnAddAlt.setText("ADD");
btnAddAlt.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddAlt.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddAlt.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddAlt.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addAlternate();
SwingUtilities.invokeLater(() ->
{
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlAltAirport.add(btnAddAlt, gridBagConstraints);
pnlAlt.add(pnlAltAirport);
}
public void createPanelWindsAloft()
{
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
public List<List<String>> createDataForWindsTable()
{
List<List<String>> finalResult = new ArrayList<>();
System.out.println("SIZE: "+finalResult.size());
for (int i=0; i<appSingleton.flightPlanShared.size(); i++)
{
String icao;
String name;
String type;
if(appSingleton.flightPlanShared.get(i).size()>2)
{
icao = appSingleton.flightPlanShared.get(i).get(2);
name = appSingleton.flightPlanShared.get(i).get(1);
type = appSingleton.flightPlanShared.get(i).get(0);
}
else
{
icao = "";
name = "";
type = "";
}
List<String> components = new ArrayList<>();
components.add(icao);
components.add(name);
components.add(type);
System.out.println("COMPONENTS: "+components);
finalResult.add(components);
}
/* THIS WORKS!
String a1 = "LAS VEGAS/MC CARRAN ";
String a2 = "KLAS";
String a3 = "PORTDEP";
List<String> a = new ArrayList<>();
a.add(a1);
a.add(a2);
a.add(a3);
String b1 = "LOS ANGELES INTL";
String b2 = "KLAX";
String b3 = "PORTDEST";
List<String> b = new ArrayList<>();
b.add(b1);
b.add(b2);
b.add(b3);
String c1 = "SEATTLE-TACOMA INTL";
String c2 = "KSEA";
String c3 = "PORTALT";
List<String> c = new ArrayList<>();
c.add(c1);
c.add(c2);
c.add(c3);
finalResult.add(a);
finalResult.add(b);
finalResult.add(c);
*/
System.out.println("DATA CREATED: "+finalResult);
return finalResult;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
}
Main
package testjtable;
import javax.swing.SwingUtilities;
import models.Model_Flightplan;
import presenters.Presenter;
import views.View_MainFrame;
public class TestJTable {
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
View_MainFrame viewMainFrame = new View_MainFrame();
viewMainFrame.setPresenter(new Presenter(viewMainFrame, new Model_Flightplan(viewMainFrame)));
});
}
}
Data does not appear inside the table unless (!!!) I click outside of the application.
EDIT:
I solved the problem by updating the model using the setValueAt() method:
#Override
public void setValueAt(Object value, int row, int col)
{
setTableData(appSingleton.flightPlanShared);
fireTableCellUpdated(row, col);
}
You appear to be creating a new JTable and a new JPanel that holds it, with each press of the create winds aloft button.
Here is your btnPnlWindsAloft JButton's ActionListener:
btnPnlWindsAloft.addActionListener((ActionEvent e) -> {
getPresenter().displayTabWindsAloft();
});
Notice that it calls getPresenter().displayTabWindsAloft(); which is:
public void displayTabWindsAloft() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
And notice that this method calls viewMainFrame.createPanelWindsAloft(); which is:
public void createPanelWindsAloft() {
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(
new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
... and every time this method is called, it creates a new pnlWindsAloftInfo JPanel, a new pnlWindsAloftTable JPanel, a new tblWindsAloft JTable which it fills with a new table model, via a call to createDataForWindsTable(). Again, why are you re-creating these components and models unnecessarily?
Don't do this -- create your key components just once, and then while the program is running, change the state of the JTable's model as well as the state of the visibility of the "card" JPanel that holds the JTable, but don't keep re-creating JTables and models, some of which hold data, and some that don't.
Also the complexity of your program is needlessly huge, and this is likely preventing you from seeing the problem -- refactor and simply everything.
Side issue: you are setting sizes of key components almost guaranteeing that they will not display appropriately on most systems (such as my system where the button text is displaying as ...). You'll want to avoid this as well.
My current MCVE of your code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class TestJTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
View_MainFrame viewMainFrame = new View_MainFrame();
viewMainFrame.setPresenter(
new Presenter(viewMainFrame, new Model_Flightplan(viewMainFrame)));
});
}
}
class View_MainFrame {
AppSingleton appSingleton = AppSingleton.getInstance();
private Presenter presenter;
private JPanel panelContext;
private JFrame frame;
public JPanel pnlDep;
public JPanel pnlDest;
public JPanel pnlAlt;
public JPanel pnlWindsAloft;
public JPanel panelButtons;
public JButton btnFlightplan;
public JPanel panelButtonsAdd;
public JButton btnFlightplanDummy;
public JPanel pnlDepAirport;
private JButton btnAddDep;
private javax.swing.JPanel pnlDestAirport;
public JButton btnAddDest;
private javax.swing.JPanel pnlAltAirport;
public JButton btnAddAlt;
private javax.swing.JPanel pnlWindsAloftInfo;
private javax.swing.JPanel pnlWindsAloftTable;
public JButton btnPnlDeparture;
public JButton btnPnlDestination;
public JButton btnPnlAlternate;
public JButton btnPnlWindsAloft;
public View_MainFrame() {
createUI();
}
private void createUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("iGoDispatch IXEG Boeing-733");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
new javax.swing.BoxLayout(frame.getContentPane(), javax.swing.BoxLayout.Y_AXIS));
Dimension frameSize = new Dimension(1050, 700);
Dimension frameSizeMin = new Dimension(500, 200);
frame.setPreferredSize(frameSize);
frame.setMinimumSize(frameSizeMin);
createPanelButtons();
createPanelButtonsAdd();
createPanelDeparture();
createPanelDestination();
createPanelAlternate();
pnlWindsAloft = new JPanel();
pnlWindsAloft.setLayout(new java.awt.BorderLayout());
createPanelWindsAloft();
setPanelContext(new JPanel());
getPanelContext().setLayout(new java.awt.CardLayout());
frame.getContentPane().add(getPanelContext(), java.awt.BorderLayout.SOUTH);
getPanelContext().add(pnlDep, "cardDep");
getPanelContext().add(pnlDest, "cardDest");
getPanelContext().add(pnlAlt, "cardAlt");
getPanelContext().add(pnlWindsAloft, "cardWindsAloft");
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public JPanel getPanelContext() {
return panelContext;
}
public void setPanelContext(JPanel panelContext) {
this.panelContext = panelContext;
}
private void createPanelButtons() {
panelButtons = new JPanel();
panelButtons.setBorder(
new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelButtons.setLayout(new java.awt.GridLayout(1, 0));
Dimension panelButtonsMinSize = new Dimension(1050, 60);
panelButtons.setMinimumSize(panelButtonsMinSize);
btnFlightplan = new JButton();
btnFlightplan.setFont(new java.awt.Font("Lucida Grande", 1, 13));
btnFlightplan.setText("Flightplan");
btnFlightplan.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnFlightplan.setIconTextGap(5);
btnFlightplan.setMaximumSize(new java.awt.Dimension(90, 70));
btnFlightplan.setMinimumSize(new java.awt.Dimension(90, 70));
btnFlightplan.setPreferredSize(new java.awt.Dimension(90, 70));
btnFlightplan.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnFlightplan.addActionListener((java.awt.event.ActionEvent evt) -> {
getPresenter().displayTabDep();
});
panelButtons.add(btnFlightplan);
frame.getContentPane().add(panelButtons, java.awt.BorderLayout.NORTH);
}
private void createPanelButtonsAdd() {
panelButtonsAdd = new JPanel();
panelButtonsAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
frame.getContentPane().add(panelButtonsAdd, java.awt.BorderLayout.CENTER);
panelButtonsAdd.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
btnFlightplanDummy = new JButton();
btnFlightplanDummy.setAlignmentY(0.0F);
btnFlightplanDummy.setEnabled(false);
btnFlightplanDummy.setVisible(false);
btnFlightplanDummy.setMaximumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setMinimumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setPreferredSize(new java.awt.Dimension(50, 50));
panelButtonsAdd.add(btnFlightplanDummy);
addButtonsFlightplan();
}
public void addButtonsFlightplan() {
removeButtons();
Dimension buttonDim = new Dimension(150, 50);
Font buttonFont = new Font("Helvetica", Font.PLAIN, 10);
btnPnlDeparture = new JButton("DEP");
btnPnlDeparture.setPreferredSize(buttonDim);
btnPnlDeparture.setFont(buttonFont);
btnPnlDeparture.setVisible(true);
btnPnlDeparture.addActionListener((ActionEvent e) -> {
getPresenter().displayTabDep();
});
panelButtonsAdd.add(btnPnlDeparture);
btnPnlDestination = new JButton("ARR");
btnPnlDestination.setPreferredSize(buttonDim);
btnPnlDestination.setFont(buttonFont);
btnPnlDestination.setVisible(true);
btnPnlDestination.addActionListener((ActionEvent e) -> {
getPresenter().displayTabDest();
});
panelButtonsAdd.add(btnPnlDestination);
btnPnlAlternate = new JButton("ALT");
btnPnlAlternate.setPreferredSize(buttonDim);
btnPnlAlternate.setFont(buttonFont);
btnPnlAlternate.setVisible(true);
btnPnlAlternate.addActionListener((ActionEvent e) -> {
getPresenter().displayTabAlt();
});
panelButtonsAdd.add(btnPnlAlternate);
btnPnlWindsAloft = new JButton("WINDS");
btnPnlWindsAloft.setPreferredSize(buttonDim);
btnPnlWindsAloft.setFont(buttonFont);
btnPnlWindsAloft.setVisible(true);
btnPnlWindsAloft.addActionListener((ActionEvent e) -> {
getPresenter().displayTabWindsAloft();
});
panelButtonsAdd.add(btnPnlWindsAloft);
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void removeButtons() {
panelButtonsAdd.removeAll();
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void createPanelDeparture() {
java.awt.GridBagConstraints gridBagConstraints;
pnlDep = new JPanel();
pnlDep.setLayout(new java.awt.BorderLayout());
pnlDepAirport = new JPanel();
pnlDepAirport.setLayout(new java.awt.GridBagLayout());
btnAddDep = new JButton();
btnAddDep.setText("ADD");
btnAddDep.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddDep.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddDep.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddDep.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addDeparture();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDepAirport.add(btnAddDep, gridBagConstraints);
pnlDep.add(pnlDepAirport);
}
private void createPanelDestination() {
java.awt.GridBagConstraints gridBagConstraints;
pnlDest = new JPanel();
pnlDest.setLayout(new java.awt.BorderLayout());
pnlDestAirport = new javax.swing.JPanel();
pnlDestAirport.setLayout(new java.awt.GridBagLayout());
btnAddDest = new javax.swing.JButton();
btnAddDest.setText("jButton1");
btnAddDest.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddDest.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddDest.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddDest.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addDestination();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDestAirport.add(btnAddDest, gridBagConstraints);
pnlDest.add(pnlDestAirport);
}
private void createPanelAlternate() {
java.awt.GridBagConstraints gridBagConstraints;
pnlAlt = new JPanel();
pnlAlt.setLayout(new java.awt.BorderLayout());
pnlAltAirport = new JPanel();
pnlAltAirport.setLayout(new java.awt.GridBagLayout());
btnAddAlt = new JButton();
btnAddAlt.setText("ADD");
btnAddAlt.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddAlt.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddAlt.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddAlt.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addAlternate();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlAltAirport.add(btnAddAlt, gridBagConstraints);
pnlAlt.add(pnlAltAirport);
}
public void createPanelWindsAloft() {
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(
new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
public List<List<String>> createDataForWindsTable() {
List<List<String>> finalResult = new ArrayList<>();
System.out.println("SIZE: " + finalResult.size());
for (int i = 0; i < appSingleton.flightPlanShared.size(); i++) {
String icao;
String name;
String type;
if (appSingleton.flightPlanShared.get(i).size() > 2) {
icao = appSingleton.flightPlanShared.get(i).get(2);
name = appSingleton.flightPlanShared.get(i).get(1);
type = appSingleton.flightPlanShared.get(i).get(0);
} else {
icao = "";
name = "";
type = "";
}
List<String> components = new ArrayList<>();
components.add(icao);
components.add(name);
components.add(type);
System.out.println("COMPONENTS: " + components);
finalResult.add(components);
}
/*
* THIS WORKS! String a1 = "LAS VEGAS/MC CARRAN "; String a2 = "KLAS";
* String a3 = "PORTDEP";
*
* List<String> a = new ArrayList<>(); a.add(a1); a.add(a2); a.add(a3);
*
* String b1 = "LOS ANGELES INTL"; String b2 = "KLAX"; String b3 =
* "PORTDEST"; List<String> b = new ArrayList<>(); b.add(b1); b.add(b2);
* b.add(b3);
*
* String c1 = "SEATTLE-TACOMA INTL"; String c2 = "KSEA"; String c3 =
* "PORTALT"; List<String> c = new ArrayList<>(); c.add(c1); c.add(c2);
* c.add(c3);
*
* finalResult.add(a); finalResult.add(b); finalResult.add(c);
*/
System.out.println("DATA CREATED: " + finalResult);
return finalResult;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
}
class Presenter {
private final View_MainFrame viewMainFrame;
private final Model_Flightplan model;
public Presenter(View_MainFrame viewMainFrame, Model_Flightplan model) {
this.viewMainFrame = viewMainFrame;
this.model = model;
}
public void displayTabDep() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDep");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDeparture.setEnabled(false);
}
public void displayTabDest() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDest");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDestination.setEnabled(false);
}
public void displayTabAlt() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardAlt");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlAlternate.setEnabled(false);
}
public void displayTabWindsAloft() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
public void addDeparture() {
model.addDepartureAirport();
}
public void addDestination() {
model.addDestinationAirport();
}
public void addAlternate() {
model.addAlternateAirport();
}
}
class Model_TableWindsAloft extends AbstractTableModel {
String[] columnNames = { "ICAO", "Name", "Type" };
private List<List<String>> tableData = new ArrayList<>();
public Model_TableWindsAloft(List<List<String>> tableData) {
this.tableData = tableData;
System.out.println("CONSTRUCTOR? " + tableData);
}
#Override
public int getRowCount() {
System.out.println("DATA COUNT? " + tableData.size());
return (tableData.size());
}
#Override
public int getColumnCount() {
return (columnNames.length);
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
System.out.println("WHAT IS DATA 1? " + tableData);
List<String> data = tableData.get(rowIndex);
System.out.println("WHAT IS DATA 2? " + data);
if (data.size() >= 3) {
switch (columnIndex) {
case 0:
return data.get(0);
case 1:
return data.get(1);
case 2:
return data.get(2);
default:
return null;
}
} else {
return null;
}
}
}
class Model_Flightplan {
AppSingleton appSingleton = AppSingleton.getInstance();
private Presenter presenter;
private View_MainFrame viewMainFrame;
public Model_Flightplan(View_MainFrame viewMainFrame) {
this.viewMainFrame = viewMainFrame;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public void addDepartureAirport() {
List<String> component = new ArrayList<>();
component.add("KLAS");
component.add("KLAS");
component.add("KLAS");
appSingleton.flightPlanShared.set(0, component);
}
public void addDestinationAirport() {
List<String> component = new ArrayList<>();
component.add("KLAX");
component.add("KLAX");
component.add("KLAX");
appSingleton.flightPlanShared.set((appSingleton.flightPlanShared.size() - 2), component);
}
public void addAlternateAirport() {
List<String> component = new ArrayList<>();
component.add("KSEA");
component.add("KSEA");
component.add("KSEA");
appSingleton.flightPlanShared.set((appSingleton.flightPlanShared.size() - 1), component);
}
}
class AppSingleton {
private static AppSingleton instance = null;
public List<List<String>> flightPlanShared = new ArrayList<List<String>>() {
{
add(Arrays.asList(""));
add(Arrays.asList(""));
add(Arrays.asList(""));
}
};
private AppSingleton() {
}
public static AppSingleton getInstance() {
if (instance == null) {
instance = new AppSingleton();
}
return instance;
}
}
Related
How do I get a variable collected from a JTextField and give it to a getter method?
Very new to using Java and spent hours looking for a solution, but I cannot find out how to get the input collected by a JTextField with a button and ActionListener then be used for a getter method that can receive idNum so I can use the input in another class. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Staff extends JFrame implements ActionListener { private staffBooking staffBooking = new staffBooking(); String weekArray[] = { "Week1", "Week2" }; String dayArray[] = { "Monday" , "Tuesday", "Wednesday", "Thursday", "Friday" }; JPanel panel = new JPanel(); JLabel weekLabel = new JLabel("Week: ", SwingConstants.RIGHT); JLabel dayLabel = new JLabel("Day: ", SwingConstants.RIGHT); JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT); static JTextField id = new JTextField("",2); JComboBox weekDrop = new JComboBox(weekArray); JComboBox dayDrop = new JComboBox(dayArray); JButton button = new JButton("Submit"); private static int idNum; public Staff() { setTitle("Staff"); setSize(250,250); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); setLayout(new GridLayout(4, 2)); add(weekLabel); add(weekDrop); add(dayLabel); add(dayDrop); add(idLabel); add(id); add(panel); add(button); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(id.getText().equals("")==false) { if (e.getSource() == button) { staffBooking.setEnabled(true); staffBooking.setVisible(true); idNum = Integer.parseInt(id.getText()); } } } }); } public static int getID() { return idNum; } }
I believe what you are trying to do is something like this: import javax.swing.*; import javax.swing.SwingConstants; public class Staff extends JFrame /*implements ActionListener*/ { private final JPanel panel = new JPanel(); private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT); private final JTextField id = new JTextField("",5); private final JButton button = new JButton("Submit"); private int idNum; public Staff() { StaffBooking staffBooking = new StaffBooking(this); setTitle("Staff"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); panel.add(idLabel); panel.add(id); panel.add(button); add(panel); button.addActionListener(e -> { if(! id.getText().isEmpty()) { idNum = Integer.parseInt(id.getText()); staffBooking.setVisible(true); } }); pack(); setVisible(true); } public int getID() { return idNum; } public static void main(String[] args) { new Staff(); } } class StaffBooking extends JDialog { public StaffBooking(Staff staff) { JPanel panel = new JPanel(); JLabel idLabel = new JLabel(" "); JButton button = new JButton("Show ID"); button.addActionListener(e -> { idLabel.setText(String.valueOf(staff.getID())); }); panel.add(button); panel.add(idLabel); add(panel); setLocationRelativeTo(null); pack(); } } Using a setter in StaffBooking would be better in this case: public class Staff extends JFrame /*implements ActionListener*/ { private final JPanel panel = new JPanel(); private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT); private final JTextField id = new JTextField("",5); private final JButton button = new JButton("Submit"); public Staff() { StaffBooking staffBooking = new StaffBooking(); setTitle("Staff"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); panel.add(idLabel); panel.add(id); panel.add(button); add(panel); button.addActionListener(e -> { if(! id.getText().isEmpty()) { int idNum = Integer.parseInt(id.getText()); staffBooking.setID(idNum); staffBooking.setVisible(true); } }); pack(); setVisible(true); } public static void main(String[] args) { new Staff(); } } class StaffBooking extends JDialog { private int idNum; public StaffBooking() { JPanel panel = new JPanel(); JLabel idLabel = new JLabel(" "); JButton button = new JButton("Show ID"); button.addActionListener(e -> { idLabel.setText(String.valueOf(idNum)); }); panel.add(button); panel.add(idLabel); add(panel); setLocationRelativeTo(null); pack(); } public void setID(int idNum) { this.idNum = idNum; } } A further improvement oof the structure can be achieved by using a model class, shared between Staff and StaffBooking: public class Staff extends JFrame /*implements ActionListener*/ { private final JPanel panel = new JPanel(); private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT); private final JTextField id = new JTextField("",5); private final JButton button = new JButton("Submit"); public Staff() { Model model = new Model(); StaffBooking staffBooking = new StaffBooking(model); setTitle("Staff"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); panel.add(idLabel); panel.add(id); panel.add(button); add(panel); button.addActionListener(e -> { if(! id.getText().isEmpty()) { int idNum = Integer.parseInt(id.getText()); model.setID(idNum); staffBooking.setVisible(true); } }); pack(); setVisible(true); } public static void main(String[] args) { new Staff(); } } class StaffBooking extends JDialog { public StaffBooking(Model model) { JPanel panel = new JPanel(); JLabel idLabel = new JLabel(" "); JButton button = new JButton("Show ID"); button.addActionListener(e -> { idLabel.setText(String.valueOf(model.getID())); }); panel.add(button); panel.add(idLabel); add(panel); setLocationRelativeTo(null); pack(); } } class Model{ private int idNum; public int getID() { return idNum; } public void setID(int idNum) { this.idNum = idNum; } }
In JTabbedPane, I have two panels where same textfield and label are not displayed when written
I wanted to display same textfield and label in both the panels that are added to JTabbedPane but one of panel is displaying the textfield and label and the other is not, when added the same textfield and label for both the panels.
You can only display a component in one container. Better to have your JPanels share the same model, which for the JTextField is its Document, and for the JLabel -- well its text (not really a model that you can extract, so you'll have to change both yourself). A bit overconvoluted example: import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.EventListenerList; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; #SuppressWarnings("serial") public class SharedModels extends JPanel { private static final int TABS = 10; private JTabbedPane tabbedPane = new JTabbedPane(); private JTextField labelText = new JTextField(10); private MyModel myModel = new MyModel(); public SharedModels() { for (int i = 0; i < TABS; i++) { MyPanel myPanel = new MyPanel(myModel); String text = "tab: " + (i + 1); tabbedPane.addTab(text, myPanel); } JPanel topPanel = new JPanel(); topPanel.add(new JLabel("Text for JLabel:")); topPanel.add(labelText); labelText.getDocument().addDocumentListener(new DocumentListener() { #Override public void removeUpdate(DocumentEvent e) { setLabelText(e); } #Override public void insertUpdate(DocumentEvent e) { setLabelText(e); } #Override public void changedUpdate(DocumentEvent e) { setLabelText(e); } private void setLabelText(DocumentEvent e) { Document doc = e.getDocument(); int length = doc.getLength(); try { String text = doc.getText(0, length); myModel.setLabelText(text); } catch (BadLocationException e1) { e1.printStackTrace(); } } }); setLayout(new BorderLayout()); add(topPanel, BorderLayout.PAGE_START); add(tabbedPane, BorderLayout.CENTER); add(new MyPanel(myModel), BorderLayout.PAGE_END); } private static void createAndShowGui() { SharedModels mainPanel = new SharedModels(); JFrame frame = new JFrame("SharedModels"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> createAndShowGui()); } } class MyModel { private Document document = new PlainDocument(); private String labelText = ""; private EventListenerList eventListenerList = new EventListenerList(); private ChangeEvent changeEvent = null; public void addChangeListener(ChangeListener l) { eventListenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { eventListenerList.remove(ChangeListener.class, l); } public String getLabelText() { return labelText; } public void setLabelText(String labelText) { this.labelText = labelText; fireChangeListeners(); } protected void fireChangeListeners() { Object[] listeners = eventListenerList.getListenerList(); for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) { changeEvent = new ChangeEvent(this); } ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } public Document getDocument() { return document; } } #SuppressWarnings("serial") class MyPanel extends JPanel { private JLabel label = new JLabel(""); private JTextField textField = new JTextField(10); public MyPanel(MyModel myModel) { textField.setDocument(myModel.getDocument()); myModel.addChangeListener(ce -> { label.setText(myModel.getLabelText()); }); add(new JLabel("Label text:")); add(label); add(textField); setPreferredSize(new Dimension(400, 100)); } }
Why is the KeyListener not working?
I'm new to java and wondering what's wrong with my code. To test the keylistener, I pressed N, but nothing happened. I then rearranged some methods but that didn't work either. My code is below, any input is welcome :) import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Calculator extends MyFrame implements KeyListener { private static final long serialVersionUID = 1L; //declare variable protected JPanel northPanel; protected JPanel plusPanel, minusPanel, multiplyPanel, dividePanel,modPanel, equalPanel; protected JPanel rowPanel1, rowPanel2, rowPanel3, rowPanel4, southPanel; protected JPanel[] numPanel = new JPanel[10]; protected JTextField textField; protected JButton plusButton, minusButton, multiplyButton; protected JButton divideButton, modButton, equalButton; protected JButton[] numButton = new JButton[10]; public void setTextField() { textField = new JTextField("0.0"); textField.setBackground(Color.GRAY); textField.setHorizontalAlignment(SwingConstants.RIGHT); textField.setEditable(false); } public void setButton() { for (int i = 0; i <= 9; i++) { numButton[i] = new JButton(i + ""); } plusButton = new JButton("+"); minusButton = new JButton("-"); multiplyButton = new JButton("*"); divideButton = new JButton("/"); modButton = new JButton("%"); equalButton = new JButton("="); } public void setSqualJpanel() { for (int i = 0; i <= 9; i++) { numPanel[i] = createSquareJpanel(Color.pink, 30, numButton[i]); } plusPanel = createSquareJpanel(Color.green, 30, plusButton); minusPanel = createSquareJpanel(Color.green, 30, minusButton); multiplyPanel = createSquareJpanel(Color.green, 30, multiplyButton); dividePanel = createSquareJpanel(Color.green, 30, divideButton); modPanel = createSquareJpanel(Color.green, 30, modButton); equalPanel = createSquareJpanel(Color.blue, 30, equalButton); } public void addComponents() { rowPanel1 = new JPanel(); rowPanel2 = new JPanel(); rowPanel3 = new JPanel(); rowPanel4 = new JPanel(); southPanel = new JPanel (new BorderLayout()); northPanel = new JPanel(new BorderLayout()); northPanel.add(textField); rowPanel1.add(numPanel[0]); rowPanel1.add(numPanel[1]); rowPanel1.add(numPanel[2]); rowPanel1.add(numPanel[3]); rowPanel2.add(numPanel[4]); rowPanel2.add(numPanel[5]); rowPanel2.add(numPanel[6]); rowPanel2.add(numPanel[7]); rowPanel3.add(numPanel[8]); rowPanel3.add(numPanel[9]); rowPanel3.add(plusPanel); rowPanel3.add(minusPanel); rowPanel4.add(multiplyPanel); rowPanel4.add(dividePanel); rowPanel4.add(modPanel); rowPanel4.add(equalPanel); southPanel.add(rowPanel2, BorderLayout.NORTH); southPanel.add(rowPanel3, BorderLayout.CENTER); southPanel.add(rowPanel4, BorderLayout.SOUTH); add(northPanel, BorderLayout.NORTH); add(rowPanel1, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); } public void setFrameFeatures (String title) { setTitle(title); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = getSize().width; int h = getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; setLocation(x, y); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void createAndShowGUI() { Calculator frame = new Calculator(); frame.setFrameFeatures("Simple Calculator"); frame.setTextField(); frame.setButton(); frame.setSqualJpanel(); frame.addComponents(); frame.pack(); frame.addListener(); } private void addListener() { addKeyListener(this); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } #Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_N){ JOptionPane.showMessageDialog(null,"You Pressed N"); } } #Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } #Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }
I usually add my key listeners to jpanels not frames.
how to put value in the checkboxes
this is my code, I just want to make a receipt that when you check the checkbox theres value in it and it prints the label with the value consecutively import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; public class GUI extends JFrame implements ActionListener { private JLabel label; private JCheckBox checkbox,checkbox2,checkbox3,checkbox4,checkbox5, checkbox6,checkbox7,checkbox8,checkbox9, checkbox10,checkbox11,checkbox12,checkbox13,checkbox14,checkbox15, checkbox16,checkbox17,checkbox18,checkbox19,checkbox20; private JButton button; public GUI() { Container pane= getContentPane(); pane.setLayout(new GridLayout(15,1)); JPanel jp= new JPanel(); label= new JLabel("McDonald's"); checkbox = new JCheckBox("Cheese Burger"); checkbox2 = new JCheckBox("Big Mac"); checkbox3 = new JCheckBox("Big n' Tasty"); checkbox4 = new JCheckBox("McSpicy"); checkbox5 = new JCheckBox("Quarter Pounder with Cheese"); checkbox6 = new JCheckBox("Double Cheeseburger"); checkbox7 = new JCheckBox("McChicken Sandwich"); checkbox8 = new JCheckBox("Filet-O-Fish"); checkbox9 = new JCheckBox("Cheeseburger Deluxe"); checkbox10 = new JCheckBox("Burger Mcdo"); checkbox11 = new JCheckBox("Chicken Filet with Drinks"); checkbox12 = new JCheckBox("Spaghetti with Drinks"); checkbox13 = new JCheckBox("Hot Fudge Sundae "); checkbox14 = new JCheckBox("Caramel Sundae"); checkbox15 = new JCheckBox("Large Mcdo French Fries"); checkbox16 = new JCheckBox("Chicken Nuggets with coke"); checkbox17 = new JCheckBox("Coke Float"); checkbox18 = new JCheckBox("Green Apple Float"); checkbox19 = new JCheckBox("Crispy Chicken with rice"); checkbox20 = new JCheckBox("Oreo Sundae"); button = new JButton("Order Now"); add(label); pane.add(checkbox); pane.add(checkbox2); pane.add(checkbox3); pane.add(checkbox4); pane.add(checkbox5); pane.add(checkbox6); pane.add(checkbox7); pane.add(checkbox8); pane.add(checkbox9); pane.add(checkbox10); pane.add(checkbox11); pane.add(checkbox12); pane.add(checkbox13); pane.add(checkbox14); pane.add(checkbox15); pane.add(checkbox16); pane.add(checkbox17); pane.add(checkbox18); pane.add(checkbox19); pane.add(checkbox20); add(button); add(jp, BorderLayout.SOUTH); label.setHorizontalAlignment(JLabel.CENTER); button.setSize(10,10); button.addActionListener(this); setSize(500,550); setVisible(true); } public void actionPerformed(ActionEvent e) { String gulp = e.getActionCommand(); { if ( gulp.equals("Order Now")) { new Receipt(); setVisible(true); dispose(); } } } public static void main(String[] args) { GUI r= new GUI(); } } here is my second code, this is the format of the receipt I want to achieve import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Receipt extends JFrame { private JLabel label,label2,label3,label4,label5, label6,label7,label8,label9,label10;; public Receipt() { Container pane= getContentPane(); pane.setLayout(new GridLayout(13,1)); label= new JLabel("MC DONALD'S"); label2= new JLabel("McDonald's Tandang Sora"); label3= new JLabel("#22 Tandang Sora Corner, Commonwealth Avenue, Quezon City"); label4= new JLabel("Telephone# (02)86236"); label5= new JLabel("MACHINE SERIAL NUMBER: D123HJ01"); label6= new JLabel("Card Issuer: Sharina Tortoles"); label7= new JLabel("Account Number# 337163990"); label8= new JLabel("February 22, 2014 12:45"); label9= new JLabel("Thank You for choosing Mcdonald's"); label10= new JLabel("Please come again"); label.setHorizontalAlignment(JLabel.CENTER); label2.setHorizontalAlignment(JLabel.CENTER); label3.setHorizontalAlignment(JLabel.CENTER); label4.setHorizontalAlignment(JLabel.CENTER); label5.setHorizontalAlignment(JLabel.CENTER); label6.setHorizontalAlignment(JLabel.CENTER); label7.setHorizontalAlignment(JLabel.CENTER); label8.setHorizontalAlignment(JLabel.CENTER); label9.setHorizontalAlignment(JLabel.CENTER); label10.setHorizontalAlignment(JLabel.CENTER); pane.add(label, BorderLayout.NORTH); pane.add(label2); pane.add(label3); pane.add(label4); pane.add(label5); pane.add(label6); pane.add(label7); pane.add(label8); pane.add(label9); pane.add(label10); setSize(500,500); setVisible(true); } public static void main(String[] args) { Receipt g= new Receipt(); } } Hope that it is clear to you what I want to happen with code
I guess EnumSet is what you are looking for: import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; enum Receipt { CheeseBurger("Cheese Burger"), BigMac("Big Mac"), BigNTasty("Big n' Tasty"), McSpicy("McSpicy"), QuarterPounderWithCheese("Quarter Pounder with Cheese"), DoubleCheeseburger("Double Cheeseburger"), McChickenSandwich("McChicken Sandwich"); //JCheckBox("Filet-O-Fish"), //JCheckBox("Cheeseburger Deluxe"), //JCheckBox("Burger Mcdo"), //JCheckBox("Chicken Filet with Drinks"), //JCheckBox("Spaghetti with Drinks"), //JCheckBox("Hot Fudge Sundae "), //JCheckBox("Caramel Sundae"), //JCheckBox("Large Mcdo French Fries"), //JCheckBox("Chicken Nuggets with coke"), //JCheckBox("Coke Float"), //JCheckBox("Green Apple Float"), //JCheckBox("Crispy Chicken with rice"), //JCheckBox("Oreo Sundae"); private final String str; private Receipt(String str) { this.str = str; } #Override public String toString() { return str; } } public class GUI2 { private JButton button = new JButton(new AbstractAction("Order Now") { #Override public void actionPerformed(ActionEvent e) { EnumSet<Receipt> r = EnumSet.noneOf(Receipt.class); for (ReceiptCheckBox c: list) { if (c.isSelected()) { r.add(c.getReceipt()); } } JOptionPane.showMessageDialog((JComponent) e.getSource(), r); } }); private List<ReceiptCheckBox> list = new ArrayList<>(Receipt.values().length); public JComponent makeUI() { JPanel p = new JPanel(); for (Receipt r: Receipt.values()) { ReceiptCheckBox c = new ReceiptCheckBox(r); list.add(c); p.add(c); } JPanel panel = new JPanel(new BorderLayout()); panel.add(new JLabel("McDonald's"), BorderLayout.NORTH); panel.add(button, BorderLayout.SOUTH); panel.add(p); return panel; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { #Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.getContentPane().add(new GUI2().makeUI()); f.setSize(320, 240); f.setLocationRelativeTo(null); f.setVisible(true); } } class ReceiptCheckBox extends JCheckBox { private final Receipt receipt; public ReceiptCheckBox(Receipt receipt) { super(receipt.toString()); this.receipt = receipt; } public Receipt getReceipt() { return receipt; } }
Filtering out tab character with documentFilter
So, I have a program with JTextArea with DocumentFilter. It should (among other things) filter out tab characters and prevent them to be entered in the JTextArea completely. Well, it works well when I type, but I can still paste it in. i shouldn't be able to, according to the code... Below is kind of a SSCCE. Just run it, press ctrl+n and enter. All the colored fileds are JTextAreas with same DocumentFilter. The filter itself is the first class (DefaultDocFilter), only thing you need to look into. package core; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import javax.swing.text.JTextComponent; class DefaultDocFilter extends DocumentFilter { public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException { if ((fb.getDocument().getLength() + str.length()) <= 200) { str.replaceAll("\n", " "); str.replaceAll("\t", " "); System.out.print(str); fb.insertString(offs, str, a); } else { int spaceLeft = 200 - fb.getDocument().getLength(); if (spaceLeft <= 0) return; str.substring(0, spaceLeft); str.replaceAll("\n", " "); str.replaceAll("\t", " "); fb.insertString(offs, str, a); } } public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException { if (str.equals("\n") || str.equals("\t")) { str = ""; } if ((fb.getDocument().getLength() + str.length() - length) <= 200) { str.replaceAll("\n", " "); str.replaceAll("\t", " "); fb.replace(offs, length, str, a); } else { int spaceLeft = 200 - fb.getDocument().getLength() + length; if (spaceLeft <= 0) return; fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a); } } } #SuppressWarnings("serial") class DefaultFont extends Font { public DefaultFont() { super("Arial", PLAIN, 20); } } #SuppressWarnings("serial") class Page extends JPanel { public JPanel largePage; public int content; public Page(JPanel panel, int index) { largePage = new JPanel(); largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS)); largePage.setMaximumSize(new Dimension(794, 1123)); largePage.setPreferredSize(new Dimension(794, 1123)); largePage.setAlignmentX(Component.CENTER_ALIGNMENT); largePage.setBackground(Color.WHITE); largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96))); setMaximumSize(new Dimension(556, 931)); setBackground(Color.LIGHT_GRAY); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931))); largePage.add(this); largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96))); panel.add(largePage, index); panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40))); content = 0; Main.pages.add(this); } } #SuppressWarnings("serial") class Heading extends JTextArea { public boolean type; public AbstractDocument doc; public ArrayList<JPanel/*Question*/> questions; public ArrayList<JPanel/*List*/> list; public Heading(boolean segment, Page page) { type = segment; setBackground(Color.RED); setFont(new Font("Arial", Font.BOLD, 20)); Border in = BorderFactory.createDashedBorder(Color.BLACK); Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE); setBorder(BorderFactory.createCompoundBorder(out, in)); setLineWrap(true); setWrapStyleWord(true); setText("Heading 1 Heading 1 Heading 1 Heading 1"); doc = (AbstractDocument)this.getDocument(); doc.setDocumentFilter(new DefaultDocFilter()); page.add(this, 0); page.content++; if (type) { questions = new ArrayList<JPanel>(); } else { list = new ArrayList<JPanel>(); } } } #SuppressWarnings("serial") class Question extends JPanel { public JPanel questionArea, numberArea, answerArea; public JLabel number; public JTextArea question; public AbstractDocument doc; public Question(Page page, int pageNum, int index) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE)); questionArea = new JPanel(); questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS)); questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE)); numberArea = new JPanel(); numberArea.setLayout(new BorderLayout()); numberArea.setBackground(Color.WHITE); number = new JLabel(pageNum+". ", JLabel.RIGHT); number.setMinimumSize(new Dimension(100, 20)); number.setPreferredSize(new Dimension(100, 20)); number.setMaximumSize(new Dimension(100, 20)); number.setFont(new Font("Arial", Font.PLAIN, 17)); numberArea.add(number, BorderLayout.NORTH); questionArea.add(numberArea); question = new JTextArea(); question.setFont(new Font("Arial", Font.PLAIN, 17)); question.setBorder(BorderFactory.createDashedBorder(Color.BLACK)); question.setLineWrap(true); question.setWrapStyleWord(true); question.setBackground(Color.GREEN); question.setText("Is this the first question?"); doc = (AbstractDocument)question.getDocument(); doc.setDocumentFilter(new DefaultDocFilter()); questionArea.add(question); add(questionArea); answerArea = new JPanel(); answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS)); add(answerArea); page.add(this, index); page.content++; } } #SuppressWarnings("serial") class Answer extends JPanel { public JPanel letterArea; public JLabel letter; public JTextArea answer; public AbstractDocument doc; public Answer(Question q, int index) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); letterArea = new JPanel(); letterArea.setLayout(new BorderLayout()); letterArea.setBackground(Color.WHITE); letter = new JLabel((char)(index+96)+") ", JLabel.RIGHT); letter.setMinimumSize(new Dimension(150, 20)); letter.setPreferredSize(new Dimension(150, 20)); letter.setMaximumSize(new Dimension(150, 20)); letter.setFont(new Font("Arial", Font.PLAIN, 17)); letterArea.add(letter, BorderLayout.NORTH); add(letterArea); answer = new JTextArea(); answer.setFont(new Font("Arial", Font.PLAIN, 17)); Border in = BorderFactory.createDashedBorder(Color.BLACK); Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE); answer.setBorder(BorderFactory.createCompoundBorder(out, in)); answer.setLineWrap(true); answer.setWrapStyleWord(true); answer.addKeyListener(new KeyListener() { #Override public void keyPressed(KeyEvent arg0) { System.out.print(((JTextComponent) arg0.getSource()).getText()); if (arg0.getKeyCode() == KeyEvent.VK_ENTER) { String JLabelText = ((JLabel) ((JPanel) ((JPanel) ((Component) arg0.getSource()).getParent()).getComponent(0)).getComponent(0)).getText(); int ansNum = (int)JLabelText.charAt(0)-95; if (ansNum < 6) { Answer k = new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), ansNum); k.answer.grabFocus(); Main.mWindow.repaint(); Main.mWindow.validate(); } } } public void keyReleased(KeyEvent arg0) {} public void keyTyped(KeyEvent arg0) {} }); doc = (AbstractDocument)answer.getDocument(); doc.setDocumentFilter(new DefaultDocFilter()); answer.setBackground(Color.PINK); add(answer); q.answerArea.add(this, index-1); } } public class Main { public static Properties config; public static Locale currentLocale; public static ResourceBundle lang; public static JFrame mWindow; public static JMenuBar menu; public static JMenu menuFile, menuEdit; public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties; public static JDialog newDoc; public static JLabel newDocText1, newDocText2; public static JRadioButton questions, list; public static ButtonGroup newDocButtons; public static JButton newDocOk; public static Boolean firstSegment; public static JPanel workspace; public static JScrollPane scroll; public static ArrayList<Page> pages; public static void newDocumentForm() { //new document dialog mWindow.setEnabled(false); newDoc = new JDialog(mWindow, "newDoc"); newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); newDoc.addWindowListener(new WindowListener () { public void windowActivated(WindowEvent arg0) {} public void windowClosing(WindowEvent arg0) { mWindow.toFront(); newDocText1 = null; newDocText2 = null; questions = null; list = null; newDocButtons = null; newDocOk = null; newDoc.dispose(); mWindow.setEnabled(true); } public void windowClosed(WindowEvent arg0) {} public void windowDeactivated(WindowEvent arg0) {} public void windowDeiconified(WindowEvent arg0) {} public void windowIconified(WindowEvent arg0) {} public void windowOpened(WindowEvent arg0) {} }); newDoc.setSize(400, 200); newDoc.setLocationRelativeTo(null); newDoc.setResizable(false); newDoc.setLayout(null); newDoc.setVisible(true); newDocText1 = new JLabel("newDocText1"); newDocText1.setBounds(5, 0, 400, 20); newDocText2 = new JLabel("newDocText2"); newDocText2.setBounds(5, 20, 400, 20); newDoc.add(newDocText1); newDoc.add(newDocText2); firstSegment = true; questions = new JRadioButton("questions"); questions.setSelected(true); questions.setFocusPainted(false); questions.setBounds(10, 60, 400, 20); questions.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { firstSegment = true; } }); list = new JRadioButton("list"); list.setFocusPainted(false); list.setBounds(10, 80, 400, 20); list.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { firstSegment = false; } }); newDoc.add(questions); newDoc.add(list); newDocButtons = new ButtonGroup(); newDocButtons.add(questions); newDocButtons.add(list); newDocOk = new JButton("ok"); newDocOk.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { newDocOk.doClick(); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }); newDocOk.setFocusPainted(false); newDocOk.setBounds(160, 120, 80, 40); newDocOk.setMnemonic(KeyEvent.VK_ACCEPT); newDocOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { createNewDocument(); } }); newDoc.add(newDocOk); newDocOk.requestFocus(); } public static void createNewDocument() { //dispose of new document dialog mWindow.toFront(); newDocText1 = null; newDocText2 = null; questions = null; list = null; newDocButtons = null; newDocOk = null; newDoc.dispose(); mWindow.setEnabled(true); //create document display workspace = new JPanel(); workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS)); workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40))); workspace.setBackground(Color.BLACK); scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.getVerticalScrollBar().setUnitIncrement(20); scroll.setViewportView(workspace); pages = new ArrayList<Page>(); Page p = new Page(workspace, 1); new Heading(true, p); Question q = new Question(p, 1, 1); new Answer(q, 1); mWindow.add(scroll, BorderLayout.CENTER); mWindow.repaint(); mWindow.validate(); } public static void main(String[] args) throws FileNotFoundException, IOException { //create main window mWindow = new JFrame("title"); mWindow.setSize(1000, 800); mWindow.setMinimumSize(new Dimension(1000, 800)); mWindow.setLocationRelativeTo(null); mWindow.setLayout(new BorderLayout()); mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mWindow.setVisible(true); //create menu bar menu = new JMenuBar(); menuFile = new JMenu("file"); menuEdit = new JMenu("edit"); itmNew = new JMenuItem("new"); itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); itmNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newDocumentForm(); } }); itmClose = new JMenuItem("close"); itmClose.setActionCommand("Close"); itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); itmLoad = new JMenuItem("load"); itmLoad.setActionCommand("Load"); itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK)); itmSave = new JMenuItem("save"); itmSave.setActionCommand("Save"); itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); itmSaveAs = new JMenuItem("saveAs"); itmSaveAs.setActionCommand("SaveAs"); itmExit = new JMenuItem("exit"); itmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Add confirmation window! System.exit(0); } }); itmCut = new JMenuItem("cut"); itmCut.setActionCommand("Cut"); itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); itmCopy = new JMenuItem("copy"); itmCopy.setActionCommand("Copy"); itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); itmPaste = new JMenuItem("paste"); itmPaste.setActionCommand("Paste"); itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); itmProperties = new JMenuItem("properties"); itmProperties.setActionCommand("properties"); itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK)); menuFile.add(itmNew); menuFile.add(itmClose); menuFile.addSeparator(); menuFile.add(itmLoad); menuFile.addSeparator(); menuFile.add(itmSave); menuFile.add(itmSaveAs); menuFile.addSeparator(); menuFile.add(itmExit); menuEdit.add(itmCut); menuEdit.add(itmCopy); menuEdit.add(itmPaste); menuEdit.addSeparator(); menuEdit.add(itmProperties); menu.add(menuFile); menu.add(menuEdit); //create actionListener for menus mWindow.add(menu, BorderLayout.NORTH); mWindow.repaint(); mWindow.validate(); } }
Why don't you assign String into DocumentFilter str = str.replaceAll()?