the mission here is to create JButtons from a String in ActionListener, but we need a way to refresh the GUI panel so it know that there is now variable for the button creater in the GUI. i have a feeling that the button creater must be in ActionListener and there is a command like repaint() or removeAll that is missing inside the ActionListener.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("number of buttons");
JMenuBar meny = new JMenuBar();
JMenu fil = new JMenu("somthing");
JMenuItem angre = new JMenuItem("deleate on button");
JMenuItem angre2 = new JMenuItem("deleate all buttons");
int d;
int i;
public GUI(){
this.setTitle("somthing");
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setJMenuBar(meny);
meny.add(fil);
fil.add(angre2);
fil.add(angre);
angre2.addActionListener(this);
angre.addActionListener(this);
AntallTurneringer.addActionListener(this);
this.add(AntallTurneringer);
AntallTurneringer.setVisible(true);
if(d > 0){
turneringer = new JButton[d];
for(i = 0; i < d; i++){
turneringer[d] = new JButton();
turneringer[d].addActionListener(this);
turneringer[d].setText("Turnering "+(i+1));
turneringer[d].setVisible(true);
this.add(turneringer[d]);
}}
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons");
d = Integer.parseInt(tu);
}
}
You could use a separate panel for the buttons. would simplify the whole thing.
private JPanel buttonPnl;
public void actionPerformed(ActionEvent e){
buttonPnl.invalidate();
buttonPnl.clear();
//create the new buttons
buttonPnl.validate();
buttonPnl.repaint();
}
I have solved it, it were no need for repainting or clearing anything. the first problem in the code were that i had used [d] inside the array, and not[i]. the second problem were the placement of the for loop. this is the working code under.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("Velg antall turneringer");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
int d;
public GUI(){
this.setTitle("Squash Turnering");
this.setLayout(new GridLayout());
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.RED);
AntallTurneringer.addActionListener(this);
AntallTurneringer.setVisible(true);
panel1.add(AntallTurneringer);
add(panel1);
add(panel2);
panel2.setVisible(false);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons you want to add");
d = Integer.parseInt(tu);
turneringer = new JButton[d];
for(int i = 0; i < d; i++){
turneringer[i] = new JButton();
turneringer[i].addActionListener(this);
turneringer[i].setText("Turnering "+(i+1));
turneringer[i].setVisible(true);
turneringer[i].setSize(100, 100);
panel2.add(turneringer[i]);
}
panel1.setVisible(false);
panel2.setVisible(true);
}
}}
Related
sorry for the simple question, but I'm really new to this and can't really find an answer. I'm confused on how to add two (or more) JButtons. I can't seem to get both to show, only one ever shows, which is the "Division" one.
My most recent attempt is below. How can I get both buttons to show at the button of the window?
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:"));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:"));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("x*y="));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
subtractButton = new JButton("Subtract");
frame.add(subtractButton, BorderLayout.SOUTH);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
frame.add(divideButton, BorderLayout.SOUTH);
divideButton.addActionListener(this);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
int x = 0;
int y = 0;
String xText = xfield.getText();
String yText = yfield.getText();
try {
x = Integer.parseInt(xText);
}
catch (NumberFormatException e) {
x = 0;
}
try {
y = Integer.parseInt(yText);
}
catch (NumberFormatException e) {
y = 0;
}
result.setText(Integer.toString(x-y));
}
}
You need to add both buttons in a JPanel before adding that JPanel in the SOUTH of your frame.
So instead of
subtractButton = new JButton("Subtract");
frame.add(subtractButton, BorderLayout.SOUTH);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
frame.add(divideButton, BorderLayout.SOUTH);
divideButton.addActionListener(this);
You can do this
JPanel southPanel = new JPanel();
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Use Eclipse and WindowBuilder for your Swing interfaces and add as many buttons as you like or move them around with your mouse. Its much easier especially if you are new to this and you'll learn a lot from the generated code.
I'm making a simple text editor in Java and for some reason my find and replace actions won't work, i made two separate frames, one for the find action, and the other to open up another frame with 2 jtextfields for find and replace. i have in my actionperformed
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
and in my findFrame i have the action that should be carried out when the user clicks on the JMenuItem called "Find".
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
In my Replace frame where i want the user to find a word and replace it, anything you type into the find textfield and click the find button, it finds the first 3 characters on the text field, and the replace action just doesn't work at all,
here is my replace frame
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
the find and replace are two separate JMenuItems, when the user clicks on Find it opens up findframe and when they click on "replace" it opens up the replace frame which has a find textfield and a replace textfield.
here is the whole runnable code :
//Programmer Aly Badran – Project 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultEditorKit.CutAction;
class saveFrame extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel labelpanel = new JPanel();
JButton savebutton = new JButton("Save");
JButton dontsave = new JButton("Dont Save");
JLabel savelabel = new JLabel("Are you sure you want to close"?);
public saveFrame(){
setSize(400,100);
setLocation(500, 300);
setTitle("Saving...");
labelpanel.add(savelabel);
panel.add(savebutton);
panel.add(dontsave);
Container cpane = getContentPane();
cpane.add(panel, "South");
cpane.add(labelpanel, "Center");
setVisible(true);
savebutton.addActionListener(this);
dontsave.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == savebutton){
System.exit(0);
}
else if(source == dontsave){
System.exit(0);
}
}
}
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
class MenuFrame extends JFrame implements ActionListener, MouseListener{
static JTextArea textarea = new JTextArea();
static JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem copy = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cut = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem copyAction = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cutAction = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem pasteAction = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenu search = new JMenu("Search");
JMenuItem open = new JMenuItem("Open");
JMenuItem close = new JMenuItem("Close");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem find = new JMenuItem("Find");
JMenuItem replace = new JMenuItem("Replace");
JMenu font = new JMenu("Font");
JCheckBoxMenuItem bold = new JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem italic = new JCheckBoxMenuItem("Italic");
JPopupMenu popup;
public MenuFrame(){
Container cpane = getContentPane();
cpane.add(textarea);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenheight = d.height;
int screenwidth = d.width;
setSize(screenwidth, screenheight);
JPanel panel = new JPanel();
ImageIcon closeicon = new ImageIcon("bin/close.png");
ImageIcon openicon = new ImageIcon("bin/open.png");
ImageIcon quiticon = new ImageIcon("bin/quit.jpeg");
ImageIcon findicon = new ImageIcon("bin/find.png");
ImageIcon replaceicon = new ImageIcon("bin/replace.png");
ImageIcon boldicon = new ImageIcon("bin/bold.png");
ImageIcon italicicon = new ImageIcon("bin/italic.png");
ImageIcon copyicon = new ImageIcon("bin/copy.png");
ImageIcon cuticon = new ImageIcon("bin/cut.png");
ImageIcon pasteicon = new ImageIcon("bin/paste.png");
Border matte = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
Border etched = BorderFactory.createEtchedBorder();
popup = new JPopupMenu();
copy.setText("Copy");
cut.setText("Cut");
Paste.setText("Paste");
copy.setIcon(copyicon);
cut.setIcon(cuticon);
Paste.setIcon(pasteicon);
copyAction.setText("Copy");
cutAction.setText("Cut");
pasteAction.setText("Paste");
copyAction.setIcon(copyicon);
cutAction.setIcon(cuticon);
pasteAction.setIcon(pasteicon);
popup.add(cut);
popup.addSeparator();
popup.add(copy);
popup.addSeparator();
popup.add(Paste);
popup.addSeparator();
popup.add(find);
popup.addSeparator();
popup.add(replace);
edit.add(cutAction);
edit.addSeparator();
edit.add(copyAction);
edit.addSeparator();
edit.add(pasteAction);
find.setIcon(findicon);
replace.setIcon(replaceicon);
close.setIcon(closeicon);
menubar = new JMenuBar();
textarea = new JTextArea("He has achieved success.", d.width, d.height);
JScrollPane scroll = new JScrollPane(textarea);
cpane.add(scroll);
open = new JMenuItem("Open", openicon);
close = new JMenuItem("Close", closeicon);
quit = new JMenuItem("Quit", quiticon);
find = new JMenuItem("Find", findicon);
replace = new JMenuItem("Replace", replaceicon);
bold = new JCheckBoxMenuItem("Bold", boldicon);
italic = new JCheckBoxMenuItem("Italic", italicicon);
textarea.setLineWrap(true);
file.add(open);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(quit);
menubar.add(file);
menubar.add(edit);
menubar.add(search);
menubar.add(font);
search.add(find);
search.addSeparator();
search.add(replace);
font.add(bold);
font.addSeparator();
font.add(italic);
copy.setEnabled(false);
cut.setEnabled(false);
Paste.setEnabled(false);
find.addActionListener(this);
italic.addActionListener(this);
bold.addActionListener(this);
quit.addActionListener(this);
close.addActionListener(this);
find.addActionListener(this);
replace.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
Paste.addActionListener(this);
cut.addMouseListener(this);
textarea.addMouseListener(this);
copy.addMouseListener(this);
Paste.addMouseListener(this);
textarea.setComponentPopupMenu(popup);
file.setBackground(Color.BLACK);
edit.setBackground(Color.BLACK);
search.setBackground(Color.BLACK);
font.setBackground(Color.BLACK);
panel.add(menubar);
menubar.setBorder(matte);
menubar.setBackground(Color.BLACK);
textarea.setBorder(etched);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String command = evt.getActionCommand();
String s = textarea.getSelectedText();
Font f = new Font("Italic", Font.ITALIC, 13);
Font f2 = new Font("Bold", Font.BOLD, 13);
if(italic.isSelected()){
textarea.setFont(f);
}
if(bold.isSelected()){
textarea.setFont(f2);
}
if(bold.isSelected() && italic.isSelected()){
textarea.setFont(f);
textarea.setFont(f2);
}
if(command.equals("Quit"))
System.exit(0);
if(command.equals("Close")){
JFrame frame = new saveFrame();
frame.setVisible(true);
}
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
if(command.equals("Replace")){
JFrame frame2 = new replaceFrame();
frame2.setVisible(true);
}
}
public void mouseClicked(MouseEvent e) {
boolean s = textarea.getSelectedText() != null;
if(s){
copy.setEnabled(true);
cut.setEnabled(true);
Paste.setEnabled(true);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
}
public class Menus {
public static void main(String [] args){
JFrame frame = new MenuFrame();
frame.setJMenuBar(MenuFrame.menubar);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Your basic problem comes down to the fact that the "selection" highlight won't be painted while the JTextArea doesn't have focus, I know, awesome.
However, you could use a Highlighter instead, for example...
if (source == find) {
try {
DefaultHighlighter.DefaultHighlightPainter highlighter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));
MenuFrame.textarea.getHighlighter().addHighlight(n, n + search.length(), highlighter);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
Which will paint a "highlight" over the specified area.
You may want to have a look at this for away to remove it
This and this may also be of interest
In your replace method, you are using the text of the find JButton instead of the findtext JTextField
//String search = find.getText();
String search = findtext.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
Your codes also a mess (sorry, took me a while to navigate it).
For example, you're adding a ActionListener twice to the find menu item and probably some others, which caused to find windows to appear.
I'd avoid using Toolkit#getScreenSize(); in connection with JFrame#setSize, a better solution would be to use JFrame#setExtendedState and pass it JFrame#MAXIMIZED_BOTH, as this will also take into consideration the other UI assets that the OS may have fixed on the screen (like docks and task bars).
You really should be using dialogs instead of JFrames for your "short term input" mechanisms
Your also recreating a bunch of stuff you've already created, for example...
static JTextArea textarea = new JTextArea();
//...
textarea = new JTextArea("He has achieved success.", d.width, d.height);
What's worse, is you add the original instance of the textarea to the frame BEFORE you create the new one, which runs the risk of not knowing which component you are actually dealing with...which is just compounded by the fact that you're using a static reference to it so other classes can access it, which they shouldn't be allowed to do...
In replaceFrame, you are taking text to search from the find field (button), but you should take it from findtext (you are always searching for text "Find").
This is one of the reasons why code duplication is bad - you should extract the finding logic to one place and reuse it in both classes.
I am having a problem implementing the last part of this program, which is to make it where pressing the Enter key moves the active field from one text field to the next one in order (1,2,3,4).
This needs to be done without removing the focus cycling that is used by the tab key.
I have no idea how to even begin doing that, the only thing I've found in the API is replacing the traversal policy with your own, but I don't want to replace it I want to create a new one that runs in parallel with the default one.
public class unit27 {
JButton button1 = new JButton("add to next cup");
JButton button2 = new JButton("add to next cup");
JButton button3 = new JButton("add to next cup");
JButton button4 = new JButton("add to next cup");
JTextField text1 = new JTextField("4");
JTextField text2 = new JTextField("4");
JTextField text3 = new JTextField("4");
JTextField text4 = new JTextField("4");
JLabel label1 = new JLabel("Cup 1");
JLabel label2 = new JLabel("Cup 2");
JLabel label3 = new JLabel("Cup 3");
JLabel label4 = new JLabel("Cup 4");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
public unit27() {
mainPanel.setLayout(new GridLayout(2, 4));
panel1.setLayout(new GridLayout(1, 3));
panel2.setLayout(new GridLayout(1, 3));
panel3.setLayout(new GridLayout(1, 3));
panel4.setLayout(new GridLayout(1, 3));
frame.add(mainPanel);
frame.setSize(800, 800);
frame.setVisible(true);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
panel1.add(label1);
panel1.add(button1);
panel1.add(text1);
panel2.add(label2);
panel2.add(button2);
panel2.add(text2);
panel3.add(label3);
panel3.add(button3);
panel3.add(text3);
panel4.add(label4);
panel4.add(button4);
panel4.add(text4);
button1.add(text1);
button1.addActionListener(new MyListener1());
button2.addActionListener(new MyListener2());
button3.addActionListener(new MyListener3());
button4.addActionListener(new MyListener4());
// end class
}
class MyListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text1.getText());
int b = Integer.parseInt(text2.getText());
int c = a + b;
text2.setText(Integer.toString(c));
}
}
class MyListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text2.getText());
int b = Integer.parseInt(text3.getText());
int c = a + b;
text3.setText(Integer.toString(c));
}
}
class MyListener3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text3.getText());
int b = Integer.parseInt(text4.getText());
int c = a + b;
text4.setText(Integer.toString(c));
}
}
class MyListener4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text4.getText());
int b = Integer.parseInt(text1.getText());
int c = a + b;
text1.setText(Integer.toString(c));
}
}
public static void main(String[] args) {
new unit27();
}
}
Swing does not allow 2 focus cycles to be run at the same time. If you really need to have a second focus cycle (and not just add enter to the focus traversal keys), then what you could do is:
Create a Map which determines your cycle.
On each component with the extra cycle add a key binding for Enter that gets the next visible field in your cycle and calls requestFocus on it.
You would have to maintain the map and create custom checks to see if the next component is visible or should be skipped.
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.
I'm a beginner programmer and I am trying to learn how to pass certain objects created in the main class to other classes (in this case the action listener class).
My question is - How can I pass the button to the action listener class? Here is my code snippet.
public class MaxMinProgram
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Max Min Program");
GridLayout myLayout = new GridLayout(1,11);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int size = 11;
JTextField[] fields = new JTextField[size];
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500,110));
frame.getContentPane().add(panel);
int k = 0;
for(k=0;k<fields.length;k++)
{
fields[k] = new JTextField("", 3);
panel.add(fields[k]);
}
JButton button = new JButton("Randomize");
JButton button2 = new JButton("Max Min");
panel.add(button);
panel.add(button2);
frame.pack();
frame.setVisible(true);
}
}
public class myListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent evt)
{
ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line
int [ ] numbers = new int [10];
JTextField [] textFields;
Random randomize = new Random();
int x = randomize.nextInt(100);
}
}
Thank you very much for your help!
Move
ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line
To your main method, for example
public static void main(String[] args)
{
JFrame frame = new JFrame("Max Min Program");
GridLayout myLayout = new GridLayout(1,11);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int size = 11;
JTextField[] fields = new JTextField[size];
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500,110));
frame.getContentPane().add(panel);
int k = 0;
for(k=0;k<fields.length;k++)
{
fields[k] = new JTextField("", 3);
panel.add(fields[k]);
}
JButton button = new JButton("Randomize");
JButton button2 = new JButton("Max Min");
ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line
panel.add(button);
panel.add(button2);
frame.pack();
frame.setVisible(true);
}
First you should move the whole thing to a constructor
public static void main(String[] args)
{
new MaxMinProgram();
}
public MaxMinProgram(){
JFrame frame = new JFrame("Max Min Program");
GridLayout myLayout = new GridLayout(1,11);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int size = 11;
JTextField[] fields = new JTextField[size];
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500,110));
frame.getContentPane().add(panel);
int k = 0;
for(k=0;k<fields.length;k++)
{
fields[k] = new JTextField("", 3);
panel.add(fields[k]);
}
JButton button = new JButton("Randomize");
JButton button2 = new JButton("Max Min");
panel.add(button);
panel.add(button2);
frame.pack();
frame.setVisible(true);
}
and then you can add the listener:
either
button.addActionListener(new myListener());
or
ActionListener listener = new myListener();
button.addActionListener(listener);
in the constructor.
You add this line in your code after create the instance of button
button.addActionListener(new myListener());
button1.addActionListener(new myListener());
and remove the myListener class and add this class myListener class
public class myListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent evt)
{
int [ ] numbers = new int [10];
JTextField [] textFields;
Random randomize = new Random();
int x = randomize.nextInt(100);
}
}