Having Trouble to use jbutton to open a new window - java

i modified my code but still faced problem ,i want to MyPanel2 inside open to MyPanel by clicking button , how do i do that , here is my code given which is pop open after clicking button of Myplanel..
import java.awt.CardLayout;
import java.awt.Dimension;
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.SwingUtilities;
import javax.swing.UIManager;
import org.jpedal.PdfDecoder;
import org.jpedal.examples.viewer.Viewer;
import org.jpedal.gui.GUIFactory;
import org.jpedal.utils.LogWriter;
public class Button extends Viewer {
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Button().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
jcomp4 = new JButton("openNewWindow");
// adjust size and set layout
setPreferredSize(new Dimension(315, 85));
setLayout(null);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
a.setupViewer();
}
});
add(jcomp4);
}
}
class MyPanel2 extends Viewer {
public MyPanel2() {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
}
public MyPanel2(int modeOfOperation) {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
commonValues.setModeOfOperation(modeOfOperation);
}
}

private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
// we need to increase the size of the panel so when we switch views we can see the viewer
frame.setPreferredSize(new Dimension(2000, 700));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
Now in the button event handler
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
// inform the viewer of where it is to be displayed
a.setRootContainer(contentPane);
// hide the curently visible panel
MyPanel.this.setVisible(false);
// show the viewer
a.setupViewer();
}
});

Related

Is it possible to make a toggleable button that changes text when clicked

I have made a JFrame that shows a start button, and changes to stop when clicked. How to make it so that it changes its text to start when stop is clicked. Here is the source code:
public class FRMCountdown extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FRMCountdown frame = new FRMCountdown();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FRMCountdown() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton Start_Stop_btn = new JButton("Start");
Start_Stop_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Start_Stop_btn.setText("Stop");
}
});
Start_Stop_btn.setBounds(10, 188, 89, 23);
contentPane.add(Start_Stop_btn);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Swing was designed to be used with layout managers. I used a FlowLayout to place one JButton. Null layouts and absolute positioning lead to problems.
Java field names start with a lower case letter, Java method names start with a lower case letter. Java class names start with an upper case letter.
Here's the modified code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
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;
public class ToggleJButton {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new ToggleJButton();
}
});
}
public ToggleJButton() {
JFrame frame = new JFrame("Toggle JButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 100, 5, 100));
JButton startStopButton = new JButton("Start");
startStopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
if (text.contentEquals("Start")) {
text = "Stop";
} else {
text = "Start";
}
button.setText(text);
}
});
panel.add(startStopButton);
return panel;
}
}

How do I create a JButton solely on one pane that prints "Hello

Every time I try to do this, it gives me an error that "Change Listener cannot be converted to Action Listener" and even if I implement ActionListener to the class... it still gives me another error
Is there a way to create a JButton only on the pane "Encryption" that when pressed prints "Hello"
This is my code:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SwingDemo extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Encryption/Decryption Software");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
tabbedPane.addTab("Encryption", panel1);
tabbedPane.addTab("Decryption ", panel2);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(200,170, 500,250);
frame.setVisible(true);
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(tabbedPane.getSelectedIndex() == 0){
panel1.removeAll();
panel1.setLayout(null);
JLabel initial_text = new JLabel("Enter text to be encrypted:");
JLabel final_text = new JLabel("Final text:");
JLabel key = new JLabel("Key:");
JTextField text_field = new JTextField(100);
JTextField key_field = new JTextField(100);
panel1.add(initial_text);
panel1.add(final_text);
panel1.add(key);
panel1.add(text_field);
panel1.add(key_field);
initial_text.setBounds(10, 20, 300, 50);
final_text.setBounds(10, 150, 600, 50);
key.setBounds(10, 58, 300, 50);
text_field.setBounds(178, 30, 230, 30);
key_field.setBounds(38, 72, 36, 25);
}
}
});
}
}
to detect a click you need to add an MouseListener no a ChangeListener
Like this
import java.awt.Color;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class SwingDemo extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Encryption/Decryption Software");
JFrame frame = new JFrame("Encryption/Decryption Software");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
tabbedPane.addTab("Encryption", panel1);
tabbedPane.addTab("Decryption ", panel2);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(200, 170, 500, 250);
frame.setVisible(true);
tabbedPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Hello");
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
}

Replace ImageIcon with JButton pressed

I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.

How to open a new JPanel with a JButton?

I am trying to code a program with multiple screens, however, I do not want to use tabbed panes. I have looked at using multiple JPanels with the card layout and the methods are simply not working. What I need to be able to do is load the new JPanel when a button is clicked. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IA extends JFrame {
private JPanel contentPane;
private JPanel home;
private JPanel clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
The problem is that you have duplicate variables home and clients .
The folllowing is your modified code to fix that, with comments on the changed lines (five lines total) :
import java.awt.CardLayout;
import java.awt.EventQueue;
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.border.EmptyBorder;
public class IA extends JFrame {
private final JPanel contentPane;
// private final JPanel home; // REMOVED
// private JPanel clients; // REMOVED
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
final JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
final JPanel clients = new JPanel(); // MOVED UP
contentPane.add(clients, "name_714431450350356"); // MOVED UP
clients.setLayout(null); // MOVED UP
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
I would take a look at this post, however I have a feeling you'll need to use a actionlistener to get this done...
Java Swing. Opening a new JPanel from a JButton and making the buttons pretty
I would of left this as a comment but apparently you need 50 rep for that...
This link might be more helpful.. How to open a new window by clicking a button
When the following code is invoked the clients variable equals to null.
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
Write this:
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
before you add the Action Listener

How to pass value JList item from JFrame into another JFrame (just value)?

I have write a test with two class.
The first JPanel, Gestion: JFrame with jlist + button (the button open the Jlist 2, PanelTest)
The second JPanel, PanelTest: JFrame and I want to recover in String, the select value item in the JFrame Gestion (JList)
How to do that ?
Gestion.java:
package IHM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JList;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
public class Gestion extends JFrame {
private DocumentListener myListener;
public String test;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public String getTest() {
return test;
}
/**
* Create the frame.
* #throws Exception
*/
public Gestion() throws Exception {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
final PanelTest panel2 = new PanelTest();
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
String choix[] = {" Pierre", " Paul", " Jacques", " Lou", " Marie"};
final JList list = new JList(choix);
panel.add(list);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
test = (String) list.getSelectedValue();
System.out.println(test);
// PanelTest.setValue(test);
}
});
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PanelTest().setVisible(true);
fermerFenetre();
}
});
panel_1.add(btnNewButton);
}
public void fermerFenetre(){
this.setVisible(false);
}
}
PanelTest.java
package IHM;
import java.awt.BorderLayout;
public class PanelTest extends JFrame {
public String tyty;
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PanelTest frame = new PanelTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PanelTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textField = new JTextField();
contentPane.add(textField, BorderLayout.WEST);
textField.setColumns(10);
}
}
Suggestions:
Make your list variable a field, not a local variable, or else make it a final local variable so that it is accessible inside of the anonymous ActionListener.
Obtain the selected list item in your ActionListener where you launch the 2nd window.
Pass that String into your PanelTest object via a String parameter.
The second window should be a dialog such as a JDialog, not a JFrame.
As an aside, you'll rarely want to have your GUI classes extend top level windows such as JFrames or JDialogs as that greatly limits the flexibility of your GUI code.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Gestion2 extends JPanel {
private static final String CHOIX[] = { " Pierre", " Paul", " Jacques",
" Lou", " Marie" };
private JList<String> choixList = new JList<>(CHOIX);
public Gestion2() {
JPanel listPanel = new JPanel();
listPanel.add(new JScrollPane(choixList));
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new ListSelectAction("Select Item and Press")));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(listPanel);
add(btnPanel);
}
private class ListSelectAction extends AbstractAction {
public ListSelectAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = choixList.getSelectedValue();
if (selectedItem != null) {
PanelTest2 panelTest2 = new PanelTest2(selectedItem);
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
// JOptionPane example
JOptionPane.showMessageDialog(win, panelTest2,
"JOptionPane Example", JOptionPane.PLAIN_MESSAGE);
// or JDialog example
JDialog dialog = new JDialog(win, "JDialog Example",
ModalityType.APPLICATION_MODAL);
dialog.add(panelTest2);
dialog.pack();
dialog.setLocationRelativeTo(win);
dialog.setVisible(true);
}
}
}
private static void createAndShowGui() {
Gestion2 mainPanel = new Gestion2();
JFrame frame = new JFrame("Gestion2");
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();
}
});
}
}
#SuppressWarnings("serial")
class PanelTest2 extends JPanel {
private String selectedItem;
private JTextField textField = new JTextField(10);
public PanelTest2(String selectedItem) {
this.selectedItem = selectedItem;
textField.setText(selectedItem);
add(new JLabel("Selected Item:"));
add(textField);
}
public String getSelectedItem() {
return selectedItem;
}
}

Categories