Ok so I'm trying to get familier with Java, and I've made a simple thing where if you click a button then some text appears. How can I make it so the button and label are created in one class file, and put the code for when the button is clicked in another? Sorry if it sounds like a silly question.
Pastebin code:
package com.nate.derp;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Derp {
private JFrame frmHello;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Derp window = new Derp();
window.frmHello.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Derp() {
initialize();
}
public void initialize() {
frmHello = new JFrame();
frmHello.setTitle("Hello");
frmHello.setBounds(100, 100, 225, 160);
frmHello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHello.getContentPane().setLayout(null);
final JLabel helloLabel = new JLabel("Hello World!");
helloLabel.setVisible(false);
helloLabel.setBounds(40, 89, 145, 16);
frmHello.getContentPane().add(helloLabel);
final JButton btnClickMe = new JButton("Click Me!");
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
helloLabel.setVisible(true);
}
});
btnClickMe.setBounds(54, 29, 117, 29);
frmHello.getContentPane().add(btnClickMe);
}
}
You can do this by creating a JButton and adding an ActionListener, which can be implemented by another class.
So you first create the JButton:
Jbutton button = new JButton("hello");
Then add the Actionlistener:
button.addActionListener(new MyListener());
Where MyListener is your implementation class
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
}
}
Related
When I run this code which should take the text from a JLabel, use a getter method to move it to the button action class, modifiy it and then use a setter method to set it in the original class, it updates the JLabel variable but does not update the GUI.
I have tried repaint(), revalidate(), doLayout() on the label, the frame and the panel that holds the label.
The class that initializes the label:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class Testing4 {
private JFrame frame;
private JLabel lblNewLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing4 window = new Testing4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Testing4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
lblNewLabel = new JLabel("label");
lblNewLabel.setBounds(52, 101, 277, 53);
frame.getContentPane().add(lblNewLabel);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(114, 28, 156, 53);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(new ButtonAction());
}
public String getLabelText()
{
return this.lblNewLabel.getText();
}
public void setLabelText(String text)
{
System.out.println(text);
this.lblNewLabel.setText(text);
System.out.println(lblNewLabel.getText());
}
}
If you look at the setLabelText(String) method, it sets the text to the label called lblNewLabel and then it prints out the text to the console in the next line of code. That .getText() shows that the label has been modified, however the GUI does not show that it has been modified.
Here is the code for the button:
public class ButtonAction implements ActionListener
{
Testing4 test;
public void actionPerformed(ActionEvent e)
{
test = new Testing4();
String x = test.getLabelText();
System.out.println(x);
x = x + " hello";
System.out.println(x);
test.setLabelText(x);
}
}
For all intents and purposes, this should update the GUI with the new text, I've done this before and not had an issue but something this time is causing an issue.
This is the code.
The button doesnt work with key, if i dont click it first. It would
be great if you could help me.
I used eclipse when i created this frame
This is just an example code, but I just want to know how it functions
For any more detalis, ask here.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class ExampleApp {
private JFrame frmHi;
private JTextField textField;
private JButton btnAnother;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleApp window = new ExampleApp();
window.frmHi.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExampleApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHi = new JFrame();
frmHi.setTitle("Hi");
frmHi.setBounds(100, 100, 450, 300);
frmHi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHi.getContentPane().setLayout(null);
JButton btnEnter = new JButton("Enter");
btnEnter.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
textField.setText("You pressed enter");
}
}
});
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("Hi there from button");
}
});
btnEnter.setBounds(119, 63, 89, 23);
frmHi.getContentPane().add(btnEnter);
textField = new JTextField();
textField.setEnabled(false);
textField.setEditable(false);
textField.setBounds(108, 30, 173, 20);
frmHi.getContentPane().add(textField);
textField.setColumns(10);
btnAnother = new JButton("Backspace");
btnAnother.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
textField.setText("you pressed backspace");
}
}
});
btnAnother.setBounds(119, 119, 89, 23);
frmHi.getContentPane().add(btnAnother);
}
}
Your KeyListener addded to JButton so it works only when the button has focus (after click).
It's better to define KeyBindings for the keys you have to process.
I am trying to open the menu frame using a button on the main frame. I added an event to the button and I tried calling the other class but it keeps giving me an error of ":: expected after this token"
This is my main frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
public static JPanel mainPane;
public final JButton menuButton = new JButton("New button");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(null);
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(String[] args);
}
});
menuButton.setBounds(76, 89, 104, 32);
mainPane.add(menuButton);
}
}
And this is my menu frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class Menu extends JFrame {
public static JPanel menuPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuPane = new JPanel();
menuPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(menuPane);
menuPane.setLayout(null);
JLabel menuTitle = new JLabel("Menu");
menuTitle.setBounds(194, 11, 46, 14);
menuPane.add(menuTitle);
}
}
change your action event to this.no need to call main method .create a new instance of Menu class instead.
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu menu = new Menu();
menu.setVisible(true);
}
});
if you relly want to call main method then use
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(new String[0]);
}
});
the error is here
Menu.main(String[] args);//error
this is not a correct way of passing arguments to a methods.this is declaration of parameter list.
you can correct error by changing it to ,
String args[] = null;
Menu.main(args); //correct
I cant see my JMenu in the frame when I run it, what should i do?
I removed the panel where it was before, then i just want to put it in my frame
package app.ui;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.WindowConstants;
import app.model.User;
import app.util.JMenusss;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class JMenus {
private JFrame menuu;
private SecurityQuestion securityQuestion;
private User user;
private JMenu mnAccount;
public JMenus(JFrame menuu) {
this.menuu = menuu;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
final JLabel lblHome = new JLabel("");
lblHome.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
Welcome myWelcome = new Welcome();
menuu.dispose();
}
});
lblHome.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/home-icon.png")));
lblHome.setBounds(780, 4, 88, 83);
menuu.getContentPane().add(lblHome);
final JLabel lblItem = new JLabel("");
lblItem.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ItemManagement myItemManagement = new ItemManagement();
myItemManagement.ItemManagement();
menuu.dispose();
}
});
lblItem.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/items.png")));
lblItem.setBounds(860, 4, 88, 83);
menuu.getContentPane().add(lblItem);
final JLabel lblGroupManagement = new JLabel("");
lblGroupManagement.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/group11.png")));
lblGroupManagement.setBounds(940, 4, 88, 83);
menuu.getContentPane().add(lblGroupManagement);
lblGroupManagement.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
GroupManagement myGroupManagement = new GroupManagement();
myGroupManagement.groupManagement();
menuu.dispose();
}
});
final JLabel lblInventory = new JLabel("");
lblInventory.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
IOStock myInventory = new IOStock();
myInventory.InventoryWindow();
menuu.dispose();
}
});
lblInventory.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/IO.png")));
lblInventory.setBounds(1020, 4, 88, 83);
menuu.getContentPane().add(lblInventory);
final JLabel lblLogout = new JLabel("");
lblLogout.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/lock.png")));
lblLogout.setBounds(1100, 4, 120, 83);
menuu.getContentPane().add(lblLogout);
lblLogout.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int selectedOption = JOptionPane.showConfirmDialog(null,"You are about to logout, are you sure?","Choose",JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
Login window = new Login();
window.frmLogin.setVisible(true);
menuu.dispose();
}
}
});
This is where my JMenu is
JMenuBar mnbMenu = new JMenuBar();
mnbMenu.setBackground(Color.WHITE);
mnbMenu.setBounds(100, 4, 80, 89);
menuu.getContentPane().add(mnbMenu);
mnAccount = new JMenu();
mnAccount.setBackground(Color.WHITE);
mnAccount.setForeground(Color.WHITE);
mnAccount.setIcon(new ImageIcon("/app/resources/Settings-icon.png"));
mnAccount.setBounds(1180, 4, 100, 100);
mnbMenu.add(mnAccount);
JMenuItem mntmChangeUsername = new JMenuItem("Change Username");
mntmChangeUsername.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
UpdateUserName updateUsername = new UpdateUserName(user);
updateUsername.setVisible(true);
}
});
//mntmChangeUsername.setBackground(Color.WHITE);
mnAccount.add(mntmChangeUsername);
JMenuItem mntmChangePassword = new JMenuItem("Change Password");
mntmChangePassword.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ChangeUsername changeUsername = new ChangeUsername(menuu);
changeUsername.changeAcc();
}
});
mntmChangePassword.setBackground(Color.WHITE);
mnAccount.add(mntmChangePassword);
JMenuItem mntmChangeSecurityQuestion = new JMenuItem("Change Security Question");
mntmChangeSecurityQuestion.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ChangeSecurityQuestion changeSecurity = new ChangeSecurityQuestion(user, securityQuestion);
changeSecurity.setVisible(true);
changeSecurity.setLocationRelativeTo(null);
changeSecurity.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
changeSecurity.setAlwaysOnTop(true);
}
});
mntmChangeSecurityQuestion.setBackground(Color.WHITE);
mnAccount.add(mntmChangeSecurityQuestion);
}
}
This is my code...
I want to add the JMenu on my Frame,,, but its not visible, why?
Here:
JMenuBar mnbMenu = new JMenuBar();
...
menuu.getContentPane().add(mnbMenu);
The correct way to set the menu bar to a JFrame is through setJMenuBar() method:
JMenuBar mnbMenu = new JMenuBar();
...
menuu.setJMenuBar(mnbMenu);
Take a look to How to Use Menus tutorial. Additionaly you may want to see this topic Why JMenuBar is not place in the JFrame content pane(...)
Side note
Take a look to all #AndrewThompson's tips:
MCTaRE (Minimal Complete Tested and Readable Example)
Nowhere in those code snippets is a call to method setJMenuBar
Don't add a mouse listener to a menu. Add an ActionListener or an Action instead.
To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)