Adding ActionListeners to JPanel - java

This questions has been asked a few times but mine is a little different. I created a small application and in the view I added a few JPanels to a JFrame. I then try to add actionListeners in the controller which is where the problem happened.
The code below gives me the following error:
The method addActionListener(new ActionListener(){})
is undefined for the type JPanel
The view class
public class MainMenuGUI {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel findUserPanel;
JPanel deleteUserPanel;
JPanel addUserPanel;
JFrame frame = new JFrame();
JPanel tabbedPanel = new JPanel();
//Controller class for tabbedPanel
ControllerTabbedPane listen = new ControllerTabbedPane(this);
//Controller class for findUserPanel
FindUserPanelController findUserController = new FindUserPanelController(findUserPanel);
public MainMenuGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
findUserPanel = createFindUserPanel();
deleteUserPanel = createDeleteUserPanel();
addUserPanel = createAddUserPanel();
tabbedPane.addTab("Find User", findUserPanel);
tabbedPane.addTab("Delete User", deleteUserPanel);
tabbedPane.addTab("Add User", addUserPanel);
tabbedPanel.add(tabbedPane);
frame.add(tabbedPanel);
frame.pack();
// opens frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel createFindUserPanel() {
findUserPanel = new JPanel();
findUserPanel.setPreferredSize(new Dimension(300, 300));
findUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
findUserPanel.add(firstlbl);
findUserPanel.add(firstNametxt);
findUserPanel.add(lastlbl);
findUserPanel.add(lastNametxt);
findUserPanel.add(addresslbl);
findUserPanel.add(addresstxt);
findUserPanel.add(agelbl);
findUserPanel.add(age);
findUserPanel.add(window, BorderLayout.CENTER);
findUserPanel.add(btn);
return findUserPanel;
}
Controller Class
public class ControllerTabbedPane {
MainMenuGUI mainMenuGUI;
int currentTabbedIndex = 0;
ControllerTabbedPane(MainMenuGUI mainMenuGUI){
this.mainMenuGUI = mainMenuGUI;
addTabbedPaneListeners();
}
private void addTabbedPaneListeners() {
mainMenuGUI.tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
currentTabbedIndex = mainMenuGUI.tabbedPane.getSelectedIndex();
System.out.println("Current tab is:" + currentTabbedIndex);
}
});
}
/*ERROR saying The method addActionListener(new ActionListener(){})
is undefined for the type JPanel*/
private void findPanelListeners() {
mainMenuGUI.findUserPanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}

This is the way to achieve your request:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton bt1 = new JButton();
JButton bt2 = new JButton();
panel1.add(bt1);
panel2.add(bt2);
bt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt1 on panel1 pressed");
}
});
bt2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt2 on panel2 pressed");
}
});
You can modify variables or other objects into the listeners to store which panel was "pressed".

I think its not possible to add addActionListner() to JPanel
Instead
You can use,
JPanel p1=new JPanel();
p1.addMouseListener(this);
And override
public void mouseClicked(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
System.out.println(x+","+y);
//By using x AND y you can identify the panel
}
NB: extends MouseAdapter

Related

Can't set background color

For some reason my background just doesn't turn blue. Does anyone know how to solve this with keeping everything inside?
I've been trying to fix this for ages already, but nothing works apparantly..
public static void window() {
JFrame frame = new JFrame("Sharp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel b = new JPanel();
JLabel label2 = new JLabel("Hello, World!", JLabel.CENTER);
label2.setAlignmentY(0);
label2.setAlignmentX(0);
label2.setText("<html>Made by Julian</html>");
JPanel a = new JPanel();
b.add(label2);
a.setAlignmentX(Component.CENTER_ALIGNMENT);
a.setPreferredSize(new Dimension(850, 500));
a.setMaximumSize(new Dimension(850, 850)); // set max = pref
JToggleButton tb = new JToggleButton("SHARP Instructions");
tb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
if(btn.isSelected()) {
Desktop d = Desktop.getDesktop();
try {
d.browse(new URI("https://pastebin.com/nDdGZ0cJ"));
} catch (IOException | URISyntaxException e2) {
e2.printStackTrace();
}
}
}
});
frame.setBackground(Color.BLUE);
a.add(tb);
// JPanel b = new JPanel();
frame.add(a, new GridBagConstraints());
frame.getContentPane().add(a);
frame.getContentPane().add(b);
//frame.getContentPane().add(b);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Your JPanel a is on top of your JFrame, so just:
a.setBackground(Color.BLUE); will fix it.

Swing panels inside panel not showing

I'm trying to create a JFrame with one main panel contains two panels: left sub-panel has add and remove buttons which will dynamically add and remove components; right panel contains regular component. My code works find when there is only one panel, fails when used inside sub-panel.
public class MultiPanel extends JFrame{
static MultiPanel myFrame;
static int countMe = 0;
JPanel mainPanel;
JPanel userPanel;
JPanel contentPanel;
private static void iniComponents() {
myFrame = new MultiPanel();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.prepareUI();
myFrame.pack();
myFrame.setVisible(true);
}
private void prepareUI() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("My Title");
setPreferredSize(new java.awt.Dimension(1280, 720));
setSize(new java.awt.Dimension(1280, 720));
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
userPanel = new JPanel();
// userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.Y_AXIS));
mainPanel.add(userPanel);
JButton buttonAdd = new JButton("Add subPanel");
buttonAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userPanel.add(new subPanel());
myFrame.pack();
}
});
JButton buttonRemoveAll = new JButton("Remove All");
buttonRemoveAll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userPanel.removeAll();
myFrame.pack();
}
});
contentPanel = new JPanel();
JLabel jLabel1 = new JLabel("Content here");
contentPanel.add(jLabel1);
mainPanel.add(contentPanel);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(mainPanel)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(mainPanel)
);
// getContentPane().add(userPanel, BorderLayout.WEST);
// getContentPane().add(contentPanel, BorderLayout.EAST);
// getContentPane().add(buttonAdd, BorderLayout.PAGE_START);
// getContentPane().add(buttonRemoveAll, BorderLayout.PAGE_END);
}
private class subPanel extends JPanel {
subPanel me;
public subPanel() {
super();
me = this;
JLabel myLabel = new JLabel("This is subPanel(): " + countMe++);
add(myLabel);
JButton myButtonRemoveMe = new JButton("remove me");
myButtonRemoveMe.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
me.getParent().remove(me);
myFrame.pack();
}
});
add(myButtonRemoveMe);
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
iniComponents();
});
}
}
I also wonder what is the proper way to write about the layout, aligning and organizing components seems to be painful for me.

Access variable in Action Listener from class

I've been trying for days to access some variables from a class above in an ActionListener, but I fail all the time :( What am I doing wrong? I hope you can help me folks.
public class FileFrameBetterStructured extends JFrame {
protected FileModel fileModel = new FileModel();
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
TableRowSorter<TableModel> TableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
In the ActionListener I want to access the variables: button, filterText and TableRowSorter. THANK YOU!
Add this to the top of your class:
protected static JButton button;
protected static JTextField filterText;
protected static TableRowSorter<TableModel> TableRowSorter;
Change your code as following
public class FileFrameBetterStructured extends JFrame {
static JButton button;
static JTextField filterText;
staitc TableRowSorter<TableModel> tableRowSorter;
protected FileModel fileModel = new FileModel();
FileFrameBetterStructured()
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
tableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
Hope it helps.

get set Text from one JFrame to another pop up JFrame with a textArea

I need to take all the textField, comboBox, jlst, and jslider input from the first frame and make it into a summary in the second frame after the Submit button is picked. I can't figure out the best way to do this. My assignment requires a popup second frame with a textArea and exit button that brings you back to the first frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
public class Ch10Asg extends JFrame
{
private String[] flightNames = {"342", "4324", "939", "104", "222"};
private String[] cardTypes ={"Mastercard", "Visa", "American Express", "Discover"};
private String[] Dates ={"8/1/2013", "8/2/2013", "8/3/2013", "8/4/2013", "8/5/2013"};
private JTextField jtfFirst = new JTextField(10);
private JTextField jtfLast = new JTextField(10);
private JTextField jtfAddress = new JTextField(15);
private JTextField jtfCity = new JTextField(15);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
private JTextField jtfCard = new JTextField(16);
private JComboBox jcbo = new JComboBox(flightNames);
private JComboBox jcbcctype = new JComboBox(cardTypes);
private JList jlst = new JList(Dates);
private JSlider jsldHort = new JSlider(JSlider.HORIZONTAL,0,4,0);
private JButton jbtExit = new JButton ("EXIT");
private JButton jbtClear = new JButton ("CLEAR");
private JButton jbtSubmit = new JButton ("SUBMIT");
private JTextField jtfStart = new JTextField();
private JTextField jtfEnd = new JTextField();
public Ch10Asg()
{
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(new JLabel("First Name"));
p1.add(jtfFirst);
p1.add(new JLabel("Last Name"));
p1.add(jtfLast);
p1.add(new JLabel("Address"));
p1.add(jtfAddress);
p1.add(new JLabel("City"));
p1.add(jtfCity);
p1.add(new JLabel("State"));
p1.add(jtfState);
p1.add(new JLabel("ZIP"));
p1.add(jtfZip);
JPanel p2 = new JPanel(new GridLayout(3,1));
p2.add(new JLabel("Select Flight Number"));
p2.add(jcbo);
p2.add(new JLabel("Select Date"));
p2.add(jlst);
p2.add(new JLabel("Select Time"));
jsldHort.setMajorTickSpacing(1);
jsldHort.setPaintTicks(true);
Hashtable<Integer, JLabel> labels = new Hashtable<Integer, JLabel>();
labels.put(0, new JLabel("4:00am"));
labels.put(1, new JLabel("5:00am"));
labels.put(2, new JLabel("8:00am"));
labels.put(3, new JLabel("11:00am"));
labels.put(4, new JLabel("5:00pm"));
jsldHort.setLabelTable(labels);
jsldHort.setPaintLabels(true);
p2.add(jsldHort);
JPanel p4 = new JPanel(new GridLayout(3,1));
p4.add(new JLabel("Starting City"));
p4.add(jtfStart);
p4.add(new JLabel("Ending City"));
p4.add(jtfEnd);
p4.add(new JLabel("Select Card Type"));
p4.add(jcbcctype);
p4.add(new JLabel("Enter Number"));
p4.add(jtfCard);
p4.add(jbtExit);
p4.add(jbtClear);
p4.add(jbtSubmit);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
add(p4, BorderLayout.SOUTH);
jbtExit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}});
jbtClear.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jtfFirst.setText("");
jtfLast.setText("");
jtfAddress.setText("");
jtfCity.setText("");
jtfState.setText("");
jtfZip.setText("");
jtfCard.setText("");
}});
jbtSubmit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
new Infopane(jtfFirst.getText());
//dispose();
}});
}//ENDOFCONSTRUCTOR
public static void main(String[] args)
{
Ch10Asg frame = new Ch10Asg();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flights");
frame.setVisible(true);
frame.setSize(700,450);
}//ENDOFMAIN
}//ENDOFCLASS
class Infopane extends JFrame
{
private JTextArea Info = new JTextArea();
private JButton jbtExit1 = new JButton ("EXIT");
public Infopane(String jtfFirst)
{
JPanel s1 = new JPanel();
add(Info, BorderLayout.NORTH);
//Info.setFont(new Font("Serif", Font.PLAIN, 14));
Info.setEditable(false);
JScrollPane scrollPane = new JScrollPane(Info);
//setLayout(new BorderLayout(5,5));
add(scrollPane);
add(jbtExit1, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Flight Summary");
setVisible(true);
setSize(700,450);
jbtExit1.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}});
}
}
Suggestions:
The second window shouldn't be a second JFrame but rather a modal JDialog since it truly is a dialog of the first window. This way, you don't have to fret about the second window closing the entire application when it is closed.
You already have an idea of what you should be doing -- passing information from one object to another -- since you're passing the String held by the first window's first name's JTextField into the second class: jtfFirst.getText()
Instead of passing just one JTextField's text, consider creating a third data class that holds all the information that you want to pass from one class to the other, create an object of this in the submit's ActionListener, and pass it into the new class.
Alternatively, you could give your first class getter methods, and just pass an instance of the first object into the second object, allowing the second object to extract info from the first by calling its getter methods.
Edit
For example here are snippets of a code example that works. The main JPanel is called MainPanel:
class MainPanel extends JPanel {
// my JTextFields
private JTextField fooField = new JTextField(10);
private JTextField barField = new JTextField(10);
public MainPanel() {
add(new JLabel("Foo:"));
add(fooField);
add(new JLabel("Bar:"));
add(barField);
add(new JButton(new AbstractAction("Submit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent evt) {
DialogPanel dialogPanel = new DialogPanel(MainPanel.this);
// code deleted....
// create and show a JDialog here
}
}));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
// getter methods to get information held in the fields.
public String getFooText() {
return fooField.getText();
}
public String getBarText() {
return barField.getText();
}
}
And in the dialog panel:
class DialogPanel extends JPanel {
private JTextArea textarea = new JTextArea(10, 15);
private MainPanel mainPanel;
public DialogPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel; // actually don't even need this in your case
// extract the information from the origianl class
textarea.append("Foo: " + mainPanel.getFooText() + "\n");
textarea.append("Bar: " + mainPanel.getBarText() + "\n");
add(new JScrollPane(textarea));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
}

Getting Static from NonStatic Java (ActionListener)

From my action listener which I believe is static, im trying to call a non static method from a class. How can i call my method from my class?
public class addContent {
User Darryl = new User();
public static void addStuff(){
//Panel and Frame
JPanel panel = new JPanel(new BorderLayout());
JFrame frame = new JFrame("PandaHunterV3");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setup labels
JLabel label = new JLabel("Label");
frame.getContentPane().add(label);
//Setup buttons
JButton button = new JButton("Button");
frame.getContentPane().add(button);
//Action listener
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Darryl.showHealth(); // HERE IS THE PROBLEM.
}
});
//Crap
frame.pack();
frame.setVisible(true);
}
}
and my class from which i am trying to call the methods from
public class User {
int health;
User(){
health = 50;
}
public void showHealth(){
System.out.print(health);
}
public void incHealth(){
health += 20;
}
}
EDIT:
Mark the Daryl instance as static or the method addStuff() as non-static.
btw. use low case for naming the variables / instances and upper-case for class names.
public class AddContent {
private User darryl = new User();
public void addStuff(){
//Panel and Frame
JPanel panel = new JPanel(new BorderLayout());
JFrame frame = new JFrame("PandaHunterV3");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setup labels
JLabel label = new JLabel("Label");
frame.getContentPane().add(label);
//Setup buttons
JButton button = new JButton("Button");
frame.getContentPane().add(button);
//Action listener
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
AddContent.this.darryl.showHealth(); // SHOULD BE FINE
}
});
//Crap
frame.pack();
frame.setVisible(true);
}
}

Categories