I am new to Java and am trying to get two buttons to change a textfield and a label. I think the problem is that l in the ClearButton class and tf in the CopyButton class cannot be referenced. How do I do that?
public class SwingEx1
{
JFrame f;
JPanel p;
JLabel l;
JTextField tf;
JButton b1,b2;
public SwingEx1()
{
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
tf = new JTextField("Enter Text");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void LaunchFrame()
{
p.add(b1,BorderLayout.SOUTH);
p.add(b2,BorderLayout.SOUTH);
p.add(l,BorderLayout.CENTER);
p.add(tf,BorderLayout.CENTER);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
SwingEx1 swObj1 = new SwingEx1();
swObj1.LaunchFrame();
}
}
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
tf.setText("");
}
}
class CopyButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
l.setText(tf.getText());
}
}
It's a scope issue. You've declared tf inside your SwingEx1 class, so outside classes don't know it exists! I would move your button classes inside the SwingEx1 class, that should make them able to resolve the variable names. class structure would look like this:
class SwingEx1
{
...
class ClearButton implements ActionListener
{
...
}
class CopyButton implements ActionListener
{
...
}
}
Is there any reason you can't simply have the class implement ActionListener. That way you wouldn't have to worry about the scoping issues. You should also give your variables meaningful names like btnClear, btnCopy.
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 SwingEx1 implements ActionListener {
JFrame f;
JPanel p;
JLabel l;
JTextField tf;
JButton b1, b2;
public SwingEx1() {
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
tf = new JTextField("Enter Text");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void LaunchFrame() {
p.add(b1, BorderLayout.SOUTH);
p.add(b2, BorderLayout.SOUTH);
p.add(l, BorderLayout.CENTER);
p.add(tf, BorderLayout.CENTER);
f.getContentPane().add(p);
b1.addActionListener(this);
b2.addActionListener(this);
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
SwingEx1 swObj1 = new SwingEx1();
swObj1.LaunchFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
tf.setText("");
} else if (e.getSource() == b2) {
l.setText(tf.getText());
}
}
}
Related
Basically, I'm trying to get the JButton in Frame1 to edit the JLabel in Frame2. I know it can work if I set the JLabel and getLabel() method in Frame2 to static, and have the ActionListener reference Frame1 directly, but I want to know if there's a way to do it without using static variables or methods.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
}
class Frame1 extends JFrame {
JButton button;
public Frame1(JFrame f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
button = new JButton("Button");
add(button);
button.addActionListener(new Listener(f.getLabel()));
}
}
class Frame2 extends JFrame {
JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("hello");
add(label);
}
public JLabel getLabel() {
return label;
}
}
class Listener implements ActionListener {
private JLabel lab;
public Listener(JLabel lab) {
this.lab = lab;
}
public void actionPerformed(ActionEvent e) {
lab.setText("nice");
}
}
Any suggestions? Thanks!
EDIT: Here's a compilable version of the code -- label and getLabel() are static, and the ActionListener references JFrame1 directly when it's called. My goal is to have no static variables or methods (outside of main).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
}
class Frame1 extends JFrame {
JButton button;
public Frame1(JFrame f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
button = new JButton("Button");
add(button);
button.addActionListener(new Listener(Frame2.getLabel()));
}
}
class Frame2 extends JFrame {
static JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("hello");
add(label);
}
public static JLabel getLabel() {
return label;
}
}
class Listener implements ActionListener {
private JLabel lab;
public Listener(JLabel lab) {
this.lab = lab;
}
public void actionPerformed(ActionEvent e) {
lab.setText("nice");
}
}
Oracle has a really nifty Swing tutorial. I think your studying the tutorial would be a really good idea.
I had to make a bunch of changes to your code to get it to execute.
The main change I made was to keep the reference to the JLabel in the Frame2 class. I passed an instance of Frame2 to the Listener class. Just like I did yesterday with your previous question.
Here's the code. Take the time to study what I did before you ask another question tomorrow.
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.SwingUtilities;
public class DoubleJFrameTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
});
}
}
class Frame1 extends JFrame {
private static final long serialVersionUID = 1L;
private JButton button;
public Frame1(Frame2 f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
button = new JButton("Button");
button.addActionListener(new Listener(f));
panel.add(button, BorderLayout.CENTER);
add(panel);
}
}
class Frame2 extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
label = new JLabel("hello");
panel.add(label, BorderLayout.CENTER);
add(panel);
}
public void setLabelText(String text) {
label.setText(text);;
}
}
class Listener implements ActionListener {
private Frame2 frame;
public Listener(Frame2 frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent e) {
frame.setLabelText("nice");
}
}
I am new to Java and trying to create a simple Swing program with two buttons, but I'm getting an error with addActionListener.
public class swingEx1
{
JFrame f;
JPanel p;
JLabel l;
JButton b1,b2;
public swingEx1()
{
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void launchFrame()
{
p.add(b1,BorderLayout.SOUTH);
p.add(b2,BorderLayout.EAST);
p.add(l,BorderLayout.NORTH);
p.setSize(200,300);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
swingEx1 swObj1 = new swingEx1();
swObj1.launchFrame();
}
}
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b1 = (Button) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b2 = (Button) e.getSource();
b2.setLabel("It it Copy Button");
}
}
Line b1.addActionListener(new ClearButton()) produces error:
The method addActionListener(ActionListener) in the type
AbstractButton is not applicable for the arguments (ClearButton)
Line b2.addActionListener(new CopyButton()) produces error:
The method addActionListener(ActionListener) in the type
AbstractButton is not applicable for the arguments (CopyButton)
In your two inner classes you should be using JButton and you are using Button. This is probably why you are getting your exception. I ran your code with the recommended changes and I got no error.
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;
public class swingEx1 {
JFrame f;
JPanel p;
JLabel l;
JButton b1, b2;
public swingEx1() {
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void launchFrame() {
p.add(b1, BorderLayout.SOUTH);
p.add(b2, BorderLayout.EAST);
p.add(l, BorderLayout.NORTH);
p.setSize(200, 300);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
swingEx1 swObj1 = new swingEx1();
swObj1.launchFrame();
}
}
class ClearButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b1 = (JButton) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b2 = (JButton) e.getSource();
b2.setLabel("It it Copy Button");
}
}
I adjusted your ActionListener class (which is a separate defaulted-access class in your code) to an inner class and changed Button to JButton. It works.
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton b1 = (JButton) e.getSource();
b1.setLabel("It it Clear Button");
}
}
The GUI appears as follows:
1. Before clicking:
Panel before clicking
2.After clicking:
panel after clicking
I changed my imports from:
import javax.swing.*;
import java.awt.*;
to:
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;
This fixed the problem. Not sure why the original imports didn't work.
I'm starting my adventure with programming and I've got one problem. I try make a simple calculator using awt. I can't go further because I don't know, how to change one variable - textField initialized in MainFrame. I want to change it in actionPerformed. Here's my code and I'll be grateful if You'll give me some guidance. Thanks!
package starter;
import java.awt.EventQueue;
public class Starter {
public Starter () {
EventQueue.invokeLater(new Runnable (){
#Override
public void run () {
new MainFrame();
System.out.println();
}
});
}
public static void main(String[] args) {
new Starter();
}
}
MainFrame
package starter;
import java.awt.BorderLayout;
import java.awt.GridLayout;
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 MainFrame extends JFrame {
private JTextField textField = new JTextField();
DigitActionListener digitPressed = new DigitActionListener();
public MainFrame() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(true);
setSize(350, 400);
setLayout (new GridLayout (6, 4, 3, 3));
JButton buttonClear = new JButton("Clear"); buttonClear.addActionListener(digitPressed);
JButton button0 = new JButton ("0"); button0.addActionListener(digitPressed);
JButton button1 = new JButton ("1"); button1.addActionListener(digitPressed);
JButton button2 = new JButton ("2"); button2.addActionListener(digitPressed);
JButton button3 = new JButton ("3"); button3.addActionListener(digitPressed);
JButton button4 = new JButton ("4"); button4.addActionListener(digitPressed);
JButton button5 = new JButton ("5"); button5.addActionListener(digitPressed);
JButton button6 = new JButton ("6"); button6.addActionListener(digitPressed);
JButton button7 = new JButton ("7"); button7.addActionListener(digitPressed);
JButton button8 = new JButton ("8"); button8.addActionListener(digitPressed);
JButton button9 = new JButton ("9"); button9.addActionListener(digitPressed);
JButton multiplicationButton = new JButton ("*"); multiplicationButton.addActionListener(digitPressed);
JButton divisionButton = new JButton ("/"); divisionButton.addActionListener(digitPressed);
JButton additionButton = new JButton ("+"); additionButton.addActionListener(digitPressed);
JButton substructionButton = new JButton ("-"); substructionButton.addActionListener(digitPressed);
JButton equalsButton = new JButton ("="); equalsButton.addActionListener(digitPressed);
JButton commaButton = new JButton ("."); commaButton.addActionListener(digitPressed);
add (buttonClear);
add (new JLabel (""));
add (new JLabel (""));
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
textPanel.add(textField, BorderLayout.CENTER);
this.add(textPanel);
add(button7);
add(button8);
add(button9);
add(divisionButton);
add(button4);
add(button5);
add(button6);
add(multiplicationButton);
add(button1);
add(button2);
add(button3);
add(additionButton);
add(commaButton);
add(button0);
add(equalsButton);
add(substructionButton);
}
public JTextField getTextField() {
return textField;
}
public void setTextField(String text) {
textField.setText(text);
}
}
DigitActionListener
package starter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DigitActionListener implements ActionListener {
int size = 0;
char[] tab = new char[size];
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
}
}
Your problem is here:
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
You're creating a new MainFrame object and changing its state, but understand that this will have no effect on the completely distinct displayed MainFrame object and will not change its state whatsoever (will not change what is displayed within its JTextField). There are a variety of possible solutions, but it all boils down to understanding what Java references are, and calling methods on the appropriate reference, here the appropriate MainFrame object. A simple solution could be for to pass the MainFrame object into your listener via a listener constructor, and then call the methods on this reference.
For example:
class DigitActionListener implements ActionListener {
private MainFrame mainFrame;
int size = 0;
char[] tab = new char[size];
public DigitActionListener(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
// MainFrame mainFrame = new MainFrame(); // **** no, don't do this
mainFrame.setTextField(eq);
size++;
}
}
}
and then within MainFrame itself, do something like:
// pass *this* or the current MainFrame instance, into the DigitalActionListener
DigitActionListener digitPressed = new DigitActionListener(this);
Other issues -- learn to use and then use arrays and ArrayLists, as this can help you simplify your code, and thus make program improvement and debugging much easier.
My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}
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.