How to change images with a JButton - java

How can I change between the pictures with help of clicking the button.
I made a x variable because then I could make different if-statements but that didn't work for me, probably because I did something wrong... Here is my code so far:
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private JLabel pic2;
private JLabel pic3;
private JLabel picture;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel(new ImageIcon("pic1.png"));
pic2 = new JLabel(new ImageIcon("pic.png"));
pic3 = new JLabel(new ImageIcon("pic3.png"));
panel.add(pic1);
panel.add(pic2);
panel.add(pic3);
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}

public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel();
panel.add(pic1);
ImageIcon icon1 = new ImageIcon("pic1.gif");
ImageIcon icon2 = new ImageIcon("pic2.gif");
ImageIcon icon3 = new ImageIcon("pic3.gif");
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
if(x == 0){
pic1.setIcon(icon1);
}else if(x == 1){
pic1.setIcon(icon2);
}else if(x == 2){
pic1.setIcon(icon3);
}
Main.this.pack();
x++;
if(x > 2) x = 0;
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
you don't need multiple JLabels, use 3 ImageIcons instead.
you need to call JFrame's pack() every time you had UI Changes (in
this case, changing image)

Related

Java Swing GridLayout Change Grid Sizes

I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}

Why is JFrame not registering "ESC" being pressed? [duplicate]

This question already has answers here:
Keylistener not working for JPanel
(4 answers)
KeyListener not working in JPanel?
(1 answer)
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 1 year ago.
In my game, I want the player to be able to press ESC and activate a menu. In this menu, they would be able to return to the home screen. I have tried to use .addKeyListener() as you will see below. I have tried using event.getKeyCode() == 27 and event.getKeyCode() == KeyEvent.VK_ESCAPE, but it doesn't seem to change the outcome(JFrame not registering "ESC" being pressed.
Is there a bug in my code? Or am I just missing something blatant..
Code(refer to this if you have an answer):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Main {
static JFrame jframe = new JFrame();
static JLabel startingTitle = new JLabel("Welcome!");
static JPanel aiPanel = new JPanel();
static Font buttonFont = new Font("MineCrafter", Font.BOLD, 20);
static JFrame gameScreen = new JFrame();
static JFrame onevoneScreen = new JFrame();
static JFrame escScreen = new JFrame();
static JPanel onevonePanel = new JPanel();
static JFrame aiScreen = new JFrame();
static JPanel title = new JPanel();
static JButton onevone = new JButton("Multiplayer");
static JButton aifight = new JButton("Singleplayer");
static JButton BackToStart = new JButton("Back");
public Main(){
Font myFont = new Font("Serif", Font.BOLD, 30);
startingTitle.setFont(myFont);
startingTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
onevone.setAlignmentX(Component.CENTER_ALIGNMENT);
aifight.setAlignmentX(Component.CENTER_ALIGNMENT);
title.setLayout(new BoxLayout(title, BoxLayout.Y_AXIS));
title.add(Box.createRigidArea(new Dimension(0, 50)));
title.add(startingTitle);
title.add(Box.createRigidArea(new Dimension(0, 50)));
title.add(aifight);
title.add(Box.createRigidArea(new Dimension(0, 25)));
title.addKeyListener(new MKeyListener());
title.add(onevone);
gameScreen.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gameScreen.setLocationRelativeTo(null);
gameScreen.setExtendedState(JFrame.MAXIMIZED_BOTH);
gameScreen.add(title);
gameScreen.pack();
}
static void setEscScreen(boolean on){
escScreen.setVisible(on);
}
public static void main(String[] argv) throws Exception {
SwingUtilities.invokeLater(Main::new);
BackToStart.setFont(buttonFont);
BackToStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
aiPanel.setVisible(false);
onevonePanel.setVisible(false);
title.setVisible(true);
gameScreen.add(title);
}
});
JButton startGame = new JButton("Launch");
startGame.setFont(buttonFont);
startGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Started");
jframe.setVisible(false);
gameScreen.setVisible(true);
title.setVisible(true);
}
});
// Creates starting screen
onevone.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Activate 1v1");
title.setVisible(false);
onevonePanel.setVisible(true);
gameScreen.add(onevonePanel);
}
});
aifight.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Activate AI");
title.setVisible(false);
aiPanel.setVisible(true);
gameScreen.add(aiPanel);
}
});
// Creates onevoneScreen
JLabel onevoneTitle = new JLabel("1v1[In Progress]");
onevonePanel.add(onevoneTitle);
onevonePanel.addKeyListener(new MKeyListener());
// Creates aiScreen
JLabel aiTitle = new JLabel("ai[In Progress]");
aiPanel.add(aiTitle);
aiPanel.addKeyListener(new MKeyListener());
//Creates escScreen
escScreen.setLayout(new GridBagLayout());
escScreen.add(BackToStart, new GridBagConstraints());
escScreen.getContentPane().setBackground(new Color(211, 211, 211));
escScreen.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
escScreen.setLocationRelativeTo(null);
escScreen.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Creates launch screen
jframe.setLayout( new GridBagLayout() );
jframe.add(startGame, new GridBagConstraints());
jframe.setSize(400, 350);
jframe.setVisible(true);
}
}
class MKeyListener extends KeyAdapter {
static boolean escapedOn = false;
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
int e = event.getKeyCode();
if (e == KeyEvent.VK_ESCAPE){
if (escapedOn == true){
System.out.println("escaped off");
Main.setEscScreen(false);
escapedOn = false;
} else if (escapedOn == false){
System.out.println("escaped on");
Main.setEscScreen(true);
escapedOn = true;
}
}
}
}
Another question that I would like to be answered(but doesn't have to be answered): Can I make the menu JFrame slightly transparent(so that you can see the game in the background)? If I can, can you implement it in the answer too?

create Jbuttons from ActionListener variable

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);
}
}}

Uploading JPG Images in GUI Java?

So we randomly choose a number between 1 to 6 and whatever is rolled will have an image uploaded of a die face that corresponds to the number. It's compiling, but I get an exception thread I don't understand.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.awt.FlowLayout;
public class Butttin {
private static JLabel label;
public static void main(String[] args) {
JFrame frame = new JFrame("Rolling Dice Game");
JPanel panel = new JPanel();
JButton buttonRoll = new JButton("Roll!");
buttonRoll.addActionListener(new buttonRoll());
panel.setLayout(new GridLayout(5, 2, 5, 5));
panel.add(label);
frame.setVisible(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
}
private static class buttonRoll implements ActionListener {
private java.util.Random random = new java.util.Random();
public void actionPerformed(ActionEvent event) {
int max = 6;
int min = 1;
ImageIcon img;
int rolledNumber = random.nextInt(max - min + 1) + min;
String command = event.getActionCommand();
if (command == "Roll!") {
if ("Roll!".equals(command)) {
ImageIcon imageIcon = new ImageIcon("die 1.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 2){
ImageIcon imageIcon = new ImageIcon("die 2.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 3){
ImageIcon imageIcon = new ImageIcon("die 3.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 4){
ImageIcon imageIcon = new ImageIcon("die 4.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 5){
ImageIcon imageIcon = new ImageIcon("die 5.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 6){
ImageIcon imageIcon = new ImageIcon("die 6.jpg");
label = new JLabel(imageIcon);
}
}
}
}
}
The problem is that you do not initialize your JLabel before you add it to your JPanel. The easiest thing to do would be to initialize it directly:
private static JLabel label = new JLabel();
And in your actionPerformed method, instead of creating a new JLabel every time and replacing the old one, just use its setIcon method.
label.setIcon(imageIcon);
On another note, when working with Swing components (creating components, adding components, etc), it should be run on the Event Dispatch Thread:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//...
}
});

Trouble Updating AbstractTableModel from another Class

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.

Categories