I'm doing a project for my class and I'm working on the GUI right now. I don't have much because, well, it's not showing up and it's infuriating. Here's my code.
public class BookQuizGUI extends JFrame implements ActionListener
{
private Container c;
private JPanel pnlButtons;
private JButton addQs;
private JButton takeQuiz;
private JButton quit;
private Container c2;
private JPanel pnlButtons2;
private JComboBox qType;
private JComboBox ans;
private JTextField q;
private JTextField cA;
private JTextField cB;
private JTextField cC;
private JTextField cD;
private JButton add;
private JButton writeAll;
private JButton done;
/**
*
*/
public BookQuizGUI()
{
//The main screen for when the program starts
c = getContentPane();
pnlButtons = new JPanel();
pnlButtons.setLayout(new GridLayout(1, 3));
addQs = new JButton("Add Questions");
takeQuiz = new JButton("Take Quiz");
quit = new JButton("Quit");
setTitle("Book Quiz");
setSize(800, 400);
setLocation(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pnlButtons.add(addQs);
pnlButtons.add(takeQuiz);
pnlButtons.add(quit);
addQs.addActionListener(this);
takeQuiz.addActionListener(this);
quit.addActionListener(this);
c.add(pnlButtons, BorderLayout.NORTH);
c.setVisible(true);
//The screen for when the user presses "Add questions"
c2 = getContentPane();
pnlButtons2 = new JPanel();
qType = new JComboBox();
qType.addItem("Elementary Question");
qType.addItem("Standard Question");
qType.addItem("Advanced Question");
pnlButtons2.add(qType);
}
/**
* #param args
*/
public static void main(String[] args)
{
BookQuizGUI gui = new BookQuizGUI();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == quit)
{
System.exit(0);
}
else if(e.getSource() == addQs)
{
c2.setVisible(true);
}
}
}
Another fundamental question of mine is how to go about switching between GUI screens? This code is supposed to have like a book quiz and you can add questions. Do I just make one container not visible and another visible?
You need to pack it and set it to be visible!
frame.pack();
frame.setVisible(true);
As for answering your second question, why not just change the elements and repaint() the screen, if I understand you want it to be like a quiz with multiple questions, right?
Related
Welcome everyone,
This is my first post on this website and I am also quite new to java so go easy on me :)
I am working on a project for my college the task is:
"Design & Build a Java application based on a class linked to a swing
(GUI) application. "
So I Decided to go for a shopping app that will allow you to choose a few games, add them to cart and then display the cart / edit it / remove items etc.
I am having problem with adding items to a cart using a JButton. Here is my code:
Driver:
public class Driver {
public static void main (String[] args) {
MainShop shop= new MainShop ("Welcome to my Shop");
}
}
MainShop:
import java.awt.*;
import java.util.*;
import java.text.*;
import java.math.*;
import javax.swing.*;
import java.awt.event.*;
public class MainShop extends JFrame implements ActionListener, WindowListener {
private Container content;
private JLabel l1 = new JLabel ("Welcome to my Shop");
private JLabel l2 = new JLabel("You want to browse for great games?");
private JLabel l3 = new JLabel ("Choose one of the following 2 platforms: ");
private JLabel l4 = new JLabel ("XBox has no good games. Try PS4 :) ");
private PS4 dialog1 = null ;
private XBox dialog2 = null;
private JButton b1 = new JButton("PS4");
private JButton b2 = new JButton("XBox");
public MainShop (String str) {
super(str);
content = getContentPane();
content.setLayout(new GridLayout(2,2));
content.add(l1);
content.add(l2);
content.add(l3);
content.add(l4);
l4.setVisible(false);
content.add(b1);
b1.addActionListener(this);
content.add(b2);
b2.addActionListener(this);
setSize(800, 150);
content.setBackground(Color.white);
this.addWindowListener(this);
setVisible(true);
}
public void actionPerformed (ActionEvent e) {
Object target = e.getSource();
if (target == b2) {
l4.setVisible(true);
}
if (target == b1) {
l4.setVisible(false);
this.setVisible(false);
new PS4(this, "PS4");
}
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
PS4 class
import java.awt.*;
import java.util.*;
import java.text.*;
import java.math.*;
import javax.swing.*;
import java.awt.event.*;
class PS4 extends JFrame implements ActionListener, WindowListener{
private JPanel Center = new JPanel();
private JPanel South = new JPanel ();
private JPanel North = new JPanel ();
private JPanel South1 = new JPanel();
private JPanel South2 = new JPanel();
private JPanel Center1 = new JPanel();
private JPanel Center2 = new JPanel ();
private JPanel Center3 = new JPanel ();
private JLabel n1 = new JLabel ("PS4 Games");
private JLabel c1desc = new JLabel ("Name");
private JLabel li1 = new JLabel ("Like it?");
private JLabel c2desc = new JLabel ("Description");
private JLabel c3desc = new JLabel ("Price");
private JButton basket = new JButton ("Proceed to checkout");
private JButton CB = new JButton("Go Back");
private JLabel g1 = new JLabel("Uncharted");
private JButton b1 = new JButton("Add to Basket");
private JLabel d1 = new JLabel (" Action-adventure ");
private JLabel p1 = new JLabel ("59.99€");
private JLabel g2 = new JLabel("Call of Duty");
private JButton b2 = new JButton("Add to Basket");
private JLabel d2 = new JLabel (" First Person Shooter ");
private JLabel p2 = new JLabel ("69.99€");
private JLabel g3 = new JLabel("Fifa 18");
private JButton b3 = new JButton("Add to Basket");
private JLabel d3 = new JLabel (" Sport ");
private JLabel p3 = new JLabel ("69.99€");
private JLabel g4 = new JLabel("Skyrim");
private JButton b4 = new JButton("Add to Basket");
private JLabel d4 = new JLabel (" Open World RPG ");
private JLabel p4 = new JLabel ("49.99€");
private Container content;
private JFrame parent;
public PS4 (JFrame p, String Str) {
super(Str);
parent = p;
getContentPane().add(North, BorderLayout.NORTH);
North.add(n1);
getContentPane().add(Center, BorderLayout.CENTER);
Center.setLayout(new GridLayout(5,4));
Center.add(c1desc);
Center.add(c2desc);
Center.add(c3desc);
Center.add(li1);
Center.add(g1);
Center.add(d1);
Center.add(p1);
Center.add(b1); b1.addActionListener(this);
Center.add(g2);
Center.add(d2);
Center.add(p2);
Center.add(b2); b2.addActionListener(this);
Center.add(g3);
Center.add(d3);
Center.add(p3);
Center.add(b3); b3.addActionListener(this);
Center.add(g4);
Center.add(d4);
Center.add(p4);
Center.add(b4); b4.addActionListener(this);
getContentPane().add(South, BorderLayout.SOUTH);
South.setLayout(new GridLayout(1,2));
South.add(South1);
South.add(South2);
South1.add(CB);
CB.addActionListener(this);
South2.add(basket);
basket.addActionListener(this);
setSize(600,400);
setVisible(true);
this.addWindowListener(this);
}
public void actionPerformed(ActionEvent e) {
Object target = e.getSource();
if (target == b1) {
// THIS IS WHERE I STRUGGLE
}
if (target == b2) {
}
if (target == b3) {
}
if(target == b4) {
}
if(target==CB) {
this.setVisible(false);
parent.setVisible(true);;
}
if (target == basket) {
this.setVisible(false);
new Checkout(this, "");
}
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
So how do I Add the items I want to a new class by clicking the "Add to cart" JButton?
The worst thing is that we have to present it in 2 weeks and it was given to us on our last class on Friday before eastern break. So we literally have 2 weeks to work on it without any help of our lecturers.
Also, please do not worry about the code structure/layout etc as this will be done at the very end. Right now I'm trying to get the code working.
Now, I know its a long post so any suggestions would be appreciated
If anyone needs screenshots just let me know and I will add them.
Thanks!
I’m currently on my phone, so this answer will be brief for now, however I can help more if required when I get home.
Two options come to mind immediately.
You could create an ArrayList called something like “basket” and add an item to the list, depending on which item’s “add to basket” button you press.
Create a custom object of your own, and use that as the shopping basket.
I am trying to make a program that reads a file chosen by the user, and after reading the file - the suffix "txt" is changed to "gif" and the file is saved as a picture (which is in the same catalogue as the file). The thing is, this picture variable gets its value in the "actionPerformed-method" and after that I want to add it to a frame in another class- but it doesn't show. Here's the code in my OptionsPane-class:
public class OptionsPane extends JComponent implements ActionListener{
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private FileHandler filehandler;
private String picture;
private JLabel picLabel;
public OptionsPane(){
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
System.out.println("hello");
option = 4;
filehandler = new FileHandler();
filehandler.read();
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
this.add(picLabel);
}
}
}
The frame is in the "MainFrame"-class, which looks like this at the moment:
public class MainFrame extends JFrame{
private JFrame frame = new JFrame();
private String picture;
private JLabel picLabel;
public MainFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
OptionsPane optionspane = new OptionsPane();
frame.add(optionspane);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
}
Why isn't the picture visible in the mainframe?
EDIT
It works now!
https://stackoverflow.com/a/22380387/3271504
Thank you for your help #arooaroo . I tried to write down some of what you wrote, but it still didn't work when I wanted to add an image based on what file the user had chosen (for example if the user chose file text1.txt i wanted the corresponding picture "text1.gif" to show up). With your help, the picture showed up when I typed a specific pathway with "/"-slashes, but when I chose a file and tried to load the picture from the file pathway, it didn't show and that is because it had backslashes in the pathways. This is how it should be (such an irritating problem):
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
filehandler = new FileHandler();
filehandler.read();
filepath = filehandler.getFilePath();
picture = filepath.replaceFirst("txt", "gif");
picture = picture.replaceAll("\\\\", "/");
ImageIcon icon = new ImageIcon(picture);
mainFrame.setPicture(icon);
}
Thank you for your help!
Once you separate your GUI code in to separate classes - which is a Good Thing - you will find the eternal challenge for GUI programming is allowing for clean communication between them where there are inter-dependencies.
In this instance perhaps the simplest approach is to pass in a reference of MainFrame into OptionsPane.
Let's assume you create an additional method in MainFrame for setting the picture:
public class MainFrame extends JFrame{
// all instance vars as before
public MainFrame() {
// same as before except for this line...
OptionsPane optionspane = new OptionsPane(this);
}
public void setPicture(JLabel pictureLabel) {
// add code here for adding the picture...
// That's an exercise for yourself, or another question ;)
}
}
Then in your OptionsPane class:
....
private MainFrame mainFrame; // add a new instance var
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
// ... rest of the code same as before
}
#Override
public void actionPerformed(ActionEvent e) {
//...
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
mainFrame.setPicture(picLabel); // <-- This is where you communicate with the mainFrame instance
//...
}
EDIT
Although my original answer provided a valid and correct solution, it's clear that the OP requires a fully working example, including the code to load display the resulting image. Here's a sample program.
public class OptionsPane extends JComponent implements ActionListener {
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private String picture;
private JLabel picLabel;
private MainFrame mainFrame;
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
// For sake of simplicity I'm ignoring the original button logic here
// and focussing on just getting an icon loaded in the parent frame...
ImageIcon icon = new ImageIcon("/path/to/test/image.png");
// Just pass the icon itself rather than a new label.
mainFrame.setPicture(icon);
}
}
public class MainFrame {
// No need to extend JFrame if you're using a JFrame instance variable
private JFrame frame = new JFrame();
private JLabel picLabel;
private JPanel mainPanel;
public MainFrame() {
mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(Color.DARK_GRAY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
OptionsPane optionspane = new OptionsPane(this);
mainPanel.add(optionspane, BorderLayout.NORTH);
picLabel = new JLabel();
picLabel.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(picLabel, BorderLayout.CENTER);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
public void setPicture(ImageIcon icon) {
picLabel.setIcon(icon);
}
public static void main(String[] args) {
new MainFrame();
}
}
Note I've done a couple of things differently. Personally I always create a JPanel and set that up as the primary layer rather and add that directly to the frame rather than messing with the rootPane. And I used the BorderLayout in this example as it's much simpler.
The other thing is to add the JLabel which is to hold the picture to the GUI in the initial set up. Then you'll see I'm only changing its icon in the setPicture() method rather than adding a new JLabel on each instance.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class FirstGui extends JFrame {
int num1;
int num2;
int num3;
//Buttons 'n' stuff
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JRadioButton button;
private JButton calculate;
private JTextField textfield1;
private JTextField textfield2;
//Buttons 'n' stuff
public static void main (String args[]) {
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(200, 200);
gui.setVisible(true);
gui.setTitle("T Calc");
}
public FirstGui(){
setLayout(new FlowLayout());
label1 = new JLabel ("Triangle Base");
add(label1);
textfield1 = new JTextField (15);
add(textfield1);
label2 = new JLabel ("Triangle Height");
add(label2);
textfield2 = new JTextField (15);
add(textfield2);
calculate = new JButton ("Calculate!");
add(calculate);
label3 = new JLabel ("Waiting for calculation...");
add(label3);
getvalue1 getvalue1 = new getvalue1();
textfield1.addActionListener(getvalue1);
getvalue2 getvalue2 = new getvalue2();
textfield2.addActionListener(getvalue2);
event event = new event();
button.addActionListener(event);
}
public class getvalue1 implements ActionListener {
public void actionPerformed(ActionEvent getvalue1){
num1 = Integer.parseInt(textfield1.getText());
}
}
public class getvalue2 implements ActionListener {
public void actionPerformed(ActionEvent getvalue2){
num2 = Integer.parseInt(textfield2.getText());
}
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent event){
num3 = 1/2 *num1*num2;
label3.setText(String.valueOf(num3));
}
}
}
So yeah, that's the code ..
here is the problem I get when I compile it:
Exception in thread "main" java.lang.NullPointerException
at FirstGui.<init>(FirstGui.java:56)
at FirstGui.main(FirstGui.java:20)
I just have no clue what is wrong..
it's really annoying and I am not sure whether it's the compiler or not... help!!!
The error is not really very helpful.
You haven't initialised button anywhere in your code. You need to do this before attempting to invoke any methods on it.
button = new JRadioButton("Your text here");
More importantly, I can't see any other place where you're using that component. You haven't added it to your frame. Did you mean to add event that to the calculate button?
I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.
I'm trying to learn Swing and JFrame, so I'm creating a really simple program that asks for your name and then displays a box telling you what you've entered.
I'm trying to use a separate class from the first to act as the ActionListener and display the name that was typed in. However it's not working for me. I tried creating a constructor in the second class that sets an instance variable to the value taken in the JTextfield but it's not showing up as I expected. Please have a look;
And here's my code (I've imported all libraries properly but omitted for space's sake)
This is the main class...
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
//setSize(300, 150);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the ActionListener class:
public class SubmitButton implements ActionListener {
String nameInput;
public SubmitButton(String textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput );
}
}
You are passing in an empty String into the ActionListener class SubmitButton when it is created and it is never updated once the text changes in the JTextField textBoxToEnterName so nothing is ever displayed.
You could pass the textBoxToEnterName JTextField to gain access to the value when required:
class SubmitButtonListener implements ActionListener {
private JTextField textfield;
public SubmitButtonListener(JTextField textfield) {
this.textfield = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame, "You've Submitted the name "
+ textfield.getText());
}
}
I think you should have the SubmitButton class as an inner class of the NamePrompt class. This way you can use the text field's variable without having to pass it along to a new class, which might complicate things.
class SubmitButton implements ActionListener {
// Do not need this
// public SubmitButton(String textfield){
// nameInput = textfield;
// }
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + textBoxToEnterName.getText());
}
But be sure to define the variables outside of the constructor so it can be used by the inner class:
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
JLabel enterYourName;
JextField textBoxToEnterName;
JPanel panelTop;
JButton submit;
JPanel panelBottom;
String name;
public NamePrompt(){ ..... (set up the variables here)
The final class would look like:
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
JLabel enterYourName;
JTextField textBoxToEnterName;
JPanel panelTop;
JButton submit;
JPanel panelBottom;
public NamePrompt(){
setLayout(new BorderLayout());
enterYourName = new JLabel("Enter Your Name Here:");
textBoxToEnterName = new JTextField(21);
panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()));
panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
//setSize(300, 150);
pack();
setLocationRelativeTo(null);
}
class SubmitButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + textBoxToEnterName.getText());
}
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
There is the problem:
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()))
To the listener you are passing a String instead of the textfield, change it to accept textfield :)
And at
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput );
}
ask the textfield current value