Manage JFrame Instances - java

In my project I've one instance of jframe1 and two instance of jframe2. Then I want to update from jframe1 txt2 component of first instance of jframe2. But when I invoke perfomaction() method it was to update the second instance of jframe2.
public class Jframe1 extends Jframe {
public jframe1() {
Performedaction() {
jframe2.txt2.setText("do it");
}
}
public class jframe2 extends Jframe {
public static JtextFiedl txt2;
public jframe2() {
}

Here is an example.. The example uses two JFrame window's and on clicking a button in one jframe, the second one's JLabel is updated. The example uses a JLabel instead of JTextField.
The mechanism uses java.util.Observer interface and Observable class to update from one window to the other one.
The example's code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TwoFramesExample {
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TwoFramesExample().start();
}
});
}
private void start() {
Frame1 f1 = new Frame1();
new Frame2(f1);
}
}
class Frame1 implements Observer {
private JLabel label;
#Override // Observer interface's implemented method
public void update(Observable o, Object data) {
label.setText((String) data); // displays new text in JLabel
}
Frame1() {
JFrame f1 = new JFrame("Frame-1");
f1.getRootPane().setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
label = new JLabel("Click button in frame-2...");
label.setFont(new Font("Dialog", Font.PLAIN, 20));
f1.add(label);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(350, 150);
f1.setLocation(200, 200);
f1.setVisible(true);
}
}
class Frame2 {
private int clicks;
Frame2(Frame1 f1) {
// Create Observable and add Observer
final MessageObservable observable = new MessageObservable();
observable.addObserver(f1);
// Display frame
JFrame f2 = new JFrame("Frame-2");
JButton button = new JButton("Press me");
button.setFont(new Font("Dialog", Font.PLAIN, 20));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "button clicks in frame-2: [" + ++clicks + "]";
observable.changeData(data);
}
});
f2.add(button);
f2.setSize(250, 150);
f2.setLocation(600, 200);
f2.setVisible(true);
}
}
class MessageObservable extends Observable {
MessageObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}

Related

Receiving a string in Java graphics from a text box

I started to make a graphic for program I built in which to insert a name and length of a song, how do I do it in graphics? I found out how to pick up a button but I do not understand how to absorb something inserted into a text box
import java.awt.*;
import java.awt.event.*;
public class Active extends Frame {
public void init() {
ActionListener al = new MyActionListener();
TextField tf = new TextField(20);
Button b;
setLayout(new FlowLayout());
setSize(1000, 1000);
b = new Button ("first");
b.setActionCommand("First");
b.addActionListener(al);
add(b);
b = new Button ("Second");
b.setActionCommand("Second");
b.addActionListener(al);
add(b);
setVisible(true);
add(tf);
}
public Active(String caption) {
super(caption);
init();
}
public static void main(String[] args) {
Active m = new Active("Active buttons");
}
}
the main:
import java.awt.*;
import java.awt.event.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("First")) {
System.out.println("The first button was switched");
}
if(s.equals("Second")) {
System.out.println("The second button was switched");
}
}
}
I would write it with the Swing GUI Toolkit. Here is a short example of that:
public class MyPanel extends JPanel
{
private JTextField songNameField;
private JTextField songLengthField;
private JButton assignBtn;
public MyPanel()
{
this.songNameField = new JTextField();
this.songLengthField = new JTextField();
this.assignBtn = new JButton("Assign");
this.assignBtn.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent event)
{
String name = songNameField.getText();
int length = Integer.parseInt(parsesongLengthField.getText());
...
}
});
this.add(songNameField);
this.add(songLengthField);
this.add(assignBtn);
}
}

Java NetBeans call ActionListener with another

I am learning Java with GUI using JFrame, I would like to seek help regarding on how to call an ActionListener using an ActionListener. Here is some of my codes. The bottom part has the two action listeners and I added a simple comment for easy understanding.
package onlinedelivery;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu extends JFrame {
public JButton mainMenuButton;
public JButton exitButton;
public MainMenuButtonHandler mmHandler;
public ExitButtonHandler exHandler;
public static final int width = 400;
public static final int heigth = 300;
public MainMenu() {
Font bigFont = new Font("Arial",Font.BOLD,12);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mainMenuButton.addActionListener(mmHandler);
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
setTitle("Main Menu");
Container pane = getContentPane();
pane.setLayout(new GridLayout(5,2));
pane.add(mainMenuButton);
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class MainMenuButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
// ExitButtonHandler should be called here
// When I click Main Menu Button Handler, ExitButtonHandler shall perform
}
}
public class ExitButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
If both Actions logic is the same you can define just one and use it for both menu and button.
If not you can extend one action from another
public class MainMenuButtonHandler extends ExitButtonHandler {
#Override public void actionPerformed(ActionEvent e) {
// An additional logic here
super.actionPerformed(e);
}
}
You can use the doClick() method in JButton (inherited from AbstractButton)
With that alter the Handler Class of MainMenuButton like this:
public class MainMenuButtonHandler implements ActionListener {
private JButton exitButton;
public void setExitButton(JButton exitButton){
this.exitButton = exitButton;
}
#Override public void actionPerformed(ActionEvent e) {
//Do your work and invoke Click of exitButton
this.exitButton.doClick();
}
}
Also the MainMenu():
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mmHandler.setExitButton(exitButton) // newly added
mainMenuButton.addActionListener(mmHandler);

Cant draw string on jframe

I want to create a window(JFrame) and draw a string on it.However, when i run my code the window appears but without the string i want to draw on it. I have made two classes LabelFrame and WebStalker.
Here is my code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.net.*;
public class LabelFrame extends JFrame {
private final JTextField urlString;
private final JButton backButton;
private final JButton loadButton;
private Stack urlStack = new Stack();
String content;
class GraphicPane extends JComponent {
public GraphicPane() {
super();
}
#Override
public void paint(Graphics g) {
g.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 14));
g.drawString("Hello, World!", 30, 20);
}
}
public LabelFrame() {
setTitle("WebStalker");
setSize(600, 600);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setLayout(new FlowLayout());
urlString = new JTextField(30);
backButton = new JButton("Load");
loadButton = new JButton("Back");
GraphicPane gp = new GraphicPane();
this.add(new JLabel("URL"));
this.add(urlString);
this.add(loadButton);
this.add(backButton);
this.add(gp);
TextFieldHandler tHandler = new TextFieldHandler();
ButtonHandler bHandler = new ButtonHandler();
urlString.addActionListener(tHandler);
backButton.addActionListener(bHandler);
loadButton.addActionListener(bHandler);
}
private class TextFieldHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
content = URLReaderFinal.Reading(event.getActionCommand());
}
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == loadButton) {
try {
//remember url for back button
urlStack.push(urlString.getText());
content = URLReaderFinal.Reading(urlString.getText());
} catch (Exception e) {
System.out.println("Unable to load page");
}
} else if (event.getSource() == backButton) {
if (urlStack.size() <= 1) {
return;
}
try {
urlStack.pop();
String urlString = (String)urlStack.peek();
} catch (Exception e) {
System.out.println("Unable to load page");
}
}
}
}
}
And the other class :
import java.awt.*;
import javax.swing.*;
public class WebStalker extends JFrame {
public static void main(String[] args) {
LabelFrame frame = new LabelFrame();
frame.setVisible(true);
}
}
You panel is using a FlowLayout. A FlowLayout respects the preferred size of a component. The preferred size of your custom component is (0, 0) so there is nothing to paint.
Override the getPreferredSize() method to return a proper size for your component.
Also, custom painting is done by overriding the paintComponent() method.
Since you are extending JComponent you should also do a fillRect(...) on the entire size of the component to make sure the background is cleared. It would be easier to extend JPanel, then you can just invoke super.paintComponent() at the start to clear the background.
Read the section from the Swing tutorial on Custom Painting for working example and more information on both of these suggestions.

Everything works, except for buttons. GUI Java

Okay I can get text fields and normal text and even images to show but I can not get a button to show. I am not sure what I am doing wrong because I have done the same steps for the rest. Any help would be great thanks!
package EventHandling2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import EventHandling.GUITest;
public class EventMain extends JFrame{
private JLabel label;
private JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(600, 300);
gui.setVisible(true);
gui.setTitle("Button Test");
}
public void EventMain(){
setLayout(new FlowLayout());
button = new JButton ("click for text");
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
The problem is with the method: void EventMain()
Constructor has NO return type. Just remove "void". The code will work just fine.
Your actionListener(e) contains a minor control structure error:
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
Change to:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Now you can see words");
}
}
First off, you have to remove void keyword in EventMain's constructor. Then, creating JPanel and add components into it, then add the JPanel to the JFrame.contentPane.
The following code should work:
public class EventMain extends JFrame {
private final JLabel label;
private final JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
// close program
gui.setSize(600, 300);
gui.setTitle("Button Test");
gui.setVisible(true);
}
public EventMain() {
// setLayout(new FlowLayout());
JPanel panel = new JPanel(new FlowLayout());
button = new JButton("click for text");
panel.add(button);
label = new JLabel("");
panel.add(label);
Events e = new Events();
button.addActionListener(e);
this.getContentPane().add(panel);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}

Java: Not able to print on TextArea from other class

I have one frame in which one TestArea is there. When I append some string from this class then String is appended but when I want to append String from other class then String is not appended. I created one method to append string in TextArea, when I call this method in this class then string is appended on text Area. But when I call this method from other Class then String is not appended on TextArea.
Code (MainClass):
public class MainClass {
private JFrame frame;
private TextArea textArea;
private Font font;
private JButton button1;
private JButton button2;
private SecondClass secondClass;
public MainClass() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("XXX");
frame.setBounds(200, 200, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
button1 = new JButton("Button1");
font = new Font("Arial", Font.BOLD, 13);
button1.setFont(font);
button1.setBounds(4, 4, 289, 30);
button2 = new JButton("Button2");
button2.setFont(font);
button2.setBounds(300, 4, 289, 30);
font = null;
textArea = new TextArea();
textArea.setBounds(4, 38, 585, 322);
textArea.setEnabled(true);
font = new Font("Arial", Font.PLAIN, 13);
textArea.setFont(font);
frame.add(button1);
frame.add(button2);
frame.add(textArea);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
textArea.append("*** I am in actionPerformed() ***\n");
appendToTextArea("Call from actionPerformed() method\n");
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass();
secondClass.printOnTextArea();
}
});
} catch (Exception e) {
textArea.append(e.toString());
}
}
public void appendToTextArea(String str) {
System.out.println(str+"\n");
textArea.append(str+"\n"); //this line not work when I call this method from other class
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainClass window = new MainClass();
window.frame.setVisible(true);
}
});
}
}
Code(SecondClass):
import com.grissserver.MainClass;
public class SecondClass extends MainClass{
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
super.appendToTextArea("call from Second Class in printOnTextArea()");
}
}
Please give some Idea, why this is not working.
I think the problem is that the way you try to paint to the text area is wrong.
In your action method you create a new object of SecondClass which extends MainClass. This means this object has its own textarea object. But this new object (frame) is not displayed, because you only call setVisibile in MainClass#main, and hence you cannot see the displayed text!
In short: There are two different text areas! And one of them is not visible
The SecondClass has its own textArea. So you may need to pass MainClass's textArea to SecondClass.
public class SecondClass {
private TextArea tArea;
SecondClass(TextArea ta) {
tArea = ta;
}
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
tArea.append("call from Second Class in printOnTextArea()");
}
}
You should change your MainClass like this.
....
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass(textArea);
secondClass.printOnTextArea();
}
});
....
hope this helps...

Categories

Resources