I have created a JFrame with 3 JTextFields, a button and a label in the centre of the page. I will create a key where if the user enters 'a' in all three textfields and hits the button, the color of the text in the label should change to a different colour for example red.
The main problem I have is linkning my textfields and the button so they work together.
import java.awt.BorderLayout;
import java.awt.Color;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CE203_2017_Ex1 extends JFrame
{
public static void window()
{
//Button
JButton but = new JButton("Submit");
//JNumberTextField
JTextField rgb1 = new JTextField("",3);
JTextField rgb2 = new JTextField("",3);
JTextField rgb3 = new JTextField("",3);
//JLabel
JLabel text1 = new JLabel("hello my name is adam ", JLabel.CENTER);
text1.setForeground(Color.BLUE);
text1.setAlignmentX(0);
text1.setAlignmentY(0);
//JFrame
JFrame window1 = new JFrame("Adam");
window1.setVisible(true);
window1.setSize(500,500);
window1.add(text1);
//JPanel
JPanel butPanel = new JPanel();
butPanel.add(rgb1);
butPanel.add(rgb2);
butPanel.add(rgb3);
butPanel.add(but);
window1.add(butPanel, BorderLayout.SOUTH);
window1.add(text1);
Here is my actionlistener for the button
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JTextField input = (JTextField) e.getSource();
String passy = input.getText();
String p = new String (passy);
if (rgb1.equals("a")&& rgb2.equals("a")&& rgb3.equals("a")){
text1.setForeground(Color.WHITE);
}
else{
JOptionPane.showMessageDialog(null, "nocorrect");}}});
}
public static void main( String[] args )
{
window();
}
}
You want to test the text value in the textFields not the objects.
if (rgb1.getText().equals("a")&& rgb2.getText().equals("a")&& rgb3.getText().equals("a")) {
text1.setForeground(Color.WHITE);
}
Related
as you see I have made a very simple program where I input text on a textfield, then press the button to print it on the console:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Main {
private static class Window extends JFrame {
private static class TextField extends JTextField {
private TextField() {
setVisible(true);
setBounds(5, 0, 190,20);
}
}
public class Button extends JButton implements ActionListener {
private Button() {
setText("print");
addActionListener(this);
setVisible(true);
setBounds(5, 35, 190,20);
}
public void actionPerformed(ActionEvent e) {
TextField textField = new TextField();
String input = textField.getText();
System.out.println(input);
}
}
However, while I click the button, it adds blank lines to the console, without the text I have written in it.
Your actionPerformed method creates a new TextField instance and prints the text from that new instance.
A very simple example that works as intended:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TextAndButtonExample {
public static void main( String[] args ) {
EventQueue.invokeLater(() -> new TextAndButtonExample().start());
}
void start() {
JTextField textField = new JTextField();
JButton button = new JButton(new AbstractAction("Print") {
public void actionPerformed( ActionEvent e ) {
System.out.println(textField.getText());
}
});
JPanel controlPane = new JPanel(new GridLayout(2, 1));
controlPane.add(textField);
controlPane.add(button);
JPanel contentPane = new JPanel();
contentPane.add(controlPane);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Note that I did not extend any Swing components and that I did use a layout manager instead of explicitly setting bounds for components.
I have to create a Library for lending Media Items. So far I have the GUI to look how it should, but now I've hit a brick wall with what to do next. When the user clicks the 'Add' button, two prompts should open asking the user for the Title and then the Format, but I have no clue what to do to achieve it. Any help would be great!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class FinalView extends JFrame{
private JButton add;
private JButton checkOut;
private JButton checkIn;
private JButton delete;
private JScrollPane display;
private JList jlist;
Scanner input = new Scanner(System.in);
public FinalView(){
setTitle("My Library");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//change later for save feature per printout
setLocationRelativeTo(null);
setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setLayout(new GridLayout(1, 4, 8, 8));
add = new JButton("Add");
checkOut = new JButton("Check Out");
checkIn = new JButton("Check In");
delete = new JButton("Delete");
buttonPanel.add(add);
buttonPanel.add(checkOut);
buttonPanel.add(checkIn);
buttonPanel.add(delete);
String[] movie = {"Star Wars", "StarTrek"};
Library call = new Library();
jlist = new JList(movie);
jlist.setVisibleRowCount(4);
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(jlist));
setVisible(true);
ActionListener listener = null;
add.addActionListener(listener);
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showInputDialog("Title:");
String title = input.nextLine();
JOptionPane.showInputDialog("Format:");
String format = input.nextLine();
addNewItem(title, format);
}
private void addNewItem(String title, String format) {
MediaItem lib = new MediaItem(title, format);
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new FinalView();
}
}
I am trying to create a Java GUI application that contains a label and button. When the button is clicked the background color of the first panel is changed. I've got the label and button but getting errors whenever I click the button. Also, I wanted the first panel to originally have a yellow background then switch to whatever color. Here's my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel;
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new BorderLayout());
biggerPanel.setBackground(Color.YELLOW);
JLabel namePanel = new JLabel("Click the button to change the background color");
biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
biggerPanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
I made a few changes to your code.
First, you must start a Swing application with a call to SwingUtilities.invokeLater.
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
Second, you use Swing components. You only extend a Swing component when you want to override a method of the Swing component.
Third, I made a action listener specifically for your JButton. That way, you don't have to check for a particular JButton string. You can create as many action listeners as you need for your GUI.
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
Finally, I changed the background color of the JButton panel.
Here's the entire ChangeDemo class.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Here is working demo based on amendments to your code, haven't had time to tidy it up but hopefully you'll get the gist of it. Problem was you hand't added Panels to the borders (north, south etc.) in order to color them. Hopefully this helps.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel = new JPanel();
private JPanel namePanel = new JPanel();
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
//JPanel biggerPanel = new JPanel();
this.biggerPanel.setLayout(new BorderLayout());
this.biggerPanel.setBackground(Color.YELLOW);
JLabel nameLabel = new JLabel("Click the button to change the background color");
namePanel.add(nameLabel);
namePanel.setBackground(Color.YELLOW);
//this.biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
changeButton.setActionCommand("Change Color");
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
this.namePanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
I have the following 2 java classes. I want to make a third class. The third class is supposed to be a tabbed pane which has two tabs. one tab should have the first pane that i put up and the 2nd tab should have the 2nd one I put up. I can't figure it out. Please help me before I break my computer. I've searched everywhere. I've tried to read the oracle documents and it just doesn't click for me I guess. I have read my text over and over and over and........
package Week4;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class OfficeAreaCalculator extends JFrame{
private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator()
{
mainFrame = new JFrame("Office Area Calculator");
exitButton = new JButton("Exit");
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
lengthField = new JTextField(5);
widthField = new JTextField(5);
areaField = new JTextField(5);
areaField.setEditable(false);
calculateButton = new JButton("Calculate");
Container c = mainFrame.getContentPane();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
c.add(lengthLabel);
c.add(lengthField);
c.add(widthLabel);
c.add(widthField);
c.add(areaLabel);
c.add(areaField);
c.add(calculateButton);
c.add(exitButton);
calculateButton.setMnemonic('C');
exitButton.setMnemonic('X');
mainFrame.setSize(260, 150);
mainFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
mainFrame.setVisible(true);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = ("0");
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
area = length * width;
areaField.setText(num.format(area));
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if (e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if (e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if (e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
public static void main(String arg[])
{
new OfficeAreaCalculator();
}
}
and
package Week4;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.*;
public class DayGUI extends JFrame
{
private JFrame mainFrame;
private JButton cmdGood;
private JButton cmdBad;
public DayGUI(){
mainFrame = new JFrame("Messages");
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container c = mainFrame.getContentPane();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
c.add(cmdGood);
cmdGood.setBackground(Color.green);
c.add(cmdBad);
cmdBad.setBackground(Color.red);
cmdGood.setMnemonic('G');
cmdBad.setMnemonic('B');
mainFrame.setSize(300, 100);
mainFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
mainFrame.setVisible(true);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e){
if (e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if (e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DayGUI app;
app = new DayGUI();
}
}
You can't add a Jframe to a tabbed pane. if each of your application was a JPanel you could just add them to your JTabbedPane.
each one of your JFrame classes uses a JFrame, and in the frame, each class creates its content.
You can re-arrange your code so that each of your JFrame creates a panel which creates its content just like the Jframe. then the panel is added to the JFrame. your first two applications should still work.
for your third class, use a Jframe, add the JTabbedPane to the Jframe, and then add the two panels created above (one from each of your first two) to your tabbed pane.
the easiest way is probably to accomplish the 3rd class is to just change the first two classes to extend JPanel instead of Jframe.
Then create a class which extends from JFrame, and adds a JTabbedPane which adds the two panels.
My program is suppose to make a GUI that calculates the square root of a number that is entered. I can not figure out why this code will not compile. I keep getting the following error message:
cannot find symbol
symbol : method getText(double)
What am I doing wrong?
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel Numberlbl = new JLabel("Enter a number:");
final JTextField NumberField = new JTextField(10);
NumberField.setText("");
JLabel Answerlbl = new JLabel("Square Root of your number is:");
final JTextField AnswerField = new JTextField(10);
AnswerField.setText("");
JLabel ButtonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(Numberlbl);
panel.add(NumberField);
panel.add(ButtonLabel);
panel.add(button);
panel.add(Answerlbl);
panel.add(AnswerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double NumberX = Double.parseDouble(NumberField.getText());
double Answer = Math.sqrt(NumberX);
AnswerField.setText(Answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The only compilation error I got was for the AnswerField.setText() line - if you look at the API reference for setText() it takes a string, but you are trying to pass it a double.
Have a look at the NumberFormat class for converting the double to a string correctly. A simpler option is to use a Double object (as opposed to the double data type, note capitalization), and use its toString() method. A down-and-dirty method is to write it as ("" + Answer), since it will auto-convert it for you.
The code will not compile because the method setText(String text) expects a String parameter, and you are giving it a double.
To make your code work, use:
AnswerField.setText(String.valueOf(Answer));
final Double answer = Math.sqrt(NumberX);
AnswerField.setText(answer.toString());
This one compiles. Here you go:
import java.awt.GridLayout;
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.JTextField;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel numberlbl = new JLabel("Enter a number:");
final JTextField numberField = new JTextField(10);
numberField.setText("");
JLabel answerlbl = new JLabel("Square Root of your number is:");
final JTextField answerField = new JTextField(10);
answerField.setText("");
JLabel buttonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(numberlbl);
panel.add(numberField);
panel.add(buttonLabel);
panel.add(button);
panel.add(answerlbl);
panel.add(answerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double numberX = Double.parseDouble(numberField.getText());
double answer = Math.sqrt(numberX);
answerField.setText(""+answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}