How to add back and next button for CardLayout? - java

I want to add a 'back' and 'next' button for my gui but it doesn't seem to work. It feels like I'm missing something important in my code. I tried using cl.next(ImagePanel); but the method is not working for some reason.
private void initComponents() {
mainPanel = new javax.swing.JPanel();
cardLayout = new java.awt.CardLayout();
imagePanel = new javax.swing.JPanel(cardLayout);
JLabel firstPicture = new JLabel("");
JLabel secondPicture = new JLabel("");
jButton back = new jButton("\u22b2Back");
jButton next = new jButton("Next\u22b3");
firstPicture.setIcon(...);
secondPicture.setIcon(...);
imagePanel.add(firstPicture, "1");
imagePanel.add(secondPicture, "2");
cardLayout.show(imagePanel, "1");
//...buttons actionPerformed(evt);
mainPanel.add(imagePanel);
}
private void backActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) imagePanel.getLayout();
cl.previous(imagePanel); //should proceed to the previous image... not working
}
private void nextActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout) imagePanel.getLayout();
cl.next(imagePanel); //should proceed to the next image... not working
}

Related

wrong parent for CardLayout in java

I want to change cards in my CardLayout (which contains labels) for every choice in my combo box. So when I select Item2 in the combo box it should show the second card but it returns error instead.
Inside the method initComponents() I successfully showed the first card using cardLayout.show(imagePanel, "1"); but when I tried to do the same inside private void comboMenuActionPerformed(), it returns the error "IllegalArgumentException: wrong parent for CardLayout". Why is this happening?
public class MyFrame extends JFrame {
public MyFrame() {
initComponents();
}
private void initComponents() {
cardLayout = new java.awt.CardLayout();
mainPanel = new javax.swing.JPanel();
centerPanel = new javax.swing.JPanel();
imagePanel = new javax.swing.JPanel(cardLayout);
comboMenu = new javax.swing.JComboBox<>();
JLabel firstPicture = new JLabel("");
JLabel secondPicture = new JLabel("");
...
firstPicture.setIcon(...);
secondPicture.setIcon(...);
imagePanel.add(firstPicture, "1");
imagePanel.add(secondPicture, "2");
String[] menu = {"Item1", "Item2", "Item3"};
cardLayout.show(imagePanel, "1"); //this works fine
imagePanel.setLayout(new java.awt.CardLayout());
centerPanel.add(imagePanel);
comboMenu.setModel(new javax.swing.DefaultComboBoxModel<>(menu));
mainPanel.add(centerPanel);
}
private void comboMenuActionPerformed(java.awt.event.ActionEvent evt) {
if(comboMenu.getSelectedItem().toString().equals("Item2")) {
cardLayout.show(imagePanel, "2"); //WHY THIS DOESN'T WORK
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyFrame().setVisible(true);
}
});
}
private javax.swing.JComboBox<String> comboMenu;
private javax.swing.JPanel centerPanel;
private javax.swing.JPanel imagePanel;
private javax.swing.JPanel mainPanel;
private java.awt.CardLayout cardLayout;
}
imagePanel = new javax.swing.JPanel(cardLayout);
...
cardLayout.show(imagePanel, "1"); //this works fine
imagePanel.setLayout(new java.awt.CardLayout());
You replace the layout of the image panel with a new instance of the CardLayout. Get rid of the last statement:
//imagePanel.setLayout(new java.awt.CardLayout());
You assign the card layout to imagePanel by:
imagePanel = new javax.swing.JPanel(cardLayout);
But then you assign a new card layout by:
imagePanel.setLayout(new java.awt.CardLayout());
This overwrites the first card layout to which you added the labels.

How do I delete an image inside a JLabel by right clicking my mouse

I'm working on an Animal Project and I want to improve the project with the MouseListener functions, but I cannot find out how to do this specific bit and I've looked everywhere. Here is my code so you get a good idea at what I'm doing.
Main Class
public class Animals {
public static void main(String[] args) {
JFrame application = new JFrame("Animal Project");
GUI graphicalInterface = new GUI();
application.add(graphicalInterface);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(200, 200);
application.pack();
application.setVisible(true);
application.setResizable(false);
}
Sub Class
public class GUI extends JPanel implements ActionListener {
private JButton animalOption = new JButton();
private JButton save = new JButton();
private JButton load = new JButton();
private JButton clear = new JButton();
private JPanel buttonPanel;
private JPanel imagePanel;
private ImageIcon bear;
private ImageIcon tiger;
private ImageIcon lion;
private JLabel imageBlock1;
private JLabel imageBlock2;
private JLabel imageBlock3;
private int choice;
private int count = 1;
private JLabel currImageBlock = null;
GUI() {
Border blackline = BorderFactory.createLineBorder(Color.black);
//create button panel
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(100, 230));
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.white);
buttonPanel.setBorder(blackline);
imagePanel = new JPanel(new GridLayout(3, 3));
imagePanel.setPreferredSize(new Dimension(500, 500));
imagePanel.setOpaque(true);
imagePanel.setBackground(Color.white);
imagePanel.setBorder(blackline);
imageBlock1 = new JLabel();
imageBlock1.setPreferredSize(new Dimension(100, 100));
imageBlock1.setOpaque(true);
imageBlock1.setBackground(Color.white);
imageBlock1.setBorder(blackline);
imageBlock2 = new JLabel();
imageBlock2.setPreferredSize(new Dimension(100, 100));
imageBlock2.setOpaque(true);
imageBlock2.setBackground(Color.white);
imageBlock2.setBorder(blackline);
imageBlock3 = new JLabel();
imageBlock3.setPreferredSize(new Dimension(100, 100));
imageBlock3.setOpaque(true);
imageBlock3.setBackground(Color.white);
imageBlock3.setBorder(blackline);
bear = new ImageIcon("Bear.png");
tiger = new ImageIcon("Tiger.png");
lion = new ImageIcon("Lion.png");
animalOption = new JButton();
//add action listener to each button
animalOption.addActionListener(this);
//set button size
animalOption.setPreferredSize(new Dimension(100, 50));
//set text for each button
animalOption.setText("Animal");
animalOption.setToolTipText("press to select your animal");
//add buttons to gui
buttonPanel.add(animalOption);
save = new JButton();
//add action listener to each button
save.addActionListener(this);
//set button size
save.setPreferredSize(new Dimension(100, 50));
//set text for each button
save.setText("Save");
save.setToolTipText("press to save your selection");
//add buttons to gui
buttonPanel.add(save);
load = new JButton();
//add action listener to each button
load.addActionListener(this);
//set button size
load.setPreferredSize(new Dimension(100, 50));
//set text for each button
load.setText("Load");
load.setToolTipText("press to load your selection");
//add buttons to gui
buttonPanel.add(load);
clear = new JButton();
//add action listener to each button
clear.addActionListener(this);
//set button size
clear.setPreferredSize(new Dimension(100, 50));
//set text for each button
clear.setText("Clear");
clear.setToolTipText("press to clear your selection");
//add buttons to gui
buttonPanel.add(clear);
this.add(buttonPanel);
this.add(imagePanel);
imagePanel.add(imageBlock1);
imagePanel.add(imageBlock2);
imagePanel.add(imageBlock3);
}
public void actionPerformed(ActionEvent e) {
if (count == 1) {
currImageBlock = imageBlock1;
} else if (count == 2) {
currImageBlock = imageBlock2;
} else if (count == 3) {
currImageBlock = imageBlock3;
} else if (count > 3 && e.getSource().equals(animalOption)) {
JOptionPane.showMessageDialog(imagePanel, "Your choices have exceeded, please press clear.");
}
if (e.getSource().equals(animalOption) && count < 4) {
choice = selectAnimal();
if (choice == 1) {
currImageBlock.setIcon(bear);
currImageBlock.setToolTipText("This is a bear");
} else if (choice == 2) {
currImageBlock.setIcon(tiger);
currImageBlock.setToolTipText("This is a tiger");
} else if (choice == 3) {
currImageBlock.setIcon(lion);
currImageBlock.setToolTipText("This is a lion");
}
chooseNumber();
count++;
}
if (e.getSource().equals(clear)) {
imageBlock1.setIcon(null);
imageBlock2.setIcon(null);
imageBlock3.setIcon(null);
imageBlock1.revalidate();
imageBlock2.revalidate();
imageBlock3.revalidate();
count = 1;
}
}
static int selectAnimal() {
int animal = 0;
String theAnimal = JOptionPane.showInputDialog("Please enter animal, type 1 for bear, type 2 for tiger, type 3 for lion");
animal = Integer.parseInt(theAnimal);
return animal;
}
And this is what it looks like when I run the code and after I've selected which Animal I want
I have a clear all button where if I click it, it clears all the images in inside the imageBlock Jlabel, however I want to add a feature where if I right click on the specific JLabel the image and all its contents will be deleted inside that specific JLabel. Any help would really be appreciated.
This example code shows how a mouse listener can be used to perform an action (in this case - remove) on an image set as icon within a JLabel. Note a MouseAdapter is used in the code but a MouseListener interface can be implemented with similar result.
Other ways of performing this function:
Select an image label and click a button to remove it.
Open a context or pop-up menu with remove image menu option - when the image label is right-clicked upon.
The example code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageLabelAction {
private JLabel imageBlock;
private ImageIcon koala = new ImageIcon("koala.jpg");
public static void main(String [] args) {
new ImageLabelAction().gui();
}
private void gui() {
JFrame frame = new JFrame();
frame.setTitle("Frame with Image Label");
imageBlock = new JLabel();
imageBlock.setPreferredSize(new Dimension(100, 100));
imageBlock.setOpaque(true);
imageBlock.setBackground(Color.white);
imageBlock.setBorder(BorderFactory.createLineBorder(Color.black));
imageBlock.setIcon(koala);
imageBlock.addMouseListener(new PictureRemoveListener());
frame.add(imageBlock);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(250, 250);
frame.setVisible(true);
}
private class PictureRemoveListener extends MouseAdapter {
#Override public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
imageBlock.setIcon(null);
}
}
}
}
You could set a mouse listener to just move it way out of the frame when right clicked. Or you can make a boolean if mouse is clicked set true and only show that object if the boolean is true, so where you set the image from the file only run that code if right mouse button hasn't been clicked
Something like the following pseudo code:
imageBlock1.addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent e) {
// use flags to figure out if it is right mouse click
imageBlock1.setIcon(null);
}
});
Do this for imageBlock2, 3, 4 etc.
It has been a while but something along those lines could do what you are asking.

JList not displaying any objects?

I've been trying to figure out how to use JList and I cant seem to get it to display an object into my GUI.
there's a class called Drawing that I'm trying to add to the JList and it just doesnt seem to show..
Any help would be greatly appreciated
here's my code:
public class DrawingDisplayer extends JPanel implements ActionListener, ListSelectionListener {
JLabel title;
JButton draw,pause,clear,
open,close,
lines,background;
JSlider speedSlider;
JProgressBar progress;
Drawing drawing;
JFileChooser chooser;
JList fileList;
DefaultListModel listModel;
JPanel drawPanel;
JScrollPane scrollPane;
public DrawingDisplayer(){
title = new JLabel("The Drawing Displayer");
title.setHorizontalAlignment(JLabel.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 24));
draw = new JButton("Draw");
pause = new JButton("Pause");
clear = new JButton("Clear");
speedSlider = new JSlider();
progress = new JProgressBar();
open = new JButton("Open Drawing");
close = new JButton("Close Drawing");
listModel = new DefaultListModel();
fileList = new JList(listModel);
fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fileList.addListSelectionListener(this);
fileList.setVisibleRowCount(10);
scrollPane = new JScrollPane(fileList);
scrollPane.setPreferredSize(new Dimension(200,250));
lines = new JButton("Lines");
background = new JButton("Background");
setLayout(new BorderLayout());
//Draw Panel
drawPanel = new JPanel();
drawPanel.setBorder(BorderFactory.createTitledBorder("Drawing Area"));
//Drawing Speed
JPanel drawSpeed = new JPanel();
drawSpeed.setPreferredSize(new Dimension(300,200));
drawSpeed.setBorder(BorderFactory.createTitledBorder("Drawing Speed"));
drawSpeed.add(draw);
drawSpeed.add(pause);
drawSpeed.add(clear);
drawSpeed.add(speedSlider);
drawSpeed.add(progress);
//File Options
JPanel fileOptions = new JPanel();
fileOptions.setPreferredSize(new Dimension(300,350));
fileOptions.setBorder(BorderFactory.createTitledBorder("File Options"));
open.addActionListener(this);
close.addActionListener(this);
fileOptions.add(open);
fileOptions.add(close);
fileOptions.add(fileList);
fileOptions.add(scrollPane);
//Colour Options.
JPanel colourOptions = new JPanel();
colourOptions.setPreferredSize(new Dimension(300,200));
colourOptions.setBorder(BorderFactory.createTitledBorder("Colour Options"));
colourOptions.add(lines);
colourOptions.add(background);
//Control Panel
JPanel controlPanel = new JPanel();
controlPanel.setPreferredSize(new Dimension(325,200));
controlPanel.add(drawSpeed);
controlPanel.add(fileOptions);
controlPanel.add(colourOptions);
chooser = new JFileChooser(".");
add(title, BorderLayout.NORTH);
add(controlPanel,BorderLayout.WEST);
add(drawPanel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == open){
chooser = new JFileChooser(".");
if(chooser.showOpenDialog(null) == chooser.APPROVE_OPTION){
drawing = new Drawing(chooser.getSelectedFile());
fileList.add(drawing);
listModel.addElement("test");
}
}
else if (e.getSource() == close){
}
}
public void valueChanged(ListSelectionEvent e) {
}
public static void main(String[] args){
DrawingDisplayer panel = new DrawingDisplayer();
JFrame frame = new JFrame("drawing");
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
To understand the problem you're having you need to understand that a component can only reside within a single container (it can only have a single parent).
If you try and add the component to another container, it is removed from the first before been added to the second.
So, in your code you do...
fileList = new JList(listModel);
//...
// Add fileList as the view for the scrollpane...
scrollPane = new JScrollPane(fileList);
scrollPane.setPreferredSize(new Dimension(200, 250));
//...
// Remove fileList from the scrollpane and add it to fileOptions...
fileOptions.add(fileList);
fileOptions.add(scrollPane);
...So, basically, you've started out well, but ended up removing the fileList from the scrollPane and adding it to the fileOptions instead, then added the (now empty) scrollPane to the fileOptions as well...
Remove fileOptions.add(fileList); and it should work as you expect it...
You might also want to take a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?.
You can control the size of the JScrollPane by using things like setVisibleRowCount and appropriate cell renderers ...
The default rendering of an object added to the ListModel is to simple display the toString() of the object.
If you are adding a custom object, then you need to provide a custom renderer. Read the section from the Swing tutorial on How to Use Lists, especially the section on Writing a Custom Cell Renderer for more information on this concept.

Adding picture to JFrame from another class java

I am trying to make a program that reads a file chosen by the user, and after reading the file - the suffix "txt" is changed to "gif" and the file is saved as a picture (which is in the same catalogue as the file). The thing is, this picture variable gets its value in the "actionPerformed-method" and after that I want to add it to a frame in another class- but it doesn't show. Here's the code in my OptionsPane-class:
public class OptionsPane extends JComponent implements ActionListener{
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private FileHandler filehandler;
private String picture;
private JLabel picLabel;
public OptionsPane(){
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
System.out.println("hello");
option = 4;
filehandler = new FileHandler();
filehandler.read();
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
this.add(picLabel);
}
}
}
The frame is in the "MainFrame"-class, which looks like this at the moment:
public class MainFrame extends JFrame{
private JFrame frame = new JFrame();
private String picture;
private JLabel picLabel;
public MainFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
OptionsPane optionspane = new OptionsPane();
frame.add(optionspane);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
}
Why isn't the picture visible in the mainframe?
EDIT
It works now!
https://stackoverflow.com/a/22380387/3271504
Thank you for your help #arooaroo . I tried to write down some of what you wrote, but it still didn't work when I wanted to add an image based on what file the user had chosen (for example if the user chose file text1.txt i wanted the corresponding picture "text1.gif" to show up). With your help, the picture showed up when I typed a specific pathway with "/"-slashes, but when I chose a file and tried to load the picture from the file pathway, it didn't show and that is because it had backslashes in the pathways. This is how it should be (such an irritating problem):
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
filehandler = new FileHandler();
filehandler.read();
filepath = filehandler.getFilePath();
picture = filepath.replaceFirst("txt", "gif");
picture = picture.replaceAll("\\\\", "/");
ImageIcon icon = new ImageIcon(picture);
mainFrame.setPicture(icon);
}
Thank you for your help!
Once you separate your GUI code in to separate classes - which is a Good Thing - you will find the eternal challenge for GUI programming is allowing for clean communication between them where there are inter-dependencies.
In this instance perhaps the simplest approach is to pass in a reference of MainFrame into OptionsPane.
Let's assume you create an additional method in MainFrame for setting the picture:
public class MainFrame extends JFrame{
// all instance vars as before
public MainFrame() {
// same as before except for this line...
OptionsPane optionspane = new OptionsPane(this);
}
public void setPicture(JLabel pictureLabel) {
// add code here for adding the picture...
// That's an exercise for yourself, or another question ;)
}
}
Then in your OptionsPane class:
....
private MainFrame mainFrame; // add a new instance var
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
// ... rest of the code same as before
}
#Override
public void actionPerformed(ActionEvent e) {
//...
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
mainFrame.setPicture(picLabel); // <-- This is where you communicate with the mainFrame instance
//...
}
EDIT
Although my original answer provided a valid and correct solution, it's clear that the OP requires a fully working example, including the code to load display the resulting image. Here's a sample program.
public class OptionsPane extends JComponent implements ActionListener {
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private String picture;
private JLabel picLabel;
private MainFrame mainFrame;
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
// For sake of simplicity I'm ignoring the original button logic here
// and focussing on just getting an icon loaded in the parent frame...
ImageIcon icon = new ImageIcon("/path/to/test/image.png");
// Just pass the icon itself rather than a new label.
mainFrame.setPicture(icon);
}
}
public class MainFrame {
// No need to extend JFrame if you're using a JFrame instance variable
private JFrame frame = new JFrame();
private JLabel picLabel;
private JPanel mainPanel;
public MainFrame() {
mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(Color.DARK_GRAY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
OptionsPane optionspane = new OptionsPane(this);
mainPanel.add(optionspane, BorderLayout.NORTH);
picLabel = new JLabel();
picLabel.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(picLabel, BorderLayout.CENTER);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
public void setPicture(ImageIcon icon) {
picLabel.setIcon(icon);
}
public static void main(String[] args) {
new MainFrame();
}
}
Note I've done a couple of things differently. Personally I always create a JPanel and set that up as the primary layer rather and add that directly to the frame rather than messing with the rootPane. And I used the BorderLayout in this example as it's much simpler.
The other thing is to add the JLabel which is to hold the picture to the GUI in the initial set up. Then you'll see I'm only changing its icon in the setPicture() method rather than adding a new JLabel on each instance.

Java adding components to JOptionPane

I'm trying create a custom panel for a simple data entry dialog. I've created a custom panel which I add my labels and text fields. I'm trying to add it to a JOptionPane for display.
When I call it, my components do not display but the JOptionPane buttons do. What is the correct way of doing this?
Here is where I create my custom panel and call JOptionPane:
public class ListenCustEdit implements ActionListener {
#Override
#SuppressWarnings("empty-statement")
public void actionPerformed(ActionEvent e) {
TestPanel panel = new TestPanel();
int input = JOptionPane.showConfirmDialog(frame, panel, "Edit Customer:"
,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (input == 0) {
// OK
JOptionPane.showMessageDialog(frame,"Changes savewd");
} else {
// Cancel
JOptionPane.showMessageDialog(frame, "No changes were saved");
}
}
}
Here is my custom panel class:
public class TestPanel extends JPanel {
JTextField custIdTextField;
JTextField companyTextField;
JTextField firstNameTextField;
JTextField lastNameTextField;
public TestPanel() {
initUI();
}
public final void initUI() {
// create the panel and set the layout
JPanel main = new JPanel();
main.setLayout(new GridLayout(4,4));
// create the labels
JLabel custIdLabel = new JLabel("Cust Id: ");
JLabel companyLabel = new JLabel("Company: ");
JLabel firstNameLabel = new JLabel("First Name: ");
JLabel lastNameLabel = new JLabel("Last Name: ");
// create the text fields
custIdTextField = new JTextField();
companyTextField = new JTextField();
firstNameTextField = new JTextField();
lastNameTextField = new JTextField();
// add componets to panel
main.add(custIdLabel);
main.add(custIdTextField);
main.add(companyLabel);
main.add(companyTextField);
main.add(firstNameLabel);
main.add(firstNameTextField);
main.add(lastNameLabel);
main.add(lastNameTextField);
}
You need to add the main panel to your TestPanel.
public final void initUI() {
// ...
add(main);
}
In initUI, you create a JPanel (called "main") and stuff it full of components, but don't do anything with it. You need to either add "main" to the actual instance of TestPanel, or just skip the step of creating the "main" panel altogether.
The first way:
public final void initUI() {
// ... everything as before, then
this.add(main);
}
The second way:
public final void initUI() {
this.setLayout(new GridLayout(4,4));
// create the labels
JLabel custIdLabel = new JLabel("Cust Id: ");
JLabel companyLabel = new JLabel("Company: ");
JLabel firstNameLabel = new JLabel("First Name: ");
JLabel lastNameLabel = new JLabel("Last Name: ");
// create the text fields
custIdTextField = new JTextField();
companyTextField = new JTextField();
firstNameTextField = new JTextField();
lastNameTextField = new JTextField();
// add componets to panel
this.add(custIdLabel);
this.add(custIdTextField);
this.add(companyLabel);
this.add(companyTextField);
this.add(firstNameLabel);
this.add(firstNameTextField);
this.add(lastNameLabel);
this.add(lastNameTextField);
}
(The "this."'s aren't strictly necessary, but I added them for illustration.)
Hope this helps!
You didn't add main Panel to your TestPanel instance in the constructor.

Categories