Java: Jswing: Jlist - java

When i input a name to the Jlist, the name gets outputted to the lower section of the list, how do i make it to where the name is set to the top of the window
package Gui;
//import java.awt.BorderLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI implements ActionListener {
JButton button;
JTextField field;
JList list;
JTextField name1;
DefaultListModel listModel;
String name;
public GUI(){
listModel = new DefaultListModel();
listModel.addElement(null);
listModel.setSize(1);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
field = new JTextField("Enter Name", 10);
button = new JButton("Click");
list = new JList(listModel);
list.setBorder(BorderFactory.createEmptyBorder(120, 20, 20, 120));
JScrollPane listScrollPane = new JScrollPane(list);
panel.add(listScrollPane);
listScrollPane.setWheelScrollingEnabled(true);
panel.add(button);
panel.add(field);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.addElement(name);
}
}

You can simply use the add(0, object) method.
Instead of listModel.addElement(name), listModel.add(0, name) will add the name at the top of the List.
For the size of the JList you shouldn't use this border but instead select a preferredSize for your JSCrollPane :
package Gui;
...
import java.awt.Dimension;
public class GUI implements ActionListener {
...
public GUI(){
...
list = new JList(listModel);
JScrollPane listScrollPane = new JScrollPane(list);
listScrollPane.setPreferredSize(new Dimension(100, 240));
panel.add(listScrollPane);
...
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.add(0, name);
}
}
Resources :
JavaDoc - DefaultListModel.add(int, Object)

Related

How can I add for JPanel show/hide action to the JButton in implemented ActionListener?

I am trying to understand implemented ActionListener. I couldn't find a way out to add it to JButtons in an othor method. I simply trying to add show and hide action to buttons but I could't. Any help? My code is here. There are 3 colored JPanel and every button should hide or show related color JPanel.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class ShowHidePanels implements ActionListener {
public static void main(String[] args) {
new ShowHidePanels();
}
public ShowHidePanels() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.add(bluePanel());
frame.add(greenPanel());
frame.add(redPanel());
frame.add(buttonPanel());
frame.setSize(950, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public static JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public static JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public static JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton b_BlueHide = new JButton("Hide Blue");
JButton b_BlueShow = new JButton("Show Blue");
JButton b_RedHide = new JButton("Hide Red");
JButton b_RedShow = new JButton("Show Red");
JButton b_GreenHide = new JButton("Hide Green");
JButton b_GreenShow = new JButton("Show Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(b_BlueHide);
buttonPanel.add(b_BlueShow);
buttonPanel.add(b_GreenHide);
buttonPanel.add(b_GreenShow);
buttonPanel.add(b_RedHide);
buttonPanel.add(b_RedShow);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
}
}
static is not your friend. It has its place and purpose, but this is not one of them. Learn to live without it.
Instead, your methods and components should be instance based (that is, obviously, not static and reliant on a instance of the parent class).
The following example is slightly modified and makes use of a CardLayout to switch the panels, which is a lot more fun then trying to handle z-order issues ;)
Take a look at How to Use CardLayout
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements ActionListener {
private CardLayout cardLayout;
private JPanel contentPane;
public TestPane() {
cardLayout = new CardLayout();
setLayout(new BorderLayout());
contentPane = new JPanel(cardLayout);
contentPane.add(bluePanel(), "blue");
contentPane.add(greenPanel(), "green");
contentPane.add(redPanel(), "red");
add(contentPane);
add(buttonPanel(), BorderLayout.SOUTH);
}
public JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
// Demonstration purposes only -----//
greenPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
// Demonstration purposes only -----//
bluePanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
// Demonstration purposes only -----//
redPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton blue = new JButton("Blue");
JButton red = new JButton("Red");
JButton green = new JButton("Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(blue);
buttonPanel.add(green);
buttonPanel.add(red);
blue.addActionListener(this);
green.addActionListener(this);
red.addActionListener(this);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("blue".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "blue");
} else if ("red".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "red");
} else if ("green".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "green");
}
}
}
}
There's a lot of room for simplification and reduction of duplicate workflows, but I'll leave that for you to figure out ;)

How do i display in JTextarea or JTable

So I have created two buttons and I want to do a specific task when the buttons are clicked. If button 1 (b1) is clicked using the ActionListener, I want to create an object of Van and display the instance variables in a JTextarea or JTable. For example if Van button is clicked then the action would be to create an object of Van and get the instance variable values and print them in a JTextArea/JTable. Below is my code so far:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
public class TestButton extends JFrame{
JTable table;
public TestButton (){
setLayout(new FlowLayout());
}
static class ActionTwo implements ActionListener{
#Override
public void actionPerformed (ActionEvent evt){
Vehicle sport = new Sportcar (200, 1500, 220);
}
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent evt){
Vehicle aVan = new Van(100,0.9,3500,160.4);
}
}
public static void main (String [] args){
JFrame frame = new JFrame ("Type of Vehicle");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBackground(Color.black);
JButton b1 = new JButton("Van");
JButton b2 = new JButton("Sports Car");
panel.add(b1);
panel.add(b2);
frame.add(panel);
b1.addActionListener(new Action());
b2.addActionListener(new ActionTwo());
}
}
Have a look at the Java tutorial on Action Listeners
This will do what you would like it to do, but you should read through that tutorial to get a full grasp of what's happening.
public static void main (String [] args){
JTextField text = new JTextField();
ActionListener textSetter = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
text.setText(clicked.getText());
}
};
JButton btnVan = new JButton("Van");
btnVan.addActionListener(textSetter);
JButton btnCar = new JButton("Sports Car");
btnCar.addActionListener(textSetter);
JPanel btnPanel = new JPanel();
btnPanel.add(btnVan);
btnPanel.add(btnCar);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(text, BorderLayout.NORTH);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame ("Type of Vehicle");
frame.add(mainPanel);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

Implement copy/paste in JTextArea?

I have a very simple code that creates a frame object from the class MyJFrame accepts the first string which is used as a title. Place the second string is the text to be displayed in a JScrollPane. You can see the code below. What I need is to use copy and paste of text highlighted. I need help implementing it. So that if copy selected from a menubar it copies the highlighted portion and if paste is pastes it.
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
public class DisplayText
{
private static JTextArea text;
public DisplayText(String title, String info)
{
MyJFrame f = new MyJFrame(title);
Container c = f.getContentPane();
//default text
text = new JTextArea(info);
//Scrollpane
JScrollPane sp = new JScrollPane(text);
c.add( sp );
f.setBounds(100,200, 500, 400 );
f.setVisible(true);
}
Use the Actions that are available in the DefaultEditorKit including DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, and DefaultEditorKit.PasteAction.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.text.*;
public class TestActions {
private String[] texts = {
"Hello", "Goodbye", "What the f***?", "Heck if I know", "Peace out man!"
};
private JTextArea textArea = new JTextArea(10, 30);
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
private JPanel mainPanel = new JPanel();
private JMenuBar menubar = new JMenuBar();
private JPopupMenu popup = new JPopupMenu();
private PopupListener popupListener = new PopupListener();
public TestActions() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
btnPanel.add(new JButton(textAction));
menu.add(new JMenuItem(textAction));
popup.add(new JMenuItem(textAction));
}
menubar.add(menu);
JPanel textFieldPanel = new JPanel(new GridLayout(0, 1, 5, 5));
for (String text: texts) {
JTextField textField = new JTextField(text, 15);
textField.addMouseListener(popupListener);
textFieldPanel.add(textField);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
((JTextComponent)e.getSource()).selectAll();
}
});
}
textArea.addMouseListener(popupListener);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel textFieldPanelWrapper = new JPanel(new BorderLayout());
textFieldPanelWrapper.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(btnPanel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(textFieldPanelWrapper, BorderLayout.EAST);
}
public JComponent getMainPanel() {
return mainPanel;
}
private JMenuBar getMenuBar() {
return menubar;
}
private class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(),
e.getX(), e.getY());
}
}
}
private static void createAndShowGui() {
TestActions testActions = new TestActions();
JFrame frame = new JFrame("Test Actions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testActions.getMainPanel());
frame.setJMenuBar(testActions.getMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
code borrowed from my answer here.
Edit
You ask in comment:
I appreciate the answer. However, could you make it a bit simpler to understand, I am fairly new to Java.
Sure, here is a simple JMenuBar that holds an edit JMenu that holds JMenuItems for copy, cut, and paste with just that code borrowed from my example. Note that as an aside, you should not setBounds on anything, you should instead set the rows and columns of your JTextArea, and that you should not use a static JTextArea, and in fact no Swing components should ever be static.
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultEditorKit;
public class DisplayText {
private JTextArea text;
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
public DisplayText(String title, String info) {
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
menu.add(new JMenuItem(textAction));
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
JFrame f = new JFrame(title);
f.setJMenuBar(menuBar);
Container c = f.getContentPane();
text = new JTextArea(info, 20, 50);
JScrollPane sp = new JScrollPane(text);
c.add(sp);
// f.setBounds(100,200, 500, 400 );
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new DisplayText("Title", "This is info text");
}
}

repaint JPanel with every click at JList

everytime i click on a JList item, i need to clear + refresh my current panel & load another panel, returned via method 'populateWithButtons()'. temp is an int variable that stores what was clicked at the JList. How do i rectify the following?
list_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
//refresh + populate JPanel
Food food = new Food();
JPanel panel2 = new JPanel();
JPanel pane11 = new JPanel();
panel2.add(panel1);
panel1.validate();
panel1.repaint();
panel1.setBounds(153, 74, 281, 269);
panel1.add(food.populateWithButtons(temp));
contentPane.add(panel2);
}
don't to use NullLayout
add ListSelectionListener to JList instead of MouseListener, otherwise you would need to convert point from mouse to Item in JList
use CardLayout instead of add, remove JPanels on runtime, then selection from ListSelectionListener (ListSelectionModel to SINGLE...) to switch prepared card (JPanel with some contents)
EDIT
.
.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CardlayoutTest {
private Color[] colors = new Color[]{Color.BLACK, Color.RED, Color.GREEN, Color.BLUE};
private JFrame frame = new JFrame();
private JList list = new JList();
private JPanel panel = new JPanel();
private CardLayout card = new CardLayout();
public CardlayoutTest() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(card);
Vector<String> items = new Vector<String>();
for (int x = 0; x < colors.length; x++) {
JPanel pnl = new JPanel(new BorderLayout());
pnl.setBackground(colors[x]);
panel.add(pnl, colors[x].toString());
items.add(colors[x].toString());
}
list = new JList(items);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String card = list.getSelectedValue().toString();
CardLayout cL = (CardLayout) (panel.getLayout());
cL.show(panel, card);
}
}
});
frame.add(new JScrollPane(list), BorderLayout.WEST);
frame.add(panel);
frame.setPreferredSize(new Dimension(400, 150));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CardlayoutTest();
}
});
}
}
move validate() and repaint() after adding to contentPane as in that point it will be redrawed.

Opening a new JFrame from a Button

I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.
Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}
see my last line
{
ActList.setVisible(true);
}

Categories