How to execute a .java file on clicking a jbutton in jframe? - java

On clicking the jbutton in a jframe, I want Start.java file to be executed;what to do?
The Start.java is executing well. I want the same execution to be done when clicked on jbutton in jframe, please help me out.
My jframe code has jbutton
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
// i want to execute Start.java file on clicking the button
Start s = new Start();
String in = s.getTxt;
System.out.println(in);
repaint();
}
My Start.java file is :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Start extends JPanel{
public String getTxt;
public Start()
{
final JTextField jf = new JTextField(20);
jf.setBounds(30, 30, 250, 30);
final JButton j1 = new JButton("OK");
j1.setBounds(80, 80, 100, 30);
setLayout(null);
add(jf);
add(j1);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310,250));
f.setMaximumSize(new Dimension(310,250));
f.setMinimumSize(new Dimension(310,250));
f.pack();
f.setVisible(true);
}
}

So, based on what you seem to be doing in your code, I would strongly recommend that you have a look at How to Make Dialogs, the main reason for this is, a modal dialog will cause the execution of your program to stop at the point where the dialog is made visible and resume when it's closed, this way, allowing you to inspect the values the user might have changed.
So, when I first tried to get your program to work, this is what happened...
So, after digging into your code, I noticed you'd done setLayout(null);. This is going to keep on coming back to haunt you and I strongly recommend that you don't do this and learn how to use the layout management API.
So, I jumped into you code and add a layout manager...
public class Start extends JPanel {
public String getTxt;
public Start() {
final JTextField jf = new JTextField(20);
final JButton j1 = new JButton("OK");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
add(j1, gbc);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
Now I get...
Okay, but now there's two buttons, and unless the user clicks the middle button, the text is never set!
The fact is, for this kind of thing, you don't need the button! You just need a method which can return the current text of the JTextField, for example...
public class Start extends JPanel {
final JTextField jf = new JTextField(20);
public Start() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
}
public String getText() {
return jf.getText();
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
And then I can use...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Surprise");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Start start = new Start();
JOptionPane.showMessageDialog(TestPane.this, start, "Surprise", JOptionPane.PLAIN_MESSAGE);
System.out.println(start.getText());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
to show it!
I'd strongly recommend that you take the time to have a look at Laying Out Components Within a Container

Related

how to open frame from another frame Java Swing

I am making a program that has multiple sub-programs but when I am trying to open a new frame, it doesn't do anything.
The program that calls the frame:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Options");
JButton notepad = new JButton("Notepad");
JButton todo = new JButton("To-Do List");
NoteListe noteListener = new NoteListe();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new GridLayout(1,2));
frame.add(notepad);
frame.add(todo);
notepad.addActionListener(noteListener);
}
}
The action listener for the notepad button:
import java.awt.event.*;
public class NoteListe implements ActionListener{
public void actionPerformed(ActionEvent e){
new MainNote();
}
}
The notepad:
import javax.swing.*;
import java.awt.*;
public class MainNote {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Editor");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new GridLayout(2,1));
}
}
I really think you need to take a closer look at:
Providing Constructors for Your Classes
Defining Methods
Passing Information to a Method or a Constructor
These are really fundamental concepts and you should have firm grasp of them before you venture into the wild and unforgiving world of GUI development.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MenuPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MenuPane extends JPanel {
public MenuPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JButton notepad = new JButton("Notepad");
JButton todo = new JButton("To-Do List");
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(notepad, gbc);
add(todo, gbc);
notepad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainNote note = MainNote.show(MenuPane.this);
note.setText("This is where your text goes");
}
});
}
}
public static class MainNote extends JPanel {
private JTextArea ta;
public MainNote() {
setLayout(new BorderLayout());
ta = new JTextArea(20, 40);
add(new JScrollPane(ta));
}
public void setText(String text) {
ta.setText(text);
}
public String getText() {
return ta.getText();
}
public static MainNote show(Component parent) {
MainNote mainNote = new MainNote();
JFrame frame = new JFrame("Text Editor");
frame.add(mainNote);
frame.pack();
frame.setLocationRelativeTo(parent);
frame.setVisible(true);
return mainNote;
}
}
}
Note: I've used a static method (show) to simplify the construction of another window. This is simply a delegation workflow, as I'm delegating the responsibility for creating the window to the method, but I'm still getting back an instance of the MainNote.
Because MainNote is simply a JPanel, it can be added to what ever container I want. Because I've "encapsulated" the functionality into the class itself, it makes it much easier to manage.

Center JLabel in BorderLayout with a button at line end

I have a header on a section of my swing layout, and I want to have text centered horizontally across the whole width of the section, but also have a button on only the right side. It should look like this:
/------Same width------\ /------Same width------\
[------------------------]Text here[----------------[Button]]
I am currently using a BorderLayout, with the text in the center and the button at the line end, but the text is centered not counting the button, as such:
/----Same width----\ /---Same width----\
[--------------------]Text here[-------------------][Button]]
I'm not sure if this is the answer you really want, but you could use a different layout manager, like GridBagLayout
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication295 {
public static void main(String[] args) {
new JavaApplication295();
}
public JavaApplication295() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
// gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JLabel("Look ma, no hands"), gbc);
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("No Allowance"), gbc);
}
}
}
Now, the problem with this, is both components are actually positioned at the same location, the difference is, the button is anchored to the right position of the cell, this means that when the layout is been calculated, they will overlap....
Here is an approach using the OverlayLayout which was designed to have multiple components painted on the z axis:
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JLabel label = new JLabel("I'm a Centered Label");
Box labelBox= Box.createHorizontalBox();
labelBox.add(Box.createHorizontalGlue());
labelBox.add(label);
labelBox.add(Box.createHorizontalGlue());
JButton button = new JButton("Button");
Box buttonBox= Box.createHorizontalBox();
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(button);
setLayout( new OverlayLayout(this) );
add(buttonBox);
add(labelBox);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
As the width decreases the button will paint over the label.

How to put a JButton at a specific location?

I know that there are already very similar questions to my question on stackoverflow, but neither one of them answers my question.
I want to put my JButton on a specific location on my JFrame in JAVA. Here is my Code:
public class DetectMotion extends JFrame {
private JLabel label = null;
public DetectMotionExample() {
JPanel pnlButton = new JPanel();
label = new JLabel(nothing);
JButton btn = new JButton("Close");
pnlButton.setLayout(new BorderLayout());
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
WebcamPanel panel = new WebcamPanel(webcam);
add(panel);
pnlButton.add(btn,BorderLayout.SOUTH);
pnlButton.add(label,BorderLayout.NORTH);
add(pnlButton);
pack();
setVisible(true);
}
}
I have a panel on my JFrame (webcamPanel) and a JPanel called pnlButton that includes the JButton (btn) and JLabel (label).
Now, how can I specifically change the location of my button instead of just using BorderLayout.NORTH?
Thanks!
Make use of appropriate layout managers to achieve your goals...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DetectMotion extends JFrame {
private JLabel label = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DetectMotion frame = new DetectMotion();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public DetectMotion() {
JPanel pnlButton = new JPanel();
label = new JLabel("nothing");
JButton btn = new JButton("Close");
pnlButton.setLayout(new GridBagLayout());
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
panel.setBackground(Color.RED);
add(panel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
pnlButton.add(label, gbc);
gbc.weighty = 0;
pnlButton.add(btn, gbc);
add(pnlButton, BorderLayout.EAST);
pack();
setVisible(true);
}
}
package javaapplication647;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DetectMotion extends JFrame {
private JLabel label = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DetectMotion frame = new DetectMotion();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public DetectMotion() {
JPanel pnlButton = new JPanel();
label = new JLabel("nothing");
JButton btn = new JButton("Close");
pnlButton.setLayout(new FlowLayout(FlowLayout.RIGHT));
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
panel.setBackground(Color.RED);
add(panel);
pnlButton.add(label);
pnlButton.add(btn);
add(pnlButton, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
Take a look at Laying Out Components Within a Container for more ideas
If you want to put the item into a specific coordinate you have to use null Layout:
Example:
public void newClass(){
public newClass(){
JPanel panel = new JPanel();
JButton button = new JButton("button1");
panel.setLayout(null);
button.setBounds(x,y,X,Y);
panel.add(button);
}
public static void main(String[] args){
newClass();
}
}
Doing Without a Layout Manager (Absolute Positioning)
Your best bet is to use a Java Drag-and-Drop GUI builder like NetBeans. Particularly if you're interested in very specific positioning, nothing really beats a GUI builder.

JLabel not updating

so thanks for looking at my question,Well anyways im trying to make a cookie clicker clone (if you could call it that) where you click the button and the JPanel updates, unfortunately the JPanel doesn't update and I just cant find an answer anywhere else, Any help is valuable help, thank you! Here is my code:
public int numCookies;
public main(){
//JButton
JButton click = new JButton("Click");
click.setLayout(null);
click.setLocation(50, 50);
click.setSize(80, 50);
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
}
});
//JLabel
JLabel cookies = new JLabel();
cookies.setLayout(null);
cookies.setText("Cookies:" + numCookies);
cookies.setLocation(480/2,10);
cookies.setSize(200, 50);
//JPanel
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setLocation(10, 0);
panel.setSize(260, 30);
panel.add(click);
panel.add(cookies);
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String args[]){
new main();
}
Three things...
One...
Use of null layouts. Don't be surprised when things go wrong. When using JLabel or JButton, unless you intend to actually add something to them, you don't need to touch there layout managers.
Make use of approriate layout managers
Two...
Calling setVisible on your frame before you've finished filling it out...
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
// No idea what you expect this to be doing...
pack();
//frame.setVisible(true);
frame.add(panel);
// This belongs here...and you shouldn't pack a window until
// it's ready to be made visible...
frame.setVisible(true);
Three...
You seem to expect that the lable will magically now that the value numCookies has changed...
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
// ??????
}
You need to reassign the value to the label in order for the label to be updated...
For example...
public main(){
//JLabel
// Make the lable final...so we can access from witin
// the listener...
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
//JButton
JButton click = new JButton("Click");
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});
Bonus
Make sure you read through and understand Initial Threads
...And just because null layouts annoy me so much...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public int numCookies;
public Main() {
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cookies.setText("Cookies:" + (++numCookies));
}
});
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(cookies, gbc);
frame.add(click, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Main();
}
});
}
}
Set the text of the JLabel in the actionPerformed method like this:
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});

Java GUI JPanel Not Working

I really can't figure out why this JPanel "p" isn't appearing?
I thought I coded it right for the JPanel p to be in the middle of the Jframe and should make the whole JFrame RED but it doesn't seem to do that and the buttons and JPanel aren't appearing. Sorry. I know I am probably stupid but please help. :?
Here is the code.
package com.gorillalogic.henry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Notepad {
private JFrame f; // creates all GUI components
private JPanel p;
private JButton b1;
public Notepad() {
gui();
}
public void gui() {
f = new JFrame("Notepad");
p = new JPanel();
b1 = new JButton("Quit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
f.setSize(600, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
p.setBackground(Color.RED);
p.add(b1);
f.add(p, BorderLayout.CENTER);
}
public static void main(String[] args) {
new Notepad();
}
}
Thanks in advance. :)
p.setOpaque(true);
You need to do that.

Categories