I am trying to create a JList with a small arrow next to it. When clicked, I want some content associated with the list item shown in the same List/Panel. The picture, I hope, gives a clear idea of what I am trying to achieve.
How do I do this ? Also, what is the small triangle feature to the left known as (for future search tags) ?
I hope this is what you meant. The arrowButton is a JToggleButton which, when activated, displays a JWindow containing information about the selected value of the JList. This JWindow will remain visible until the JToggleButtons state is set back to unselected again. The ListPanel class should be reusable in your code.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Example {
public Example() {
JFrame frame = new JFrame();
ArrayList<Object> elements = new ArrayList<Object>();
ArrayList<String> texts = new ArrayList<String>();
ListPanel listPanel = new ListPanel(elements, texts);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JTextField elementField = new JTextField(5);
JTextArea textArea = new JTextArea(5, 10);
JPanel panel = new JPanel();
panel.add(new JLabel("Element:"));
panel.add(elementField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Text:"));
panel.add(new JScrollPane(textArea));
int result = JOptionPane.showConfirmDialog(frame, panel, "Element & Text",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
listPanel.addElementToList(elementField.getText(), textArea.getText());
}
}
});
JButton deleteButton = new JButton("Remove");
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (listPanel.getList().getSelectedValue() != null) {
listPanel.removeElementFromList(listPanel.getList().getSelectedValue());
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
frame.add(listPanel);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
class ListPanel extends JPanel {
private JList<Object> list;
private JToggleButton arrowButton;
private ArrayList<String> texts;
private JWindow popup;
public ListPanel(ArrayList<Object> elements, ArrayList<String> texts) {
this.texts = texts;
popup = new JWindow();
arrowButton = new JToggleButton("\u25B6");
arrowButton.setMargin(new Insets(0, 0, 0, 0));
arrowButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arrowButton.isSelected()) {
Object value = list.getSelectedValue();
if (value != null) {
JLabel titleLabel = new JLabel(value.toString());
titleLabel.setBackground(Color.WHITE);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
titleLabel.setHorizontalAlignment(JLabel.LEFT);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
titlePanel.setBackground(Color.WHITE);
titlePanel.add(titleLabel);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setText(texts.get(list.getSelectedIndex()));
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
contentPanel.add(titlePanel, BorderLayout.NORTH);
contentPanel.add(textPane);
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
popup.setContentPane(contentPanel);
popup.revalidate();
popup.pack();
popup.setVisible(true);
}
} else {
if (popup.isVisible()) {
popup.setVisible(false);
}
}
}
});
Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (((JFrame) SwingUtilities.getWindowAncestor(ListPanel.this)) != null) {
activateComponentListener();
timer.stop();
}
}
});
timer.start();
list = new JList<Object>(new DefaultListModel<Object>());
for (Object element : elements) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
}
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(Color.WHITE);
buttonPanel.add(arrowButton, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBorder(null);
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollPane);
add(buttonPanel, BorderLayout.WEST);
}
private void activateComponentListener() {
((JFrame) SwingUtilities.getWindowAncestor(this)).addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent arg0) {
if (popup.isVisible()) {
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
}
}
});
}
public void removeElementFromList(Object element) {
int index = getElementIndex(element);
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(getElementIndex(element)) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
public void removeElementFromList(int index) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(index) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
private Integer getElementIndex(Object element) {
for (int i = 0; i < ((DefaultListModel<Object>) getList().getModel()).getSize(); i++) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(i).equals(element)) {
return i;
}
}
return null;
}
public void addElementToList(Object element, String text) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
getTexts().add(text);
}
public JList<Object> getList() {
return list;
}
public JToggleButton getArrowButton() {
return arrowButton;
}
public ArrayList<String> getTexts() {
return texts;
}
}
Related
I use the method getSelectedRow() to get the index of the selected row in the first table. When I use it again to get the index of the selected row in the second table it still returns the index of the selected row in the first table. I can't figure out why!
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Selection extends JFrame {
int row;
String actualArray;
JPanel panel = new JPanel();
JPanel dialogPanel = new JPanel();
DefaultTableModel model1 = new DefaultTableModel();
DefaultTableModel model2 = new DefaultTableModel();
JTable table1 = new JTable(model1);
JTable table2 = new JTable(model2);
JScrollPane scrollPane1 = new JScrollPane(table1);
JScrollPane scrollPane2 = new JScrollPane(table2);
JButton showSelectedRow = new JButton("Show");
JButton switchTable = new JButton("switch");
JDialog dialog = new JDialog();
JLabel label = new JLabel();
String [] columns = {"ID","Name"};
String [][] array1 = {{"0001","Alice"},{"0002","Evanka"},{"0003","Steve"}};
String [][] array2 = {{"0004","David"},{"0005","Mario"},{"0006","Marry"}};
public Selection() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Selection();
}
});
}
private void createAndShowGUI() {
model1.setDataVector(array1,columns);
model2.setDataVector(array2,columns);
panel.setBounds(15,20,500,480);
scrollPane1.setBounds(20,25,50,50);
scrollPane2.setBounds(20,25,50,50);
showSelectedRow.setBounds(40,160,60,25);
switchTable.setBounds(120,160,60,25);
actions();
panel.add(scrollPane1);
actualArray="array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
setSize(550, 500);
setLocation(230, 70);
setLayout(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void actions() {
showSelectedRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
row =table1.getSelectedRow();
} else {
row =table2.getSelectedRow();
}
showDialog();
}
});
switchTable.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
panel.removeAll();
panel.add(scrollPane1);
actualArray = "array2";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
} else {
panel.removeAll();
panel.add(scrollPane2);
actualArray = "array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
}
}
});
}
private void showDialog() {
dialogPanel.setBounds(5,5,50,30);
label.setText(String.valueOf(row));
label.setBounds(10,10,180,20);
dialogPanel.add(label);
dialog.add(dialogPanel);
dialog.setSize(60, 50);
dialog.setLocation(450, 250);
dialog.setLayout(null);
dialog.setResizable(false);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.setVisible(true);
}
}
I think your logic is backwards here...
When actualArray equals "array1", you're adding scrollPane1 and setting actualArray to "array2" ... shouldn't you be adding scrollPane2?
if (actualArray.equals("array1")) {
panel.removeAll();
panel.add(scrollPane1);
actualArray = "array2";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
} else {
panel.removeAll();
panel.add(scrollPane2);
actualArray = "array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
}
Having said that, I "accidentally" fixed you code trying to repair the null layout issues.
This example makes use of a CardLayout to switch between the tables instead...
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class FixMe extends JFrame {
int row;
String actualArray;
JPanel panel = new JPanel();
JPanel dialogPanel = new JPanel();
DefaultTableModel model1 = new DefaultTableModel();
DefaultTableModel model2 = new DefaultTableModel();
JTable table1 = new JTable(model1);
JTable table2 = new JTable(model2);
JScrollPane scrollPane1 = new JScrollPane(table1);
JScrollPane scrollPane2 = new JScrollPane(table2);
JButton showSelectedRow = new JButton("Show");
JButton switchTable = new JButton("switch");
JDialog dialog = new JDialog();
JLabel label = new JLabel();
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
public FixMe() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FixMe();
}
});
}
private CardLayout cardLayout;
private void createAndShowGUI() {
setLayout(new BorderLayout());
label.setBorder(new EmptyBorder(16, 16, 16, 16));
label.setHorizontalAlignment(JLabel.CENTER);
dialog.add(label);
cardLayout = new CardLayout();
panel.setLayout(cardLayout);
model1.setDataVector(array1, columns);
model2.setDataVector(array2, columns);
actions();
actualArray = "array1";
panel.add(scrollPane1, "array1");
panel.add(scrollPane2, "array2");
JPanel actions = new JPanel(new GridBagLayout());
actions.add(showSelectedRow);
actions.add(switchTable);
// panel.add(showSelectedRow);
// panel.add(switchTable);
add(panel);
add(actions, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
// setSize(550, 500);
// setLocation(230, 70);
// setLayout(null);
// setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void actions() {
showSelectedRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
row = table1.getSelectedRow();
} else {
row = table2.getSelectedRow();
}
showDialog();
}
});
switchTable.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
// panel.removeAll();
// panel.add(scrollPane1);
actualArray = "array2";
cardLayout.show(panel, actualArray);
// panel.add(showSelectedRow);
// panel.add(switchTable);
// add(panel);
// repaint();
} else {
// panel.removeAll();
// panel.add(scrollPane2);
actualArray = "array1";
cardLayout.show(panel, actualArray);
// panel.add(showSelectedRow);
// panel.add(switchTable);
// add(panel);
// repaint();
}
}
});
}
private void showDialog() {
label.setText(String.valueOf(row));
dialog.pack();
dialog.setLocationRelativeTo(panel);
dialog.setVisible(true);
// label.setBounds(10, 10, 180, 20);
// dialogPanel.add(label);
// dialog.add(dialogPanel);
// dialog.setSize(60, 50);
// dialog.setLocation(450, 250);
// dialog.setLayout(null);
// dialog.setResizable(false);
// dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
// dialog.setVisible(true);
}
}
I recommend having a read through of Laying Out Components Within a Container
Now, having said all that, I would recommend just switching the models...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
TableModel model1 = new DefaultTableModel(array1, columns);
TableModel model2 = new DefaultTableModel(array2, columns);
JFrame frame = new JFrame();
frame.add(new TestPane(new TableModel[]{model1, model2}));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private TableModel[] models;
private int currentModel = 0;
private JLabel selectedRowLabel;
public TestPane(TableModel[] models) {
setLayout(new BorderLayout());
table = new JTable();
this.models = models;
table.setModel(models[0]);
setLayout(new BorderLayout());
add(new JScrollPane(table));
selectedRowLabel = new JLabel("...");
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
currentModel += 1;
if (currentModel >= models.length) {
currentModel = 0;
}
table.setModel(models[currentModel]);
updateSelectionInformation();
}
});
JPanel infoPane = new JPanel(new GridBagLayout());
infoPane.add(switchButton);
infoPane.add(selectedRowLabel);
add(infoPane, BorderLayout.SOUTH);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
updateSelectionInformation();
}
});
}
protected void updateSelectionInformation() {
if (table.getSelectedRow() > -1) {
selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
} else {
selectedRowLabel.setText("---");
}
}
}
}
Now, if the previously selected row is important, simply keep track of it when you switch and re-apply it, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
TableModel model1 = new DefaultTableModel(array1, columns);
TableModel model2 = new DefaultTableModel(array2, columns);
JFrame frame = new JFrame();
frame.add(new TestPane(new TableModel[]{model1, model2}));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private TableModel[] models;
private int[] lastSelectedRow;
private int currentModel = 0;
private JLabel selectedRowLabel;
public TestPane(TableModel[] models) {
setLayout(new BorderLayout());
table = new JTable();
lastSelectedRow = new int[models.length];
Arrays.fill(lastSelectedRow, -1);
this.models = models;
table.setModel(models[0]);
setLayout(new BorderLayout());
add(new JScrollPane(table));
selectedRowLabel = new JLabel("...");
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lastSelectedRow[currentModel] = table.getSelectedRow();
currentModel += 1;
if (currentModel >= models.length) {
currentModel = 0;
}
table.setModel(models[currentModel]);
if (lastSelectedRow[currentModel] > -1) {
table.setRowSelectionInterval(lastSelectedRow[currentModel], lastSelectedRow[currentModel]);
}
updateSelectionInformation();
}
});
JPanel infoPane = new JPanel(new GridBagLayout());
infoPane.add(switchButton);
infoPane.add(selectedRowLabel);
add(infoPane, BorderLayout.SOUTH);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
updateSelectionInformation();
}
});
}
protected void updateSelectionInformation() {
if (table.getSelectedRow() > -1) {
selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
} else {
selectedRowLabel.setText("---");
}
}
}
}
I'm writing a GUI in java. I have a JXTable in which I currently only have static data, but I want allow the user to input data by using a template panel that I have created.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class Template_StackOverflowExample extends JPanel{
private JPanel diagPanel = new dialogTemplate();
Object[] columnIdentifiers = {
"id",
"imei",
};
Object[][] data = {
{"1", "123"},
{"2", "123"},
{"3", "123"}
};
private JDialog dialog;
private static DefaultTableModel model;
public Template_StackOverflowExample(){
setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
JButton addRow = new JButton("Add Row");
addRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Add Row");
}
});
JButton editRow = new JButton("Edit Row");
editRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Edit Row");
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1));
TitledBorder buttonBorder = new TitledBorder("Buttons");
buttonPane.setBorder(buttonBorder);
buttonPane.add(addRow);
buttonPane.add(editRow);
model = new DefaultTableModel();
model.setColumnIdentifiers(columnIdentifiers);
JTable table = new JTable(model);
for(int i = 0; i < data.length; i++){
model.insertRow(i, data[i]);
}
JScrollPane scrollPane = new JScrollPane(table);
pane.add(buttonPane, BorderLayout.LINE_END);
pane.add(scrollPane, BorderLayout.CENTER);
add(pane, BorderLayout.CENTER);
}
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null){
dialog = new JDialog(win, name, ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true);
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
Template_StackOverflowExample mainPanel = new Template_StackOverflowExample();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class dialogTemplate extends JPanel{
private JComponent[] content;
private String[] labelHeaders = {
"ID:",
"IMEI:",
};
public dialogTemplate(){
JPanel diagTemplate = new JPanel();
diagTemplate.setLayout(new BorderLayout());
JPanel rowContent = new JPanel(new GridLayout(0, 2));
JLabel idLabel = null;
JLabel imeiLabel = null;
JLabel[] labels = {
idLabel,
imeiLabel,
};
JTextField idTextField = new JTextField(20);
JTextField imeiTextField = new JTextField(20);
content = new JComponent[] {
idTextField,
imeiTextField,
};
for(int i = 0; i < labels.length; i++){
labels[i] = new JLabel(labelHeaders[i]);
rowContent.add(labels[i]);
rowContent.add(content[i]);
labels[i].setLabelFor(content[i]);
}
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1, 5, 5));
buttonPane.add(save);
buttonPane.add(cancel);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
diagTemplate.add(buttonPane, BorderLayout.PAGE_END);
diagTemplate.add(rowContent, BorderLayout.CENTER);
add(diagTemplate);
}
public void closeWindow(){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null) {
win.dispose();
}
}
}
As you might see both of the buttons in the pane creates the dialog that is created first ("Add Row" or "Edit Row"). I want them to create different dialogs so that the editing of data doesn't conflict with the addition of data.
Thanks in advance.
Assign a different dialog-creating method to each button so you can open two dialogs:
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog = new JDialog(win, name, ModalityType.MODELESS);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
dialog.setVisible(true);
}
public void openRowPane2(String name){
if(dialog2 == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog2 = new JDialog(win, name, ModalityType.MODELESS);
dialog2.getContentPane().add(diagPanel2);
dialog2.pack();
dialog2.setLocationRelativeTo(null);
}
dialog2.setVisible(true);
}
I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm developing a swing application. In that I've a JFrame which add JTextfield and JButton dynamically on the button click.and remove the created components if the user clicks the same button.
In the below screen image , when user clicks ADD button new row was added, and text was changed to REMOVE like in 2nd image.
New Row added and previous button text changed to REMOVE.
Now, if I click the REMOVE button, then the newly added row has to dispose and then button has to change the text again to ADD.
I've tried till adding the components, but I stuck up with removing the newly added row.
Anyone please guide me to achieve this.
Below is my code.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ButtonAddDynamic implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonAddDynamic().createAndShowGUI();
}
});
}
private JFrame frame;
private JPanel panel = new JPanel(new GridBagLayout());
private GridBagConstraints constraints = new GridBagConstraints();
private List fields = new ArrayList();
private List fieldButton = new ArrayList();
private List fieldFile = new ArrayList();
private static int countReport = 0;
String files = null;
int y = 2;
protected void createAndShowGUI() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
String[] labels = { "VALIDATION FORM" };
for (String label : labels)
addColumn(label);
frame = new JFrame("Add Button Dynamically");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(panel));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Set the default button to button1, so that when return is hit, it
// will hit the button1
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
private void addColumn(String labelText) {
constraints.gridx = fields.size();
constraints.gridy = 1;
panel.add(new JLabel(labelText), constraints);
constraints.gridy = 2;
final JTextField field = new JTextField(40);
field.setEditable(false);
panel.add(field, constraints);
fields.add(field);
// constraints.gridy=3;
constraints.gridx = fields.size() + fieldButton.size();
final JButton button = new JButton("ADD");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (button.getText().equals("ADD")) {
button.setText("REMOVE");
addRowBelow();
frame.pack();
} else if (button.getText().equals("REMOVE")) {
button.setText("ADD");
frame.pack();
}
}
});
panel.add(button, constraints);
fieldButton.add(button);
panel.revalidate(); // redo layout for extra column
}
private void addRowBelow() {
y++;
constraints.gridy = y;
// System.out.println(fields.size());
for (int x = 0; x < fields.size(); x++) {
constraints.gridx = x;
final JTextField field = new JTextField(40);
field.setEditable(false);
panel.add(field, constraints);
constraints.gridx = x + 1;
final JButton button = new JButton("ADD");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (button.getText().equals("ADD")) {
button.setText("REMOVE");
addRowBelow();
frame.pack();
} else if (button.getText().equals("REMOVE")) {
button.setText("ADD");
frame.pack();
}
}
});
panel.add(button, constraints);
}
}
public void actionPerformed(ActionEvent ae) {
if ("Add Another TextField and Button".equals(ae.getActionCommand())) {
addRowBelow();
frame.pack();
frame.setLocationRelativeTo(null);
}
}
}
Trying to use GridBagLayout is making this very complicated for you. A nested layout scheme is much easier to work with when you are doing this type of thing.
See this MCVE:
I'm not sure I understood your intended functionality 100% correct but I don't think it's as important as the layouts.
My layout scheme is as follows:
This is nice because BoxLayout will handle the vertical listing without much hullabaloo. Instead of having to wrangle with GridBagConstraints, the text field and button are contained together by a panel.
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Insets;
public class FieldList implements Runnable, ActionListener {
public static void main(String... args) {
SwingUtilities.invokeLater(new FieldList());
}
final int maxFields = 2;
JFrame frame;
JPanel listing;
#Override
public void run() {
frame = new JFrame("Text Field Listing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel(new BorderLayout());
content.add(new JLabel("Input Form", JLabel.CENTER), BorderLayout.NORTH);
listing = new JPanel();
listing.setLayout(new BoxLayout(listing, BoxLayout.Y_AXIS));
content.add(listing, BorderLayout.CENTER);
frame.setContentPane(content);
addNewField();
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void addNewField() {
FieldButtonPair field = new FieldButtonPair();
field.button.addActionListener(this);
listing.add(field);
frame.pack();
}
void removeLastField() {
listing.remove(listing.getComponentCount() - 1);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent ae) {
AddRemoveButton source = (AddRemoveButton)ae.getSource();
if(source.state == AddRemoveButton.State.ADD) {
if(listing.getComponentCount() < maxFields) {
addNewField();
source.setState(AddRemoveButton.State.REMOVE);
}
} else if(source.state == AddRemoveButton.State.REMOVE) {
removeLastField();
source.setState(AddRemoveButton.State.ADD);
}
}
}
class FieldButtonPair extends JPanel {
JTextField field;
AddRemoveButton button;
FieldButtonPair() {
super(new BorderLayout());
field = new JTextField();
add(field, BorderLayout.CENTER);
button = new AddRemoveButton();
add(button, BorderLayout.EAST);
}
#Override
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
pref.width = Math.max(480, pref.width);
return pref;
}
}
class AddRemoveButton extends JButton {
enum State { ADD, REMOVE }
State state = State.ADD;
AddRemoveButton() {
setText(state.name());
}
void setState(State state) {
setText(state.name());
this.state = state;
}
#Override
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
Font f = getFont();
FontMetrics fm = getFontMetrics(f);
int w = fm.stringWidth(State.REMOVE.name());
Insets ins = getInsets();
pref.width = (ins.left + w + ins.right);
return pref;
}
}
I am new to using cardlayout and I have a few questions on how to implement it. I first would like to know the best way to implement cardlayout so that I can switch from panel to panel. My main question is how to use buttons inside the constructors of my panels to switch from panel to panel. I just started working on this project today so you will see some code that is not finished or that does not make sense. I first tried to make all my classes to extend JFrame but that led to multiple unwanted windows. If I can get some sort of example on how to effectively use cardlayout and how to switch panels using the buttons within my other panel constructors. My attempts on using cardlayout only worked for buttons that I created in my gui class however that is not the result I want. Please help if you can and thanks in advance.
This is my main class.
public class controller{
public static void main(String[] args){
new Gui();
}
}
This is my gui class.
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Gui extends JFrame{
homePage home = new homePage();
public JPanel loginPanel = new textEmailLog(),
registerPanel = new Register(),
homePanel = new homePage(), viewPanel = new emailView(),
loadPanel = new loadEmail(), contentPanel = new JPanel(new CardLayout());
CardLayout cardLayout = new CardLayout();
public Gui(){
super("Email Database Program");
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPanel.setLayout(cardLayout);
contentPanel.add(loginPanel, "Login");
contentPanel.add(registerPanel, "Register");
contentPanel.add(homePanel, "Home");
contentPanel.add(viewPanel, "View");
contentPanel.add(loadPanel, "Load");
this.setContentPane(contentPanel);
cardLayout.show(contentPanel, "Login");
setVisible(true);
}
My Login Panel class
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
//panel has been added
public class textEmailLog extends JPanel{
JPanel logGui = null;
JButton registerBut, logBut;
JTextField Login;
public textEmailLog(){
//default characteristics
setSize(700,700);
setName("Email Database");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Labels for username and password
JLabel userLab = new JLabel("Username");
JLabel pwLab = new JLabel("Password");
//textfields for username and password
Login = new JTextField("", 15);
JPasswordField Password = new JPasswordField("", 15);
Password.setEchoChar('*');
//login button that confirms username and password
logBut = new JButton("Login");
logBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//needs regex checks prior to logging in
if(e.getSource() == logBut){
/* Change the panel to the homepage
if(Login.getText().equals() && Password.getText().equals()){
}
*/
new homePage();
}
}
});
registerBut = new JButton("Register");
registerBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == registerBut){
//Change the panel to the register panel
}
}
});
//Box layout for organization of jcomponents
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
//add to panel
verticalContainer.add(Box.createVerticalStrut(300));//begin relative to the center
verticalContainer.add(userLab);//Login label and text
verticalContainer.add(Login);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(pwLab);//password label and text
verticalContainer.add(Password);
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(registerBut);//register button
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(logBut);//login button
//combines both the vertical and horizontal container
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
//this.add(logGui);
setVisible(true);
}
}
My Register panel class
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
//No Panel addition
public class Register extends JPanel{
JButton submit, previous;
JLabel firstLab, lastLab, userLab, passwordLab, repassLab, address, emailAdd, errorLabel;
JTextField firstText, lastText, userText, addText, emailAddText;
JPasswordField passwordText, repassText;
public Register(){
setSize(700,700);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//register values and their labels and textfields
firstLab = new JLabel("First Name: ");
firstText = new JTextField("", 25);
lastLab = new JLabel("Last Name: ");
lastText = new JTextField("", 40);
userLab = new JLabel("Username: ");
userText = new JTextField("", 25);
passwordLab = new JLabel("Password: ");
passwordText = new JPasswordField("", 25);
passwordText.setEchoChar('*');
repassLab = new JLabel("Confirm Password");
repassText = new JPasswordField("", 25);
repassText.setEchoChar('*');
address = new JLabel("Address: ");
addText = new JTextField("", 50);
emailAdd = new JLabel("Email Address: ");
emailAddText = new JTextField("", 50);
//error message for reigstration issues
errorLabel = new JLabel();
errorLabel.setForeground(Color.red);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener(){
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == submit){
//confirm with regex methods and if statements that have been created and need to be created
if(firstText.getText().length() == 0){
errorLabel.setText("*You have not entered a first name!");
}else
if(lastText.getText().length() == 0){
errorLabel.setText("*You have not entered a last name!");
}else
if(userText.getText().length() == 0){
errorLabel.setText("*You have not entered a username!");
}else
if(passwordText.toString().length() == 0){
errorLabel.setText("*You have not entered a Password!");
}else
if(repassText.toString().length() == 0){
errorLabel.setText("*You have not matched your password!");
}
if(addText.getText().length() == 0){
errorLabel.setText("*You have not entered an address!");
}else
if(emailAddText.getText().length() == 0){
errorLabel.setText("*You have not entered an Email address!");
}else
if(userText.getText().length() < 8){
errorLabel.setText("*Username is too short!");
}
else
if(!(passwordText.toString().matches(repassText.toString()))){
errorLabel.setText("Passwords do not match!");
}
else
if(!isValidEmailAddress(emailAddText.getText())){
errorLabel.setText("*Invalid Email!");
}
else
if(!isValidAddress(addText.getText())){
errorLabel.setText("*Invalid Address!");
}
}
}
});
//returns to the previous page
previous = new JButton("Previous Page");
previous.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == previous){
//card.show(login panel);
}
}
});
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
verticalContainer.add(Box.createVerticalStrut(150));
verticalContainer.add(firstLab);
verticalContainer.add(firstText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(lastLab);
verticalContainer.add(lastText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(userLab);
verticalContainer.add(userText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(passwordLab);
verticalContainer.add(passwordText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(repassLab);
verticalContainer.add(repassText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(address);
verticalContainer.add(addText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailAdd);
verticalContainer.add(emailAddText);
verticalContainer.add(Box.createVerticalStrut(5));
//horizontal
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(submit);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(previous);
//merger
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
setVisible(true);
}
//regex check for valid Email
public boolean isValidEmailAddress(String email){
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[A-Za-z0-9._\\%-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}");
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
//regex check for valid Address
public boolean isValidAddress(String address){
java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\d{1,3}.?\\d{0,3}\\s[a-zA-Z]{2,30}\\s[a-zA-Z]{2,15}");
java.util.regex.Matcher m = p.matcher(address);
return m.matches();
}
}
Homepage panel class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
//NO Panel Yet
#SuppressWarnings("serial")
public class homePage extends JPanel{
JButton uploadEmail, viewEmail;
public homePage(){
setSize(700,700);
uploadEmail = new JButton("Upload Your Email");
uploadEmail.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == uploadEmail){
new loadEmail();
}
}
});
viewEmail = new JButton("View An Email");
viewEmail.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == viewEmail){
new emailView();
}
}
});
add(uploadEmail);
add(viewEmail);
setVisible(true);
}
}
My View Email Panel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class emailView extends JPanel{
JPanel viewPanel;
JButton logout, delete, homepage;
JTable emailList;
//Cannot be edited or may be in a new panel
/*
JLabel fileLab, toLab, fromLab, subjectLab,topicLab, emailLab, notesLab, attachLab;
JTextField fileText, toText, fromText, subjectText, topicText;
JTextArea emailText, notesText, attachText;
*/
public emailView(){
setSize(700,700);
setVisible(true);
emailList = new JTable();
logout = new JButton("Logout");
logout.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == logout){
new textEmailLog();
}
}
});
delete = new JButton("Delete");
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == delete){
}
}
});
homepage = new JButton("HomePage");
homepage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == homepage){
new homePage();
}
}
});
Box horizontalContainer = Box.createHorizontalBox();
Box verticalContainer = Box.createVerticalBox();
Box mergerContainer = Box.createVerticalBox();
horizontalContainer.add(logout);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(homepage);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(delete);
horizontalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailList);
mergerContainer.add(horizontalContainer);
mergerContainer.add(verticalContainer);
add(mergerContainer);
setVisible(true);
}
}
My upload Email Panel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class loadEmail extends JPanel{
JPanel loadPanel;
JLabel fileLab, toLab, fromLab, subjectLab, topicLab, emailLab, notesLab, attachLab;
JTextField fileText, toText, fromText, subjectText, topicText;
JTextArea emailText, notesText, attachText; //attachment text will be changed
JButton cancel, complete, enter;//enter may not be necessary
public loadEmail(){
setSize(700,700);
fileLab = new JLabel("Enter a new File: ");
fileText = new JTextField();
enter = new JButton("Enter");
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == enter){
//opens file directory window
}
}
});
toLab = new JLabel("To: ");
toText = new JTextField();
toText.setSize(5, 30);
fromLab = new JLabel("From: ");
fromText = new JTextField();
subjectLab = new JLabel("Subject: ");
subjectText = new JTextField();
topicLab = new JLabel("Topic: ");
topicText = new JTextField();
emailLab = new JLabel("Email Content: ");
emailText = new JTextArea();
notesLab = new JLabel("Comments: ");
notesText = new JTextArea();
attachLab = new JLabel("Attachments");
attachText = new JTextArea();
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == cancel){
//dispose page
}
}
});
complete = new JButton("Complete");
complete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == complete){
//store in database, prompt user for new email to enter in other wise return to homepage
}
}
});
Box verticalContainer = Box.createVerticalBox();
Box horizontalContainer = Box.createHorizontalBox();
Box mergerContainer = Box.createVerticalBox();
verticalContainer.add(fileLab);
verticalContainer.add(fileText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(Box.createHorizontalStrut(50));
verticalContainer.add(enter);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(toLab);
verticalContainer.add(toText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(fromLab);
verticalContainer.add(fromText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(subjectLab);
verticalContainer.add(subjectText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(topicLab);
verticalContainer.add(topicText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(emailLab);
verticalContainer.add(emailText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(notesLab);
verticalContainer.add(notesText);
verticalContainer.add(Box.createVerticalStrut(5));
verticalContainer.add(attachLab);
verticalContainer.add(attachText);
verticalContainer.add(Box.createVerticalStrut(5));
horizontalContainer.add(cancel);
horizontalContainer.add(Box.createHorizontalStrut(5));
horizontalContainer.add(complete);
mergerContainer.add(verticalContainer);
mergerContainer.add(horizontalContainer);
add(mergerContainer);
setVisible(true);
}
}
The short answer is don't. The reasons for this is you'll end having to expose the parent container and CardLayout to ALL your sub components, which not only exposes portions of your application to potential mistreatment, it tightly couples the navigation making it difficult to add/remove steps in the future...
A better solution would be to devise some kind of controller interface, which defines what each view could do (for example showHome, nextView, previousView), you would then pass an implementation of this interface to each view. Each view would then use this interface to request a change as the needed to.
The controller would know things like, the current view, the home view and how to move between certain views (next/previous) as required.
Updated with simple example
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AllYouViewBelongToMe {
public static void main(String[] args) {
new AllYouViewBelongToMe();
}
public AllYouViewBelongToMe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface ViewContoller {
public void goHome();
public void nextView();
public void previousView();
}
public static class DefaultViewController implements ViewContoller {
public static final String HOME = "home";
private Component currentView = null;
private List<Component> views;
private Map<Component, String> mapNames;
private Container parent;
private CardLayout cardLayout;
public DefaultViewController(Container parent, CardLayout cardLayout) {
this.parent = parent;
this.cardLayout = cardLayout;
views = new ArrayList<>(25);
mapNames = new HashMap<>(25);
}
public CardLayout getCardLayout() {
return cardLayout;
}
public Container getParent() {
return parent;
}
public void addView(Component comp, String name) {
if (!HOME.equals(name)) {
views.add(comp);
}
mapNames.put(comp, name);
getParent().add(comp, name);
}
public void removeView(Component comp, String name) {
views.remove(comp);
mapNames.remove(comp);
getParent().remove(comp);
}
#Override
public void goHome() {
currentView = null;
getCardLayout().show(getParent(), HOME);
}
#Override
public void nextView() {
if (views.size() > 0) {
String name = null;
if (currentView == null) {
currentView = views.get(0);
name = mapNames.get(currentView);
} else {
int index = views.indexOf(currentView);
index++;
if (index >= views.size()) {
index = 0;
}
currentView = views.get(index);
name = mapNames.get(currentView);
}
getCardLayout().show(getParent(), name);
}
}
#Override
public void previousView() {
if (views.size() > 0) {
String name = null;
if (currentView == null) {
currentView = views.get(views.size() - 1);
name = mapNames.get(currentView);
} else {
int index = views.indexOf(currentView);
index--;
if (index < 0) {
index = views.size() - 1;
}
currentView = views.get(index);
name = mapNames.get(currentView);
}
getCardLayout().show(getParent(), name);
}
}
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
CardLayout cardLayout = new CardLayout();
JPanel view = new JPanel(cardLayout);
final DefaultViewController controller = new DefaultViewController(view, cardLayout);
controller.addView(createPane("home"), DefaultViewController.HOME);
controller.addView(createPane("Page #1"), "View1");
controller.addView(createPane("Page #2"), "View2");
controller.addView(createPane("Page #3"), "View3");
controller.addView(createPane("Page #4"), "View4");
controller.goHome();
JPanel controls = new JPanel();
JButton btnPrev = new JButton("<");
JButton btnHome = new JButton("Home");
JButton btnNext = new JButton(">");
controls.add(btnPrev);
controls.add(btnHome);
controls.add(btnNext);
btnNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.nextView();
}
});
btnPrev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.previousView();
}
});
btnHome.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.goHome();
}
});
add(view);
add(controls, BorderLayout.SOUTH);
}
protected JPanel createPane(String name) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel(name));
return panel;
}
}
}