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.
Related
I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.
I am trying to create a method which opens up a JFrame with some text and 4 JButtons. I need it to operate just like the methods in the JOptionPane class so that i can do things like
int i = JOptionPane.showConfirmDialog(...);
I want to be able to call the method and wait for one of the buttons to be clicked before returning a value.
This is what I have tried so far but obviously there are a couple of errors. Anybody know what i need to do to make this work and how to get around the errors. Here is the methood
private static String displaySetStatus(String text){
JButton jbtWin = new JButton("Win");
JButton jbtLose = new JButton("Lose");
JButton jbtCancelBet = new JButton("Cancel Bet");
JButton jbtSkip = new JButton("Skip");
JFrame f = new JFrame("Set Status");
f.add(new JLabel(text));
JPanel jpSouth = new JPanel();
jpSouth.add(jbtWin);
jpSouth.add(jbtLose);
jpSouth.add(jbtCancelBet);
jpSouth.add(jbtSkip);
f.add(jpSouth, "South");
f.setSize(200, 150);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
String status = "Empty";
ActionListener buttonListener = new SetStatusListener();
jbtWin.addActionListener(buttonListener);
jbtLose.addActionListener(buttonListener);
jbtCancelBet.addActionListener(buttonListener);
jbtSkip.addActionListener(buttonListener);
class SetStatusListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
status = ((JButton)e.getSource()).getText();
}
}
while(status.equals("Empty")){
//do nothing - wait until button is clicked
}
f.setVisible(false);
return status;
}
If you want JOptionPane functionality, which is in fact that of a modal dialog window, why not use a JOptionPane for this? Or if that won't work, use a modal JDialog window and not a JFrame. Your while (true) block is going to totally mess up your program, and modality is what you in fact want.
For example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Foo1 extends JPanel {
private JTextField textField = new JTextField(10);
private JButton getStatusBtn = new JButton(new GetStatusAction("Get Status"));
public Foo1() {
textField.setFocusable(false);
add(new JLabel("Status:"));
add(textField);
add(getStatusBtn);
}
private class GetStatusAction extends AbstractAction {
public GetStatusAction(String name) {
super(name);
int mnemonic = name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component parentComponent = Foo1.this;
// this panel can hold any gui components that you desire
// here I simply give it a centered JLabel that displays some text
JPanel message = new JPanel(new GridBagLayout());
message.setPreferredSize(new Dimension(200, 100));
message.add(new JLabel("Some Text"));
String title = "Get Status";
int optionType = JOptionPane.OK_CANCEL_OPTION;
int messageType = JOptionPane.PLAIN_MESSAGE;
Icon icon = null;
String[] options = { "Win", "Lose" };
int initialValue = 0;
// create and show our JOptionPane, and get the information from it
int selection = JOptionPane.showOptionDialog(parentComponent,
message, title, optionType, messageType, icon, options,
initialValue);
// if the selection chosen was valid (win or lose pushed)
if (selection >= 0) {
// get the selection and use it
textField.setText(options[selection]);
}
}
}
private static void createAndShowGui() {
Foo1 mainPanel = new Foo1();
JFrame frame = new JFrame("Foo1");
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 have two frames with contents . The first one has a jlabel and jbutton which when it is clicked it will open a new frame. I need to repaint the first frame or the panel that has the label by adding another jlabel to it when the second frame is closed.
//Edited
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FirstFrame extends JPanel implements KeyListener{
private static String command[];
private static JButton ok;
private static int count = 1;
private static JTextField text;
private static JLabel labels[];
private static JPanel p ;
private static JFrame frame;
public int getCount(){
return count;
}
public static void createWindow(){
JFrame createFrame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2,1));
text = new JTextField (30);
ok = new JButton ("Add");
ok.requestFocusInWindow();
ok.setFocusable(true);
panel.add(text);
panel.add(ok);
text.setFocusable(true);
text.addKeyListener(new FirstFrame());
createFrame.add(panel);
createFrame.setVisible(true);
createFrame.setSize(600,300);
createFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
createFrame.setLocationRelativeTo(null);
createFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.out.println(command[count]);
if(command[count] != null){
p.add(new JLabel("NEW LABEL"));
p.revalidate();
p.repaint();
count++;
System.out.println(count);
}
}
});
if(count >= command.length)
count = 1;
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(command[count] == null)
command[count] = text.getText();
else
command[count] = command[count]+", "+text.getText();
text.setText("");
}
});
}
public FirstFrame(){
p = new JPanel();
JButton create = new JButton ("CREATE");
command = new String[2];
labels = new JLabel[2];
addKeyListener(this);
create.setPreferredSize(new Dimension(200,100));
//setLayout(new BorderLayout());
p.add(new JLabel("dsafsaf"));
p.add(create);
add(p);
//JPanel mainPanel = new JPanel();
/*mainPanel.setFocusable(false);
mainPanel.add(create);
*/
create.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
createWindow();
}
});
//add(mainPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
frame = new JFrame();
frame.add(new FirstFrame());
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
if(ok.isDisplayable()){
ok.doClick();
return;}
}
}
}
});
}
}
As per my first comment, you're better off using a dialog of some type, and likely something as simple as a JOptionPane. For instance in the code below, I create a new JLabel with the text in a JTextField that's held by a JOptionPane, and then add it to the original GUI:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class FirstPanel2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private JTextField textField = new JTextField("Hovercraft rules!", 30);
private int count = 0;
public FirstPanel2() {
AddAction addAction = new AddAction();
textField.setAction(addAction);
add(textField);
add(new JButton(addAction));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class AddAction extends AbstractAction {
public AddAction() {
super("Add");
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
final JTextField someField = new JTextField(text, 10);
JPanel panel = new JPanel();
panel.add(someField);
int result = JOptionPane.showConfirmDialog(FirstPanel2.this, panel, "Add Label",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
JLabel label = new JLabel(someField.getText());
FirstPanel2.this.add(label);
FirstPanel2.this.revalidate();
FirstPanel2.this.repaint();
}
}
}
private static void createAndShowGui() {
FirstPanel2 mainPanel = new FirstPanel2();
JFrame frame = new JFrame("My Gui");
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();
}
});
}
}
Also, don't add KeyListeners to text components as that is a dangerous and unnecessary thing to do. Here you're much better off adding an ActionListener, or as in my code above, an Action, so that it will perform an action when the enter key is pressed.
Edit
You ask:
Just realized it is because of the KeyListener. Can you explain please the addAction ?
This is functionally similar to adding an ActionListener to a JTextField, so that when you press enter the actionPerformed(...) method will be called, exactly the same as if you pressed a JButton and activated its ActionListener or Action. An Action is like an "ActionListener" on steroids. It not only behaves as an ActionListener, but it can also give the button its text, its icon and other properties.
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();
}
});
I'm learning Swing class now and everything about it. I've got this toy program I've been putting together that prompts for a name and then presents a JOptionPane with the message "You've entered (Your Name)".
The submit button I use can only be clicked on, but I'd like to get it to work with the Enter button too. I've tried adding a KeyListener, as is recommended in the Java book I'm using (Eventful Java, Bruce Danyluk and Murtagh).
This is my code:
import java.awt.BorderLayout;
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.JTextField;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
submit.addKeyListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the actionListener, keyListener class:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener, KeyListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
}
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
You can use the top level containers root pane to set a default button, which will allow it to respond to the enter.
SwingUtilities.getRootPane(submitButton).setDefaultButton(submitButton);
This, of course, assumes you've added the button to a valid container ;)
UPDATED
This is a basic example using the JRootPane#setDefaultButton and key bindings API
public class DefaultButton {
public static void main(String[] args) {
new DefaultButton();
}
public DefaultButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton button;
private JLabel label;
private int count;
public TestPane() {
label = new JLabel("Press the button");
button = new JButton("Press me");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
gbc.gridy++;
add(new JButton("No Action Here"), gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
InputMap im = button.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = button.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
am.put("spaced", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(button).setDefaultButton(button);
}
protected void doButtonPressed(ActionEvent evt) {
count++;
label.setText("Pressed " + count + " times");
}
}
}
This of course, assumes that the component with focus does not consume the key event in question (like the second button consuming the space or enter keys
In the ActionListener Class you can simply add
public void actionPerformed(ActionEvent event) {
if (event.getSource()==textField){
textButton.doClick();
}
else if (event.getSource()==textButton) {
//do something
}
}
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Without a frame this works for me:
JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
null, tf, "Enter your message",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,0);
message = tf.getText();
I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key
textField_in = new JTextField();
textField_in.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getExtendedKeyCode());
if (arg0.getKeyCode()==10) {
String name = textField_in.getText();
textField_out.setText(name);
}
}
});
textField_in.setBounds(173, 40, 86, 20);
frame.getContentPane().add(textField_in);
textField_in.setColumns(10);