Getting a JOptionPane to appear after clicking button - java

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();
}
}

Related

JTextfield and JButtons

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);
}

JAVA tabs design

I'm trying to make a GUI window in Java with 4 tabs at the top Home, Booking, Guest, Room. However, the problem is that I'm not sure how to implement buttons in specific tab.
More specific, I made a class called GuestTab and I made 1 button and 1 textfield, but I don't know how can I convey those informations to a Guest tab.
So, if I wasn't so clear, when I click on Guest tab I want to have buttons and text fields that I made in GuestTab class.
I'll put the code of "SEP" class, where I have my GUI main design and "GuestTab" class where I'm adding stuff for Guest tab.
SEP.java:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SEP extends JFrame
{
private GuestTab GuestTab;
private JTabbedPane tPane;
private MyButtonListener buttonListener;
private MyTabListener tabListener;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem exitMenuItem;
public SEP()
{
super("Deer Alley Hotel");
buttonListener = new MyButtonListener();
tabListener = new MyTabListener();
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(buttonListener);
fileMenu = new JMenu("File");
setJMenuBar(menuBar);
tPane = new JTabbedPane();
tPane.addTab(" Home ", new JPanel(
new FlowLayout()));
tPane.addTab(" Booking ", new JPanel(
new FlowLayout()));
tPane.addTab(" Guest ", GuestTab);
tPane.addTab(" Room ", new JPanel(new FlowLayout()));
tPane.addChangeListener(tabListener);
add(tPane);
setSize(575, 452);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitMenuItem)
{
int choice = JOptionPane.showConfirmDialog(null,
"Do you really want to exit the program?", "Exit",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
}
public class MyTabListener implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
}
}
}
GuestTab.java:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GuestTab extends JPanel
{
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JPanel panel1;
private JPanel panel2;
private JTextField text;
public GuestTab()
{
panel1 = new JPanel();
button1 = new JButton("Edit Note");
button2 = new JButton("Check out");
button3 = new JButton("Edit Form");
button4 = new JButton("Search");
text = new JTextField(15);
add(panel1);
panel1.setPreferredSize(new Dimension(280, 300));
panel1.add(button4);
panel1.add(text);
setVisible(true);
}
}
You aren't defining your GuestTab properly.
In this line:
tPane.addTab("Guest", guestTab);
Change it to:
tPane.addTab("Guest", new GuestTab());
Or you can initialize the JPanel. You never actually do this you just say
there is a guest tab but you never do anything with it so you can also do:
private GuestTab guestTab;
and then later:
guestTab = new GuestTab();
Side note, never use the same case for the variable definition and class call. Make sure you are using proper camel case.

My UI is being shown twice in the same window

Here's an example
My Jtextfields and Jbuttons are being duplicated in the same window, and appear to function exactly the same.
This is probably an easy fix, but as you can tell I'm pretty awful at coding.
(oh and some of the names for variables and such are placeholders :p)
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class Adding extends JFrame {
public Adding(Heavy_Lifting lifting) {
addUI(lifting);
}
public void addUI(final Heavy_Lifting lifting) {
setLayout(new FlowLayout());
JButton addButton = new JButton("Enter");
JButton backButton = new JButton("Quit");
final JTextField eInput = new JTextField("Enter english name");
final JTextField mInput = new JTextField("Enter maori name");
final JTextField dInput = new JTextField("Enter description");
//add(addButton);
//add(eInput);
//add(mInput);
//add(backButton);
//add(dInput);
Dimension x = new Dimension(500, 50);
//addButton.setText("Enter");
addButton.setPreferredSize(x);
//backButton.setText("Quit");
backButton.setPreferredSize(x);
//eInput.setText("Enter english name");
eInput.setPreferredSize(x);
//mInput.setText("Enter maori name");
mInput.setPreferredSize(x);
//dInput.setText("Enter description");
dInput.setPreferredSize(x);
add(addButton);
add(eInput);
add(mInput);
add(dInput);
add(backButton);
addButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent e) {
String mname = mInput.getText();
String ename = eInput.getText();
String desc = dInput.getText();
PeePee p = new PeePee(mname);
Description d = new Description(desc);
if (lifting.allChar(ename, p)) {
lifting.insert(ename, p);
lifting.insert(ename, d);
eInput.setText("1");
mInput.setText("2");
dInput.setText("3");
} else {
eInput.setText("4");
mInput.setText("5");
dInput.setText("6");
}
}
});
backButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
setTitle("placeholder");
setSize(550, 300);
setMinimumSize(new Dimension(550, 300));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
}
This looks like your public method addUI is called twice, maybe by another class. Try switch it to private and see if it still runs and produces the same visual output.

Don't know how to use an external pane for GUI

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.

Java - Program will not Compile/method getText(double)

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);
}
}

Categories

Resources