The gui has five buttons, and a default image. I would like the image to change when each of the buttons is pressed. I have tried this for 'pink' by updating the path but I am at loss as to what needs to be done each time.
public class PikminGui extends JFrame{
private JPanel buttons;
private JLabel title;
private JButton grow;
private JButton pink;
private JButton black;
private JButton blue;
private JButton red;
private JButton yellow;
private JFrame f;
private JLabel label;
private JPanel panel;
public String path;
public PikminGui() {
createGui();
}
public void createGui() {
path = "path-to-image1";
f = new JFrame();
panel = new JPanel(new BorderLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setLocation(200,200);
f.setVisible(true);
title = new JLabel("PIKMIN MAKER", JLabel.CENTER);
panel.add(title,BorderLayout.NORTH);
grow = new JButton("Grow");
grow.setBorder(BorderFactory.createRaisedBevelBorder());
panel.add(grow,BorderLayout.WEST);
buttons = new JPanel();
pink = new JButton("Pink");
pink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
path = "path-to-image2";
}
});
black = new JButton("Black");
yellow = new JButton("Yellow");
blue = new JButton("Blue");
red = new JButton("Red");
buttons.setLayout(new FlowLayout());
buttons.add(pink);
buttons.add(black);
buttons.add(yellow);
buttons.add(blue);
buttons.add(red);
panel.add(buttons,BorderLayout.SOUTH);
File file = new File(path);
BufferedImage image;
try {
image = ImageIO.read(file);
label = new JLabel(new ImageIcon(image));
panel.add(label, BorderLayout.CENTER );
f.getContentPane().add(panel);
f.pack();
f.add(panel);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
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
}
}
}
3 Classes - GUI, ImageLoader and Wizard
GUI is the main frame whereas Wizard is just a popup that changes settings and imageloader is image handler
What I want is to load image from wizard to Jlabel on my main GUI but I have no idea where to start and never had experience with loading images onto GUI. Searching for answer on here didn't really help, it just create more confusion for me. I would appreciate if you also can add explanations as well.
GUI -
public class GUI extends JPanel{
//variables
JFrame frame = new JFrame("All-in-one Application");
JMenuBar menuBar;
JMenu file, edit, help, about;
JMenuItem settings, startWizard, exit, save, load, readme;
JLabel imgLabel;
private Wizard wiz;
public void topMenuBar(){
//creating the menubar
menuBar = new JMenuBar();
//Menu
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
about = new JMenu("About");
//MenuItems
startWizard = new JMenuItem("Start Wizard");
//listener for wizard
Wizard wiz = new Wizard();
// GUIListener gListener = new GUIListener();
startWizard.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wiz.startWizardd();
}
});
settings = new JMenuItem("Settings");
readme = new JMenuItem("Read Me");
exit = new JMenuItem("Exit");
save = new JMenuItem("Save");
load = new JMenuItem("Load");
//jbutton
// test = new JButton("Test");
//adding MenuItems to the Menu
/**file**/
file.add(startWizard);
file.add(new JSeparator());
file.add(save);
file.add(load);
file.add(new JSeparator());
file.add(exit);
//end file
//edit
edit.add(settings);
//help
help.add(readme);
//about
//Adding Menu to the menu bar
menuBar.add(file);
menuBar.add(edit);
menuBar.add(help);
menuBar.add(about);
//exit action listener
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public void mainPanel(){
FlowLayout main = new FlowLayout();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(main);
//jlabel
imgLabel = new JLabel("img");
mainPanel.add(imgLabel);
frame.add(mainPanel, BorderLayout.CENTER);
}
//intiate GUI
public void intGUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300,0);
frame.setSize(1400,1000);
topMenuBar();
mainPanel();
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
}
Wizard:
public class Wizard extends JPanel{
//variables
private ImageLoader imgload = new ImageLoader(this);
private JButton applyButton, nextButton, backButton, cancelButton, openMapButton;
JDialog wizDialog;
JFrame wizFrame;
JLabel siteNameLabel, siteMapLabel, AisleNumLabel, laneNumLabel, label;
JTextField siteNameField, aisleNumField, laneNumField;
private JTextField mapURLField = new JTextField(20);
JFileChooser chooser;
private File file;
String fileName;
BufferedImage img; // private JPanel addInfoPanel, controlPanel;
public void startWizardd(){
System.out.println("Starting Wizard....");
wizardGUI();
}
public void wizardCmpt()
{
//setting the panel up with gridlayout settings
FlowLayout map = new FlowLayout();
JPanel mapPanel = new JPanel();
mapPanel.setLayout(map);
FlowLayout grid = new FlowLayout();
JPanel addInfoPanel = new JPanel();
addInfoPanel.setLayout(grid);
FlowLayout controls = new FlowLayout();
JPanel controlPanel = new JPanel();
controlPanel.setLayout(controls);
//buttons
JButton openMapButton = new JButton("Load Map");
openMapButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
imgload.fileChooser();
}
});
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton nextButton = new JButton("Next");
JButton backButton = new JButton("Back");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wizFrame.setVisible(false);
wizFrame.dispose();
}
});
//jlabels
JLabel siteNameLabel = new JLabel("Site Name :");
JLabel siteMapLabel = new JLabel("Site Map :");
JLabel AisleNumLabel = new JLabel("Number of Aisles :");
JLabel laneNumLabel = new JLabel("Number of Lanes :");
//jtextfield
JTextField siteNameField = new JTextField(5);
JTextField aisleNumField = new JTextField(5);
JTextField laneNumField = new JTextField(5);
//adding to GUI
addInfoPanel.add(siteNameLabel);
addInfoPanel.add(siteNameField);
addInfoPanel.add(AisleNumLabel);
addInfoPanel.add(aisleNumField);
addInfoPanel.add(laneNumLabel);
addInfoPanel.add(laneNumField);
mapPanel.add(siteMapLabel);
mapPanel.add(mapURLField);
mapPanel.add(openMapButton);
controlPanel.add(applyButton);
// controlPanel.add(nextButton);
// controlPanel.add(backButton);
controlPanel.add(cancelButton);
wizFrame.add(addInfoPanel, BorderLayout.NORTH);
wizFrame.add(mapPanel, BorderLayout.CENTER);
wizFrame.add(controlPanel, BorderLayout.SOUTH);
}
public void setMapUrlField(String text){
mapURLField.setText(text);
}
public File getFile(){
return file;
}
private void wizardGUI(){
System.out.println("it's loading");
wizFrame = new JFrame("Wizard Operation");
wizFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
wizFrame.setSize(600,600);
wizardCmpt();
wizFrame.pack();
wizFrame.setVisible(true); } }
Image Loader:
public class ImageLoader{
private JLabel label;
JFileChooser chooser;
File file;
private BufferedImage img;
private Wizard wiz;
public ImageLoader(Wizard wiz){
this.wiz = wiz;
}
public File fileChooser(){
File file = null;
JFileChooser fileChooser = new JFileChooser();
FileFilter imageFilter = new FileNameExtensionFilter("Image files ", ImageIO.getReaderFileSuffixes());
fileChooser.setFileFilter(imageFilter);
int retValue = fileChooser.showOpenDialog(wiz);
if(retValue == JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile();
wiz.setMapUrlField(file.getAbsolutePath());
}else{
wiz.setMapUrlField("");
}
return file;
}
}
I am encountering problems with event handling in java.
I want to add the image1 if button 1 is pressed, image2 if button 2 is pressed, et cetera.
This is my code till now; Can anyone help? This code doesn't compile.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;
public class MyPanel extends JPanel {
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JButton jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JButton jcomp8;
private JButton jcomp9;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
private ImageIcon image4;
private ImageIcon image5;
private ImageIcon image6;
private ImageIcon image7;
private ImageIcon image8;
public MyPanel() {
//construct components
image1 = new ImageIcon(getClass().getResource("hang1.jpg"));
image2 = new ImageIcon(getClass().getResource("hang2.jpg"));
image3 = new ImageIcon(getClass().getResource("hang3.jpg"));
image4 = new ImageIcon(getClass().getResource("hang4.jpg"));
image5 = new ImageIcon(getClass().getResource("hang5.jpg"));
image6 = new ImageIcon(getClass().getResource("hang6.jpg"));
image7 = new ImageIcon(getClass().getResource("hang7.jpg"));
image8 = new ImageIcon(getClass().getResource("hang8.jpg"));
jcomp1 = new JLabel (image1);
jcomp2 = new JButton ("1");
jcomp3 = new JButton ("2");
jcomp4 = new JButton ("3");
jcomp5 = new JButton ("4");
jcomp6 = new JButton ("5");
jcomp7 = new JButton ("6");
jcomp8 = new JButton ("7");
jcomp9 = new JButton ("8");
//events
jcomp2.setActionCommand("1");
jcomp3.setActionCommand("2");
jcomp4.setActionCommand("3");
jcomp5.setActionCommand("4");
jcomp6.setActionCommand("5");
jcomp7.setActionCommand("6");
jcomp8.setActionCommand("7");
jcomp9.setActionCommand("8");
jcomp2.addActionListener(new ButtonClickListener());
jcomp3.addActionListener(new ButtonClickListener());
jcomp4.addActionListener(new ButtonClickListener());
jcomp5.addActionListener(new ButtonClickListener());
jcomp6.addActionListener(new ButtonClickListener());
jcomp7.addActionListener(new ButtonClickListener());
jcomp8.addActionListener(new ButtonClickListener());
jcomp9.addActionListener(new ButtonClickListener());
//adjust size and set layout
setPreferredSize(new Dimension(624, 537));
setLayout(null);
//add components
add(jcomp2);
add(jcomp3);
add(jcomp4);
add(jcomp5);
add(jcomp6);
add(jcomp7);
add(jcomp8);
add(jcomp9);
// set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(15, 10, 595, 350);
jcomp2.setBounds(35, 375, 100, 25);
jcomp3.setBounds(190, 375, 100, 25);
jcomp4.setBounds(320, 375, 100, 25);
jcomp5.setBounds(465, 375, 100, 25);
jcomp6.setBounds(35, 450, 100, 25);
jcomp7.setBounds(190, 450, 100, 25);
jcomp8.setBounds(320, 450, 100, 25);
jcomp9.setBounds(465, 450, 100, 25);
}
class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
jcomp1.set(image1);
}
}
}
public static void main (String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
I believe you are trying to get something like this:
public class MyPanel extends JPanel {
private JLabel label;
private JButton[] buttons = new JButton[8];
private ImageIcon[] images = new ImageIcon[8];
public MyPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(2, 4, 15, 10));
for (int i = 0; i < images.length; i++) {
images[i] = new ImageIcon(getClass().getResource(i+1 + ".png"));
buttons[i] = new JButton(String.valueOf(i+1));
buttons[i].setActionCommand(String.valueOf(i+1));
buttons[i].addActionListener(new ButtonClickListener());
buttonPanel.add(buttons[i]);
}
label = new JLabel(images[0]);
setLayout(new BorderLayout());
add(label);
add(buttonPanel, BorderLayout.PAGE_END);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setIcon(images[Integer.parseInt(e.getActionCommand()) - 1]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible(true);
}
}
Notes:
Don't forget to change the image file name.
You can play with the layout manager to get what you want.
I removed setPreferredSize(new Dimension(624, 537)); because you didn't specify a resize behavior which would make this line meaningless. pack() would take care of the sizes for you.
Set the icon of the button or label. To do this, you need to create an ImageIcon, which has multiple constructors to create from a filename or a loaded image.
jcomp1.setIcon(new ImageIcon(...));
Can anyone help me solve this?
imagePanel = new JPanel();
label = new JLabel();
for (int i = 0; i < 9; i++)
{
label.setIcon(image[i]);
imagePanel.add(label);
}
When using this it gives me the errors:
Exception in thread "main" java.lang.NullPointerException...
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at assignment.Furniture_System.<init>(Furniture_System.java:55)
at assignment.Furniture_System.main(Furniture_System.java:113)
I suppose I should explain that I call this for loop in a void function that implements in a class constructor. That constructor is called in the main program.
And the variable array image is shown here:
private ImageIcon image[] =
{
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\1.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\2.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\3.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\4.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\5.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\6.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\7.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\8.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\9.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\10.jpg"),
};
All I am trying to do is cycle through the array, set and display the images as the cycle goes through.
Below is the whole program to make it easier to fix:
private ImageIcon image[] =
{
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\1.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\2.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\3.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\4.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\5.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\6.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\7.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\8.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\9.jpg"),
new ImageIcon ("C:\\Users\\James\\Pictures\\Java\\10.jpg")
};
private JLabel label;
private JLabel sofaImageLabel;
private JLabel armchairImageLabel;
private JLabel cDeskImageLabel;
private JLabel cTableImageLabel;
private JLabel tvStandImageLabel;
private JLabel cushionImageLabel;
private JLabel bedImageLabel;
private JLabel mattressImageLabel;
private JLabel duvetImageLabel;
private JLabel pillowImageLabel;
private JPanel buttonPanel;
private JPanel imagePanel;
private JButton button;
public Furniture_System()
{
setTitle("Furniture Management System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildImagePanel();
// buildButtonPanel();
add(imagePanel, BorderLayout.WEST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildImagePanel()
{
imagePanel = new JPanel();
for (int i = 0; i < 9; i++)
{
label = new JLabel();
label.setIcon(image[i]);
imagePanel.add(label);
}
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
button = new JButton("Get Image");
button.addActionListener(new chooseFileButton());
buttonPanel.add(button);
}
private class chooseFileButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
/* String filename = null;
JFileChooser fileChosen = new JFileChooser();
int status = fileChosen.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChosen.getSelectedFile();
filename = selectedFile.getPath();
JOptionPane.showMessageDialog(null, "You selected " + filename);
}
ImageIcon image = new ImageIcon(filename);
sofaImageLabel.setIcon(image);
sofaImageLabel.setText(null);
pack(); */
}
}
public static void main(String[] args)
{
new Furniture_System();
}
}
Any component can have only one parent container, and not be reused.
So the code must be:
for (ImageIcon img : image)
{
JLabel label = new JLabel();
label.setIcon(img);
imagePanel.add(label);
}
Though I would look in Furniture_System.java at line 55 (in the constructor) what could be an access to null. Like above maybe imagePanel being null.
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.