I've got my Keypad class separate and I want to run it from the other class (gui), so I can have whatever I want in my gui class (some btn etc.) and then in the bottom my Keypad.
When I try Keypad kp = new Keypad(); I get almost what I want but they're displayed in separate windows I want them to be in the same window.
That's the Keypad class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class KeypadWork extends JFrame implements ActionListener {
private JButton buttonR = new JButton("Reset");
private JButton button0 = new JButton("0");
private JButton buttonE = new JButton("Enter");
public KeypadWork() {
setTitle("Keypad");
setLayout(new GridLayout(4, 3, 2, 2));
for (int i = 1; i < 10; i++) {
addButton(new JButton(String.valueOf(i)));
}
addButton(buttonR);
addButton(button0);
addButton(buttonE);
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
private void addButton(JButton button) {
button.addActionListener(this);
add(button);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
That's the solution, thank you #Alderath
If you don't want the KeyPadWork instance to be in a separate window, then you shouldn't make it a JFrame. If you want it inside another window, extend JPanel instead and add the KeyPadWork instance to some other JFrame using the normal AWT Container.add(Component) method.
Thanks a lot!
Related
I am building a GUI program in which specific code takes place when a certain condition is meant (JButton is pressed). I have a seperate class that constructs my Jframe called "MyFrame" .
Essentially I want to know the proper way to use my use a ActionListener/ ActionEvent from my "MyFrame" class in conjunction when a JButton is pressed in which it would correlate properly in the main class.
For example i am able to initiate specific code when a JButton is pressed in my MyFrame class through the actionPerformed provided method by java in my Myframe class, I am just puzzled on how I can make the same thing work through my main class as well.
Any assistance would be appreciated
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
MyFrame mf;
mf= new MyFrame();
Expenses exp ;
BudgetSystem system ;
ActionEvent e ;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyFrame extends JFrame implements ActionListener {
JFrame myFrame;
JPanel myPanel;
JLabel greetText ;
JButton addReportButton;
JButton exitButton;
ActionListener event ;
BorderLayout layout ;
MyFrame() {
myFrame = new JFrame();
myPanel = new JPanel();
greetText = new JLabel();
addReportButton = new JButton();
exitButton = new JButton();
myPanel.setBorder(null);
myFrame.setPreferredSize(new Dimension(400,300));
greetText.setText("Please choose one of the following options to begin:" );
myPanel.add(greetText);
myFrame.add(myPanel);
addReportButton.setText("Add a budget report");
addReportButton.addActionListener(this);
myPanel.add(addReportButton);
exitButton.setText("Close Program");
exitButton.addActionListener(this);
myPanel.add(exitButton);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
myFrame.pack();
}
#Override
public void actionPerformed(ActionEvent e) {
/*
if (e.getSource()==addReportButton)
{
JOptionPane.showMessageDialog(myFrame,"This button Works!");
}
else if (e.getSource()== dummyButton)
{
JOptionPane.showMessageDialog(myFrame,"This is the dummy button ! , you are targeting specific buttons now ! ... YOU ROCK :) ");
}else
JOptionPane.showMessageDialog(myFrame,"This is does not work :( ");
*/
}
}
I tried to make a specific ActionEvent object in main but that did not work properly.
I also tried to use a MyFrame object to access the actionPerformed method in java but that doesnt seem to work either.
If your goal is to add listeners to a JButton from another class, one option is to give the class that holds the JButton a public method that allows this to happen, for instance:
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
This would allow any object that holds an instance of the class that holds the JButton to call this method and pass in a listener.
For instance:
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AddOutsideActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SomeGUI mainPanel = new SomeGUI();
mainPanel.addMyButtonListener(e -> {
String message = "Message from the main method";
String title = "Message";
int type = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(mainPanel, message, title, type);
});
JFrame frame = new JFrame("Some GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
class SomeGUI extends JPanel {
public static final int PREF_W = 600;
public static final int PREF_H = 400;
private JButton myButton = new JButton("My Button");
public SomeGUI() {
add(myButton);
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
}
I have looked at a lot of answers but i still cannot find a solution. I have a JFrame and two JPanels. I want to remove the one panel and replace it with the second when a button is pressed, but the repaint() method does not refresh the frame. Please help.
Here is my code for the frame:
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MainFrame
{
static JFrame mainFrame;
int height = 650;
int width = 1042;
public MainFrame()
{
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, width, height);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}
public static void main(String[] args)
{
new MainMenu();
mainFrame.setVisible(true);
}
}
This is the code for my MainMenu panel
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.Color.CYAN;
import static java.awt.Color.red;
public class MainMenu extends MainFrame
{
public MainMenu()
{
components();
}
//variable decleration
JPanel menuPanel;
JLabel title;
JButton periodicTable;
private void components()
{
int buttonW = 500;
int buttonH = 50;
//creating panel
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(CYAN);
//creating title label
title = new JLabel("Application Title", SwingConstants.CENTER);
title.setFont(new Font("Calibri Body", 0, 50));
title.setBounds(width / 3 - buttonW / 2, 50, buttonW, buttonH + 10);
//creating periodic table button
periodicTable = new JButton();
periodicTable.setText("Periodic Table");
periodicTable.setBounds(width / 3 - buttonW / 2, 50 + buttonH + 60, buttonW, buttonH);
periodicTable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
periodicTableActionPerformed(event);
}
});
//adding components to panel
menuPanel.add(title);
menuPanel.add(periodicTable);
//adding panel to MainFrame
mainFrame.add(menuPanel);
}
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel);
mainFrame.repaint();
new PeriodicTable();
mainFrame.repaint();
}
}
And finally my PeriodicTable panel
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends MainFrame
{
public PeriodicTable()
{
periodicComponents();
}
JPanel ptPanel;
private void periodicComponents()
{
ptPanel = new JPanel();
ptPanel.setLayout(null);
ptPanel.setBackground(Color.RED);
mainFrame.add(ptPanel);
}
}
I have no idea why you are extending MainFrame. Looks unnecessary to me.
I want to remove the one panel and replace it with the second when a button is pressed
Then use a CardLayout. Read the section from the Swing tutorial on How to Use CardLayout for a working example.
The tutorial will show you how to better structure your code.
Your PeriodicTable extends MainFrame. When creating new PeriodicTable you create with it new MainFrame which has its own instance of JFrame (MainFrame.mainFrame). You need to add that panel to existing mainFrame in MainMenu
I suggest removing changing your PeriodicTable class like this:
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends JPanel // Not MainFrame, but new custom panel
{
public PeriodicTable()
{
periodicComponents();
}
private void periodicComponents()
{
// You don't need ptPanel anymore, because `this` is JPanel
setLayout(null);
setBackground(Color.RED);
}
}
and change your actionPerformed function to something like this:
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel); // Remove old panel
mainFrame.add(new PeriodicTable()); // Create and add to existing mainFrame
mainFrame.repaint(); // Just one repaint at the end
// I think it will work even without repaint, because add and remove should schedule repainting as well
}
im trying to add an ActionListener to my buttons for my calculator Im making. The problem is that Im being presented an error when I try to make an ActionListener. I tried in one class then I created a listener class just to see if that would help. Here is my code:
package main;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public abstract class Main extends JFrame implements Listener{
public static void main(String[] args) throws IOException{
//Main variables
String dis = "0";
double ans = Double.parseDouble(dis);
//Making frames
JFrame frame = new JFrame("Calculator");
JPanel panel = new JPanel();
//Buttons
JButton enter = new JButton("Enter");
JButton sub = new JButton("-");
JButton add = new JButton("+");
JButton div = new JButton("รท");
JButton mult = new JButton("*");
JTextField text = new JTextField(dis);
//Font
Font bigFont = text.getFont().deriveFont(Font.PLAIN, 30f);
Font butf = text.getFont().deriveFont(Font.PLAIN, 20f);
//Methods
panel.setLayout(new FlowLayout());
panel.add(text);
panel.setSize(590, 100);
text.setColumns(22);
text.setFont(bigFont);
text.setHorizontalAlignment(JTextField.RIGHT);
text.setEditable(false);
enter.setForeground(Color.RED);
sub.setForeground(Color.RED);
div.setForeground(Color.RED);
mult.setForeground(Color.RED);
add.setForeground(Color.RED);
//Buttons Methods
enter.setBounds(470, 450, 100, 150);
sub.setBounds(470, 350, 100, 90);
div.setBounds(470, 250, 100, 90);
mult.setBounds(470, 150, 100, 90);
add.setBounds(470, 50, 100, 90);
enter.setFont(butf);
sub.setFont(butf);
div.setFont(butf);
mult.setFont(butf);
add.setFont(butf);
//Frame
frame.add(div);
frame.add(mult);
frame.add(sub);
frame.add(enter);
frame.add(add);
frame.add(panel);
frame.setSize(600, 650);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//extra
text.setSize(1000, 100);
//Actions
}
}
package main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public interface Listener extends ActionListener {
//Throwing error here 'Cant instantiate the type ActionListener'
ActionListener al = new ActionListener();
public default void actionPerformed(ActionEvent e){
}
}
Anyone know how to fix this error?
To declare an ActionListener use
public class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//dostuff
}
}
ActionListener is a interface, it can't be instantiated, without provide a concrete implementation of it's contract
interfaces can't contain instance fields
Simply speaking, it should look more like...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public interface Listener extends ActionListener {
public default void actionPerformed(ActionEvent e) {
}
}
You may also like to have a closer look at
How to Write an Action Listeners
What Is an Interface?
The Interfaces trail
In Swing, you should make sure that your UI is only created and manipulated from within the context of the Event Dispatching Thread. Have a look at Initial Threads for more details
You're also going to be very disappointed with the results of your layout, have a look at Laying Out Components Within a Container for better solutions
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GUI extends JFrame {
private JButton reg;
private JButton custom;
private JButton custom2;
public GUI(){
super("Heartstone Arena Alpha 0.01");
setLayout(new FlowLayout());
reg = new JButton("Click Me");
add(reg);
Icon ACn = new ImageIcon(getClass().getResource("463.png"));
Icon ACg = new ImageIcon(getClass().getResource("463 (1).png"));
custom = new JButton("Custom", ACn);
custom.setRolloverIcon(ACg);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
Icon An = new ImageIcon(getClass().getResource("Alexstrasza(303).png"));
custom2 = new JButton(" ", An);
custom2.setIcon(An);
custom2.setRolloverIcon(An);
}
}
Here is the code, what I want to do is have custom2 replace custom when it's clicked.
How would I go on about this?
I tried using custom = null and then add(custom2); but it doesn't show up
PS: Ignore the reg button
You need to add an ActionListener to your button, which should make the first button invisible and the second button visible. So it does not really get destroyed, you just dont show it.
Like this:
public class YourClassName implements ActionListener {
private JButton button1;
private JButton button2;
public YourClassName() {
// Code Snippet ----------------
button1 = new JButton("Click to replace");
button1.addActionListener(this);
// implement code for resizing and positioning here
button2 = new JButton("I am new here");
button2.setVisible(false);
// implement code for resizing and positioning here
// ...
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
button1.setVisible(false);
button2.setvisible(true);
}
}
}
Note: The code is made up out of my head, there may be a mistakes in it. Also, it is just a snippet, feel free to comment for full code
Im learning about Java Swing components and I want to do that when I push button, Java Swing would add label from another class into JFrame screen. Its just simple example for start.
I want to learn how to use and add swing components from another class.
There can be some stupid mistakes, but dont judge me, im new ^^
Frame class add button
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame{
private JButton btn;
private boolean regCompl = false;
public Frame(){
super("The title Macas");
setLayout(new FlowLayout());
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
regCompl = true;
}
}
);
add(btn);
if(regCompl == true){
RegComplete regObj = new RegComplete(this);
}
}// end of constructor
}
RegComplete Class add label to screen after button are pressed.
import javax.swing.JButton;
import javax.swing.JLabel;
public class RegComplete {
Frame frame;
private JLabel label;
public RegComplete(Frame fm){
this.frame = fm;
label = new JLabel("Hello world Mac4s");
fm.add(label);
}
}
You have to create Object inside the action Listener
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
RegComplete regObj = new RegComplete(Frame.this);
}
}
);