JButton in separate class file - java

I wrote class which contain simple JFrame and I want to add button from other
class to this JFrame
When I'm trying to write
panel.add(new CancelButton())
I got an error: LoginWindow.java:29: error: no suitable method found for add(CancelButton)
Can you help me with it?
import javax.swing.*;
import java.awt.*;
public class LoginWindow {
public LoginWindow(){
//Login Window
JFrame frame = new JFrame("Movie date base");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//label
JLabel label = new JLabel("Welcom to Movie Date Base! ");
label.setFont(new Font("Verdana", Font.PLAIN, 18));
//panel
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel1 = new JPanel(new GridBagLayout());
//add panel to the frame
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(panel1, BorderLayout.SOUTH);
//Grid layout
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(100,10,10,10);
panel.add(label,c);
}
}
import javax.swing.*;
public class CancelButton {
public CancelButton(){
JButton cancel = new JButton("cancel");
}
}

If you want to treat your CancelButton class as a JButton, then it has to extend JButton.
public class CancelButton extends JButton{
public CancelButton(){
//call the parent-level constructor
super("cancel");
}
}
Note that I've gotten rid of your cancel variable here, since your CancelButton class is-a JButton now. You can use it anywhere you can use a JButton.
However, if instead you want to use the cancel variable in other classes, then you need to create some kind of getter function for it:
public class CancelButton {
JButton cancel;
public CancelButton(){
cancel = new JButton("cancel");
}
public JButton getButton(){
return cancel;
}
}
Then you would call that getButton() function, like this:
panel.add(new CancelButton().getButton())
Which approach you take really depends on exactly what you're trying to do, and how you want to organize your code.

If you'd like to keep it like it is, put the button into an array, and in the jframe, instantiate the cancel class and call from the array.

Related

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

Swap between panels

I am trying to add buttons over the images in the panels. I am also trying to switch between the panels. The program is running but when I am clicking the "instructions" button it gives a huge list of errors in the cmd. What is the issue?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JButton;
import javax.swing.JPanel;
public class htw10 extends JFrame
{
final JFrame f=new JFrame("Hunt The Wumpus");
private static final String FIRST_PANEL="first panel";
private static final String SECOND_PANEL="second panel";
private CardLayout cardLayout=new CardLayout();
private JPanel content;
public void start()
{
// Create a new panel, make 'content' refer to it
content = new JPanel();
// Set the content pane of the window to the panel we just created
f.setContentPane(content);
// Create a button group and some buttons
// Set the layout of the content panel and add buttons
content.setLayout(new FlowLayout());
// Create and add the intro panel and instruction panel to the content panel
content.add(introPanel(),FIRST_PANEL);
content.add(instructionPanel(),SECOND_PANEL);
f.setSize(750,500);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setVisible(true);
}
private JPanel instructionPanel()
{
JPanel secondPanel=new JPanel();
ImageIcon icon=new ImageIcon("img2.jpg");
JLabel pic2 = new JLabel(icon);
secondPanel.add(pic2);
JButton b1=new JButton("Back");
content.add(b1);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(content,FIRST_PANEL);
}
});
secondPanel.repaint();
return secondPanel;
}
public JPanel introPanel()
{
JPanel iPanel=new JPanel();
ImageIcon icon=new ImageIcon("img1.jpg");
JLabel picLabel = new JLabel(icon);
iPanel.add(picLabel);
ButtonGroup group=new ButtonGroup();
JButton b1=new JButton("Instructions");
JButton b2=new JButton("Play");
JButton b3=new JButton("Exit");
picLabel.add(b1);
//f.getContentPane().add(picLabel,BorderLayout.SOUTH);
content.add(b1);
content.add(b2);
content.add(b3);
// Add a listener to the 'Instructions' button
// so that the cardLayout is shown when the button is clicked
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(content,SECOND_PANEL);
}
});
iPanel.repaint();
return iPanel;
}
public static void main(String args[])throws Exception
{
htw10 obj=new htw10();
obj.start();
}
}
In line 14, you are declaring a member variable content, but you are not initializing it. Member variables will be automatically initialized to null if you do not initialize them yourself:
private JPanel content; // is automatically set to null
In line 25 you are calling the method setLayout on content:
content.setLayout(new FlowLayout());
This will cause a NullPointerException because content is null.
To learn more about what a NullPointerException is and why it happens, see: What is a NullPointerException, and how do I fix it?
You need to set content to something. It appears that this is supposed to refer to the content pane. Furthermore, you are calling the introPanel() method multiple times, causing multiple instances of this panel to be created. That is not what you want. That panel should be created only once, and then you should use that one. Don't call introPanel() multiple times. Your start() method should look something like this:
public void start()
{
// Create a new panel, make 'content' refer to it
content = new JPanel();
// Set the content pane of the window to the panel we just created
f.setContentPane(content);
// Create a button group and some buttons
ButtonGroup group=new ButtonGroup();
JButton b1=new JButton("Instructions");
JButton b2=new JButton("Play");
JButton b3=new JButton("Exit");
// Set the layout of the content panel and add buttons
content.setLayout(new FlowLayout());
content.add(b1);
content.add(b2);
content.add(b3);
// Create and add the intro panel and instruction panel to the content panel
content.add(introPanel(),FIRST_PANEL);
content.add(instructionPanel(),SECOND_PANEL);
f.setSize(750,360);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setVisible(true);
// Add a listener to the 'Instructions' button
// so that the cardLayout is shown when the button is clicked
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(content,SECOND_PANEL);
}
});
}
I don't think Jpanel has drawImage method which you are trying to call in below code.
public JPanel introPanel()
{
JPanel iPanel=new JPanel();
ImageIcon icon=new ImageIcon("img1.jpg");
iPanel.drawImage(icon, 0, 0,getWidth(),getHeight(),this);
return iPanel;
}
You need a graphics(java.awt.Graphics) object to call drawImage method.
More-over you can try other methods like
public JPanel introPanel()
{
JPanel iPanel=new JPanel();
ImageIcon icon=new ImageIcon("img1.jpg");
JLabel picLabel = new JLabel(icon);
iPanel.add(picLabel);
iPanel.repaint();
return iPanel;
}

PictureCount does not change

the code is used to create an application which shows picture and if your anwser is correct your supposed to see the next picture but the pictureCount does not go up. all of the variables ar declared after the main class and i created an Actionlistener to check if the awnser is correct.
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) {new Main().test();}
public int pictureCount = 1;
JFrame frame = new JFrame();
JButton button1 = new JButton("Submit");
JTextField text = new JTextField();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel label = new JLabel(new ImageIcon("C:\\Users\\Admin\\Desktop\\practicum 3\\" + pictureCount + ".jpg"));
void test(){
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(text.getText().equals("5")){
pictureCount++;
new Main().test();
}
}
});
panel1.add(button1);
panel2.add(text);
panel3.add(label);
text.setPreferredSize(new Dimension(100,50));
panel1.setPreferredSize(new Dimension(1000, 200));
panel2.setPreferredSize(new Dimension(1000, 100));
panel3.setPreferredSize(new Dimension(1000, 450));
frame.getContentPane().add(BorderLayout.SOUTH, panel1);
frame.getContentPane().add(BorderLayout.CENTER, panel2);
frame.getContentPane().add(BorderLayout.NORTH, panel3);
frame.setSize(1000,750);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Operation Screen");
frame.setLocationRelativeTo(null);
}
}
You need to read in all the pictures as ImageIcons into an array or ArrayList, say called imageIconArray and then display imageIconArray[0] in your JLabel when you start.
When the button is pressed, increment pictureCount, and then reset the JLabel's icon via its setIcon(...) method:
// in the ActionListener code:
pictureCount++;
label.setIcon(imageIconArray[pictureCount];
Whatever you do, don't create a new Main object, despite what others might say. Why create a new GUI when all you need to do is swap displayed images?

Swing Number Format Exception

For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier

JButtons not appearing on my JFrame

I am making a program that includes a GUI. For some reason, the JButton objects that I have created are not showing up onto my JFrame when I run the program. Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain(){
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
enterButton.setPreferredSize(new Dimension(60,60));
exitButton.setPreferredSize(new Dimension(60,60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200,50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField();
textField.setSize(200, 100);
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
//Creating a ButtonListener class that implements the ActionListener interface
private class ButtonListener implements ActionListener{
#Override
//Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if(action.getSource()== enterButton)
enterButton();
if(action.getSource()== exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main (String[] args){
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
}
}
If there are any problems or improvements I can make in my code, please let me know!
You're adding the components to your JFrame after it's visible. You should either add them to the JFrame before it's visible, or revalidate the JFrame after you add the components.
When I load your code (after making it a lot shorter in height), this is what I see:
I suspect this is more along the lines of what you expect to see.
Here is how I did it. Look carefully at:
The numbers provided to the BorderLayout constructor for white space between the panels.
The EmptyBorder for white space around the controls.
The use of pack() to shrink the GUI to the natural size.
The use of size hints in the construction of the text field and text area.
The use of a second layout - commonly known as a combined, or nested, layout.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel pageTopPanel;
private JTextArea textArea;
public ReverseAStringMain(){
super(new BorderLayout(10,10));
setBorder(new EmptyBorder(5,15,5,15));
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
pageTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
pageTopPanel.setBackground(Color.black);
pageTopPanel.add(enterButton);
pageTopPanel.add(exitButton);
textField = new JTextField(5);
pageTopPanel.add(textField);
textArea = new JTextArea(4,40);
add(pageTopPanel, BorderLayout.PAGE_START);
add(textArea); // defaults to CENTER
}
public static void main (String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("XXX's Laid out Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
General Tips
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Generally, you want to set the frame visible After adding components
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.setVisible(true); <<------
Also, it is better practice to use .pack() insteack of .setSize(), so you had it right in the commented out //.pack()
If you wanted to set a size to the panel, you would override the getPreferredSize() like this
public Dimension getPreferredSize() {
return new Dimension(300, 300); // or whatever size you want
}
When you .pack(), this preferred size will be respected by the frame.
Also, not, setting the size of the JTextField won't work. What you want to do is pass it an integer value for the number of character spaces, like this
textField = new JTextField(20);
See an edited version of your program, with all the above mentioned points. One thing I also did was get rid of all your .setPreferredSizes. You will see the difference
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain() {
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
//enterButton.setPreferredSize(new Dimension(60, 60));
//exitButton.setPreferredSize(new Dimension(60, 60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
//buttonPanel.setPreferredSize(new Dimension(200, 50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField(20);
//textField.setSize(200, 100); /// <<-----------
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
// Creating a ButtonListener class that implements the ActionListener
// interface
private class ButtonListener implements ActionListener {
#Override
// Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if (action.getSource() == enterButton)
enterButton();
if (action.getSource() == exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Have a look at the Swing tutorial trail for more information on creating GUIs with Swing.
Try to add the buttonPanel to a Container, like this. And extend JFrame instead
Container contentpane = getContentPane();
contentPane.add(buttonPanel);

Categories