Trouble Updating AbstractTableModel from another Class - java

I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.

Related

How to return an int to another class

I'm trying to learn how to use variables from 1 class in another one. What the first class does is that it sets the int testInt to 0 and once a value is inserted in the textField and then pressed the button it is changing the value to that number. But here is the problem, when I try to use the variable in the other class I print out a 0 instead of the number i typed.
First class that creates the variable and should change it too.
public class RouletteGui extends JPanel {
private JTextField tfInput = new JTextField();
private JPanel center = new JPanel(new BorderLayout());
private JPanel South = new JPanel(new BorderLayout());
private JButton btnSearch = new JButton("Change int value");
private int testInt = 0;
public RouletteGui() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 400));
center.add(tfInput, BorderLayout.CENTER);
add(South, BorderLayout.SOUTH);
add(center, BorderLayout.CENTER);
South.add(btnSearch, BorderLayout.SOUTH);
center.add(tfInput, BorderLayout.CENTER);
createListeners();
}
public void createListeners() {
button b = new button();
btnSearch.addActionListener(b);
}
private class button implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSearch) {
testInt = Integer.parseInt(tfInput.getText());
System.out.println(testInt);
}else{}
}
}
public int getTestInt(){
return testInt;
}
public static void main(String[] a) {
JFrame frame = new JFrame("Kalkylator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RouletteGui());
frame.pack();
frame.setVisible(true);
}
}
Second class that will write out the int.
public class WritingInt {
private RouletteGui rg = new RouletteGui();
public WritingInt(){
System.out.println(rg.getTestInt());
}
public static void main (String args[]){
WritingInt wi = new WritingInt();
}
}

Access variable in Action Listener from class

I've been trying for days to access some variables from a class above in an ActionListener, but I fail all the time :( What am I doing wrong? I hope you can help me folks.
public class FileFrameBetterStructured extends JFrame {
protected FileModel fileModel = new FileModel();
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
TableRowSorter<TableModel> TableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
In the ActionListener I want to access the variables: button, filterText and TableRowSorter. THANK YOU!
Add this to the top of your class:
protected static JButton button;
protected static JTextField filterText;
protected static TableRowSorter<TableModel> TableRowSorter;
Change your code as following
public class FileFrameBetterStructured extends JFrame {
static JButton button;
static JTextField filterText;
staitc TableRowSorter<TableModel> tableRowSorter;
protected FileModel fileModel = new FileModel();
FileFrameBetterStructured()
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
tableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
Hope it helps.

how to select JRadioButton depending on button

see my problem start form this piece of code i add all the addActionListener for the button
but when it come to the Radio button it use addItemListenet but i implements ActionListener only how i will implements ItemListener so i can set Law when ever the user Select sw form the radio button and click on add item~ it will add the item to the right array i made before
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
full code
package item;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author isslam
*/
public class MyFrameMain extends JFrame{
Equipment newq = new Equipment();
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
public MyFrameMain(String title){
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(MyFrameMain.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15,20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5,1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2,2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5,1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
}
}
}
I'm not sure what array you want to fill but get the text with getText()
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
String s1 = iJTextField.getText();
String s2 = nJTextField.getText();
String s3 = swTextField.getText();
String s4 = hwTextField.getText();
// something with these strings
}
If any of the inputs are numbers and you want the numerical value, you need to parse.
Also, these need to be declared as class memebers. You have them declared in the constructor
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
Declared in the constructor, they are not within the scope of the listener class
public class MyFrameMain extends JFrame{
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
public MyFrameMain(String title){
Also, doesn't really look like you need a listener for the radio button, since an event is not necessary. The JButton listens for an event, and in the actionPerformed, it checks if the radio button is selected. Therefore no need for the radio button to listen for any event, the JButton does that.
Try following code. I ahve added a List item and adding values from swTextField TextFiled to item when user select rButton1 and click on addButton button
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
/**
*
* #author isslam
*/
public class Test extends JFrame {
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1;
java.util.List<String> item = new ArrayList<String>();
public Test(String title) {
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15, 20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
rButton1 = new JRadioButton("SW Version", false);
JRadioButton rButton2 = new JRadioButton("HW Type", false);
JRadioButton rButton3 = new JRadioButton("General", true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5, 1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2, 2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5, 1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener {
public void actionPerformed(ActionEvent a) {
Object buttonPressed = a.getSource();
if (buttonPressed.equals(exitButton)) {
System.exit(0);
}
if (buttonPressed.equals(addButton) && rButton1.isSelected()) {
item.add(swTextField.getText());
System.out.println(item);
}
}
}
public static void main(String args[]) {
Test t = new Test("Test");
t.setVisible(true);
}
}
Use ButtonGroup with the JRadioButton of your context.
Use jRadioButton.setActionCommand(String) to set their corresponding action name: for your context "SW Version" and anything such.
Make use of an ArrayList to add the item of your context. Try mapping each such array list using a HashMap<Key, Val> i.e., HashMap<String, ArrayList<Equipment>> where the "SW Version" or anything such name will be the key
Try adding listeners to each action button in-line using the means of anonymous class.
So a sample coding for add action would become depicting the usage(usefulness) of ButtonGroup:
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = buttonGroup1.getSelection()
.getActionCommand();
// actionCommand = "SW Version"
map.get(actionCmmand).add(equipment);
}
});
Tutorial and reference:
How to use Radio Button, check the demo for ButtonGroup
ButtonGroup class
HashMap

get set Text from one JFrame to another pop up JFrame with a textArea

I need to take all the textField, comboBox, jlst, and jslider input from the first frame and make it into a summary in the second frame after the Submit button is picked. I can't figure out the best way to do this. My assignment requires a popup second frame with a textArea and exit button that brings you back to the first frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
public class Ch10Asg extends JFrame
{
private String[] flightNames = {"342", "4324", "939", "104", "222"};
private String[] cardTypes ={"Mastercard", "Visa", "American Express", "Discover"};
private String[] Dates ={"8/1/2013", "8/2/2013", "8/3/2013", "8/4/2013", "8/5/2013"};
private JTextField jtfFirst = new JTextField(10);
private JTextField jtfLast = new JTextField(10);
private JTextField jtfAddress = new JTextField(15);
private JTextField jtfCity = new JTextField(15);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
private JTextField jtfCard = new JTextField(16);
private JComboBox jcbo = new JComboBox(flightNames);
private JComboBox jcbcctype = new JComboBox(cardTypes);
private JList jlst = new JList(Dates);
private JSlider jsldHort = new JSlider(JSlider.HORIZONTAL,0,4,0);
private JButton jbtExit = new JButton ("EXIT");
private JButton jbtClear = new JButton ("CLEAR");
private JButton jbtSubmit = new JButton ("SUBMIT");
private JTextField jtfStart = new JTextField();
private JTextField jtfEnd = new JTextField();
public Ch10Asg()
{
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(new JLabel("First Name"));
p1.add(jtfFirst);
p1.add(new JLabel("Last Name"));
p1.add(jtfLast);
p1.add(new JLabel("Address"));
p1.add(jtfAddress);
p1.add(new JLabel("City"));
p1.add(jtfCity);
p1.add(new JLabel("State"));
p1.add(jtfState);
p1.add(new JLabel("ZIP"));
p1.add(jtfZip);
JPanel p2 = new JPanel(new GridLayout(3,1));
p2.add(new JLabel("Select Flight Number"));
p2.add(jcbo);
p2.add(new JLabel("Select Date"));
p2.add(jlst);
p2.add(new JLabel("Select Time"));
jsldHort.setMajorTickSpacing(1);
jsldHort.setPaintTicks(true);
Hashtable<Integer, JLabel> labels = new Hashtable<Integer, JLabel>();
labels.put(0, new JLabel("4:00am"));
labels.put(1, new JLabel("5:00am"));
labels.put(2, new JLabel("8:00am"));
labels.put(3, new JLabel("11:00am"));
labels.put(4, new JLabel("5:00pm"));
jsldHort.setLabelTable(labels);
jsldHort.setPaintLabels(true);
p2.add(jsldHort);
JPanel p4 = new JPanel(new GridLayout(3,1));
p4.add(new JLabel("Starting City"));
p4.add(jtfStart);
p4.add(new JLabel("Ending City"));
p4.add(jtfEnd);
p4.add(new JLabel("Select Card Type"));
p4.add(jcbcctype);
p4.add(new JLabel("Enter Number"));
p4.add(jtfCard);
p4.add(jbtExit);
p4.add(jbtClear);
p4.add(jbtSubmit);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
add(p4, BorderLayout.SOUTH);
jbtExit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}});
jbtClear.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jtfFirst.setText("");
jtfLast.setText("");
jtfAddress.setText("");
jtfCity.setText("");
jtfState.setText("");
jtfZip.setText("");
jtfCard.setText("");
}});
jbtSubmit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
new Infopane(jtfFirst.getText());
//dispose();
}});
}//ENDOFCONSTRUCTOR
public static void main(String[] args)
{
Ch10Asg frame = new Ch10Asg();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flights");
frame.setVisible(true);
frame.setSize(700,450);
}//ENDOFMAIN
}//ENDOFCLASS
class Infopane extends JFrame
{
private JTextArea Info = new JTextArea();
private JButton jbtExit1 = new JButton ("EXIT");
public Infopane(String jtfFirst)
{
JPanel s1 = new JPanel();
add(Info, BorderLayout.NORTH);
//Info.setFont(new Font("Serif", Font.PLAIN, 14));
Info.setEditable(false);
JScrollPane scrollPane = new JScrollPane(Info);
//setLayout(new BorderLayout(5,5));
add(scrollPane);
add(jbtExit1, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Flight Summary");
setVisible(true);
setSize(700,450);
jbtExit1.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}});
}
}
Suggestions:
The second window shouldn't be a second JFrame but rather a modal JDialog since it truly is a dialog of the first window. This way, you don't have to fret about the second window closing the entire application when it is closed.
You already have an idea of what you should be doing -- passing information from one object to another -- since you're passing the String held by the first window's first name's JTextField into the second class: jtfFirst.getText()
Instead of passing just one JTextField's text, consider creating a third data class that holds all the information that you want to pass from one class to the other, create an object of this in the submit's ActionListener, and pass it into the new class.
Alternatively, you could give your first class getter methods, and just pass an instance of the first object into the second object, allowing the second object to extract info from the first by calling its getter methods.
Edit
For example here are snippets of a code example that works. The main JPanel is called MainPanel:
class MainPanel extends JPanel {
// my JTextFields
private JTextField fooField = new JTextField(10);
private JTextField barField = new JTextField(10);
public MainPanel() {
add(new JLabel("Foo:"));
add(fooField);
add(new JLabel("Bar:"));
add(barField);
add(new JButton(new AbstractAction("Submit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent evt) {
DialogPanel dialogPanel = new DialogPanel(MainPanel.this);
// code deleted....
// create and show a JDialog here
}
}));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
// getter methods to get information held in the fields.
public String getFooText() {
return fooField.getText();
}
public String getBarText() {
return barField.getText();
}
}
And in the dialog panel:
class DialogPanel extends JPanel {
private JTextArea textarea = new JTextArea(10, 15);
private MainPanel mainPanel;
public DialogPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel; // actually don't even need this in your case
// extract the information from the origianl class
textarea.append("Foo: " + mainPanel.getFooText() + "\n");
textarea.append("Bar: " + mainPanel.getBarText() + "\n");
add(new JScrollPane(textarea));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
}

Java Swing RadioButtons

i am making a group of radiobuttons and a Panel in the centre should change the colour clicking the radiobuttons.
Everything seems correct but ... it does not work !
With the main class i see the panel but the colour does not change ...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChoiceFrame extends JFrame
{
public ChoiceFrame()
{
class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setTheColor();
}
}
buttonPanel = createButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
colorPanel = createColorPanel();
add(colorPanel, BorderLayout.NORTH);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
colorPanel.repaint();
}
public JPanel createButtonPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
redButton = new JRadioButton("Red Colour");
blueButton = new JRadioButton("Blue Colour");
greenButton = new JRadioButton("Green Colour");
redButton.addActionListener(listener);
blueButton.addActionListener(listener);
greenButton.addActionListener(listener);
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(blueButton);
group.add(greenButton);
panel.add(redButton);
panel.add(blueButton);
panel.add(greenButton);
return panel;
}
public JPanel createColorPanel()
{
JPanel panel = new JPanel();
return panel;
}
public void setTheColor()
{
if (redButton.isSelected())
colorPanel.setBackground(Color.RED);
else if (blueButton.isSelected())
colorPanel.setBackground(Color.BLUE);
else if (greenButton.isSelected())
colorPanel.setBackground(Color.GREEN);
}
private JPanel colorPanel;
private JPanel buttonPanel;
private JRadioButton redButton;
private JRadioButton blueButton;
private JRadioButton greenButton;
private ActionListener listener;
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 400;
}
Add in your constructor also initialization of ChoiceListener.
listener = new ChoiceListener()
In your createButtonPanel() method, you should initialize your listener with:
listener = new ChoiceListener();
There's no point creating a new ChoiceListener object when an ActionListener field exists.
You can make while loop and Every time while loop will check which radioButton is selected

Categories