I coded a application so far so it only shows the widgets so I can see if everything is in order before I add Action Listeners and such.
The problem is when I run it, nothing shows up at all, just a blank screen.
I attached a picture of what the layout should look like. I am new to this website so apparently I cannot post any images until 10 rep. Here is a link to PhotoBucket.
http://i930.photobucket.com/albums/ad149/Wolverino5/pic_zpsa4599592.png
Here is my code so far.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Project9 extends JFrame
{
private JTextField idLabel;
private JTextField idField;
private JTextField priceLabel;
private JTextField priceField;
private JTextField numInStockLabel;
private JTextField numInStockField;
private JTextField codeLabel;
private JTextField codeField;
private JTextField transaction;
private JButton insert;
private JButton delete;
private JButton display;
private JButton displayOne;
private JButton hide;
private JButton clear;
private Container c = getContentPane();
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(650,700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Project9()
{
setTitle("BOOK DataBase Application");
c.setLayout(new FlowLayout());
Label main = new Label("Data Entry: Best Bargian Book Store");
c.add(main);
idLabel = new JTextField("Enter ID",15);
idLabel.setEditable(false);
c.add(idLabel);
idField = new JTextField();
c.add(idField);
priceLabel = new JTextField("Enter Price:",15);
priceLabel.setEditable(false);
c.add(priceLabel);
priceField = new JTextField();
c.add(priceField);
numInStockLabel = new JTextField("Enter Number In Stock:",15);
numInStockLabel.setEditable(false);
c.add(numInStockLabel);
numInStockField = new JTextField();
c.add(numInStockField);
codeLabel = new JTextField("Enter Code: 1,2,3 or 4:",15);
codeLabel.setEditable(false);
c.add(codeLabel);
codeField = new JTextField();
c.add(codeField);
insert = new JButton("Insert");
c.add(insert);
delete = new JButton("Delete");
c.add(delete);
display = new JButton("Display");
c.add(display);
displayOne = new JButton("displayOne");
c.add(displayOne);
hide = new JButton("Hide");
c.add(hide);
clear = new JButton("Clear");
c.add(clear);
Label messages = new Label ("Messages");
c.add(messages);
transaction = new JTextField();
c.add(transaction);
}
}
You never create an instance of the Project9 class, so the only four lines that run are those in main that create an empty JFrame.
Change:
JFrame frame = new JFrame();
To:
JFrame frame = new Project9();
Related
I am writing a program and am unable to figure this out but I have a JButton called nextDay and I need it set up so once I click it, it switches to the JFrame day2 as the program starts out on day1. Any help is appreciated.
Here is my code. I have a separate Main method which I wont include as it shouldn't need to be changed
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SoldierSimTest extends JFrame {
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JFrame day1;
private JFrame day2;
private JFrame day3;
private JFrame day4;
private JFrame day5;
private JFrame day6;
private JFrame day7;
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
public SoldierSimTest() {
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take
an enemy fort. How will you do so?");
situation.setEditable(false);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
JPanel situationsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 1));
situationsPanel.add(situation);
Container contentPane = getContentPane();
contentPane.add(decisionsPanel, "South");
contentPane.add(optionsPanel, "North");
contentPane.add(situationsPanel, "Center");
}
}
You can use card layout to switch panels. I used Jpanels as it seems to be the best option to use. For this example I used 2 panels.
public class SoldierSimTest extends JFrame
{
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JPanel day1Panel = new JPanel();
private JPanel day2Panel = new JPanel();
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
final static String DAY1 = "Day1";
final static String DAY2 = "Day2";
public SoldierSimTest()
{
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take an enemy fort. How will you do so?");
situation.setEditable(false);
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel situationsPanel = new JPanel();
situationsPanel.add(situation);
day1Panel.setLayout(new GridLayout(2, 1));
day1Panel.add(situationsPanel);
day1Panel.add(decisionsPanel);
JPanel cards = new JPanel(new CardLayout());
cards.add(day1Panel, DAY1);
cards.add(day2Panel, DAY2);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
nextDay.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, DAY2);
}
});
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
Container contentPane = getContentPane();
contentPane.add(optionsPanel, "North");
contentPane.add(cards, "Center");
}
}
The best way to do this if you don't necessarily need a new JFrame is the way #pavithraCS described. What I want to add is that normally, when you want a new "window" with different components to appear, you don't use a new JFrame because that opens a new window. Instead, using a new JPanel is more useful because you can stack them without having to switch to another window.
I hope this helps for the future.
I have a simple form consisting of 3 text fields and a cancel/ok button. This is in a GroupLayout. I'd like to know how to make this form pop up in a new window similar to a dialog? Can I pass my GroupLayout to a JDialog? I also need to validate the input before the form window closes. I currently have this working but it uses a new frame to do so and I've read that this is not the way to do it so I am asking here.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.*;
public class AddStockPromptTest {
private JFrame frame;
private JPanel mainPanel;
private JPanel formPanel;
private JPanel buttonPanel;
//private GroupLayout layout;
private JLabel lblItem;
private JLabel lblPrice;
private JLabel lblQuantity;
private JTextField itemField;
private JTextField priceField;
private JTextField quantityField;
private JButton okBtn;
private JButton cancelBtn;
public AddStockPromptTest() {
frame = new JFrame("Add New Stock Item");
//Container contentPane = frame.getContentPane();
mainPanel = new JPanel(new BorderLayout());
buttonPanel = new JPanel(new FlowLayout());
formPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(formPanel);
formPanel.setLayout(groupLayout);
groupLayout.setAutoCreateGaps(true);
lblItem = new JLabel("Item:");
lblPrice = new JLabel("Price:");
lblQuantity = new JLabel("Quantity:");
itemField = new JTextField();
priceField = new JTextField();
quantityField = new JTextField();
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup()
.addComponent(lblItem)
.addComponent(lblPrice)
.addComponent(lblQuantity))
.addGroup(groupLayout.createParallelGroup()
.addComponent(itemField)
.addComponent(priceField)
.addComponent(quantityField))
);
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblItem)
.addComponent(itemField))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblPrice)
.addComponent(priceField))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblQuantity)
.addComponent(quantityField))
);
cancelBtn = new JButton("Cancel");
buttonPanel.add(cancelBtn);
okBtn = new JButton("OK");
buttonPanel.add(okBtn);
mainPanel.add(formPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
frame.add(mainPanel);
frame.setTitle("Basil's Pizza Ordering System");
frame.setSize(800, 600);
frame.pack();
frame.setVisible(true);
//addStockPrompt();
}
private void addStockPrompt() {
}
}
JOptionPane will give you a dialog box. Use this in actionperformed event of your okay button.
JOptionPane.showMessageDialog(null, message);
I'm trying to create a image JButton clickable and display text once it has been clicked, but I can not seem to figure out how to make it work. I am very new to java so plenty of basic explanations would be very helpful to me. here is the code I am currently working with.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class States extends JFrame {
private JTabbedPane jtpFigures = new JTabbedPane();
//State Labels
private JButton VTPanel = new JButton();
frame.add(VTPanel);
VTPanel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent);
System.out.println("The State Capital of VT is Montpelier");
}
private JButton NYPanel = new JButton();
private JButton CAPanel = new JButton();
private JButton MEPanel = new JButton();
private JButton NHPanel = new JButton();
private JButton CTPanel = new JButton();
private JButton MAPanel = new JButton();
private JButton FLPanel = new JButton();
private JButton HIPanel = new JButton();
private JButton NDPanel = new JButton();
//Images for each of the states
private ImageIcon[] stateImage = {
new ImageIcon("image/VT.png"),
new ImageIcon("image/NY.png"),
new ImageIcon("image/CA.png"),
new ImageIcon("image/ME.png"),
new ImageIcon("image/NH.png"),
new ImageIcon("image/CT.png"),
new ImageIcon("image/MA.png"),
new ImageIcon("image/FL.png"),
new ImageIcon("image/HI.png"),
new ImageIcon("image/ND.png")};
public States() {
//adds each of the images to the panel
VTPanel.setIcon(stateImage[0]);
NYPanel.setIcon(stateImage[1]);
CAPanel.setIcon(stateImage[2]);
MEPanel.setIcon(stateImage[3]);
NHPanel.setIcon(stateImage[4]);
CTPanel.setIcon(stateImage[5]);
MAPanel.setIcon(stateImage[6]);
FLPanel.setIcon(stateImage[7]);
HIPanel.setIcon(stateImage[8]);
NDPanel.setIcon(stateImage[9]);
//Adds the panels and name
add(jtpFigures, BorderLayout.CENTER);
jtpFigures.add(VTPanel, "Vermont");
jtpFigures.add(NYPanel, "New York");
jtpFigures.add(CAPanel, "California");
jtpFigures.add(MEPanel, "Maine");
jtpFigures.add(NHPanel, "New Hampshire");
jtpFigures.add(CTPanel, "Connecticut");
jtpFigures.add(MAPanel, "Massachusetts");
jtpFigures.add(FLPanel, "Florida");
jtpFigures.add(HIPanel, "Hawaii");
jtpFigures.add(NDPanel, "North Dakota");
//Sets the default index
jtpFigures.setSelectedIndex(3);
}
public static void main(String[] args) {
States frame = new States();
frame.pack();
frame.setTitle("State License Plates");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(560,250);
}
}
You will need to add a actionlistener to your button. There is a good reference here:
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
What I am trying to do is organize five seperate JPanel's within the frame. Here is what the output is supposed to look like: There will be one panel across the top. Two panels directly below the top panel that vertically split the space and then another two panels that split the remaining space horizontally.
I cannot figure out how to organize the panels like described above and I think it is because I just don't know the proper syntax. So any help or advise is greatly appreciated here is the code I have thus far.
import java.lang.String.*;
import java.lang.Exception.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener{
// instance variables
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 150;
private static final int BUTTON_WIDTH = 90;
private static final int BUTTON_HEIGHT = 30;
private JButton readFile;
private JButton exit;
private JButton stats;
private JButton blank;
private JCheckBox avgHomeworkScore;
private JCheckBox avgTestScore;
private JCheckBox sdHomeworkScore;
private JCheckBox sdTestScore;
private JRadioButton buttonOne;
private JRadioButton buttonTwo;
private JRadioButton buttonThree;
private JRadioButton buttonFour;
private JPanel header;
private JPanel statistics;
private JPanel courses;
private JPanel display;
private JPanel action;
public static void main(String[] args){
Display frame = new Display();
frame.setVisible(true);
}
public Display(){
Container contentPane;
//Set the frame properties
setSize (FRAME_WIDTH, FRAME_HEIGHT);
setResizable (false);
setTitle ("CSCE155A Course Offerings Viewer");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new GridLayout());
contentPane.setBackground( Color.white );
//header
//Create and Place the Buttons on the frame
readFile = new JButton("Read File");
readFile.setBounds(4, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
exit = new JButton("Exit");
exit.setBounds(100, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
stats = new JButton("Stats");
stats.setBounds(195, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
blank = new JButton("Clear");
blank.setBounds(290, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
action = new JPanel(new FlowLayout());
action.setBackground(Color.blue);
action.add(readFile);
action.add(exit);
action.add(stats);
action.add(blank);
contentPane.add(action);
//Register this frame as an Action listener of the buttons
readFile.addActionListener(this);
exit.addActionListener(this);
stats.addActionListener(this);
blank.addActionListener(this);
//Create and Place the checkboxes on the frame
avgHomeworkScore = new JCheckBox();
avgHomeworkScore.setMnemonic(KeyEvent.VK_H);
contentPane.add(avgHomeworkScore);
avgHomeworkScore.setSelected(true);
avgTestScore = new JCheckBox();
avgTestScore.setMnemonic(KeyEvent.VK_T);
avgTestScore.setSelected(true);
sdHomeworkScore = new JCheckBox();
sdHomeworkScore.setMnemonic(KeyEvent.VK_S);
sdHomeworkScore.setSelected(true);
sdTestScore = new JCheckBox();
sdTestScore.setMnemonic(KeyEvent.VK_D);
sdTestScore.setSelected(true);
statistics = new JPanel(new GridLayout(0,1));
contentPane.add(statistics);
statistics.add(avgHomeworkScore);
statistics.add(avgTestScore);
statistics.add(sdHomeworkScore);
statistics.add(sdTestScore);
avgHomeworkScore.addActionListener(this);
avgTestScore.addActionListener(this);
sdHomeworkScore.addActionListener(this);
sdTestScore.addActionListener(this);
//create the radio buttons
buttonOne = new JRadioButton();
buttonOne.setMnemonic(KeyEvent.VK_1);
buttonOne.setSelected(true);
buttonTwo = new JRadioButton();
buttonTwo.setMnemonic(KeyEvent.VK_2);
buttonThree = new JRadioButton();
buttonThree.setMnemonic(KeyEvent.VK_3);
buttonFour = new JRadioButton();
buttonFour.setMnemonic(KeyEvent.VK_4);
ButtonGroup group = new ButtonGroup();
group.add(buttonOne);
group.add(buttonTwo);
group.add(buttonThree);
group.add(buttonFour);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
courses = new JPanel(new GridLayout(0,1));
courses.setBackground(Color.blue);
courses.add(buttonOne);
courses.add(buttonTwo);
courses.add(buttonThree);
courses.add(buttonFour);
contentPane.add(courses);
//Exit program when the viewer is closed
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Use a layout manager. Never set the bounds, sizes and locations of your panels and other components. That's the job of the layout manager. Layout managers are explained in details in the Swing tutorial (as everything else, BTW).
You could use a BorderLayout for the main panel, and another for the bottom panel, for example.
The idea is there are 5 JButtons on the top of the screen. Every time you press one it removes the old menu and produces a new one. To me, my code looks fine. The problem is when i click on "Add CD" nothing happens, but then if i manually resize the window (moving my mouse to the edge of the window and changing the size of it) the new menu pops up... Can anyone give me advice on how to fix this problem... Thanks, the whole runnable code is below.
package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class mainInterface extends JFrame implements ActionListener
{
// Variables declaration - do not modify
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
private JButton jButton4;
private JButton jButton5;
private JButton jButton6;
private JPanel jPanel1;
private JTextField text1;
private JTextField text2;
private JTextField text3;
private JTextField text4;
private JTextField text5;
private JTextField text6;
private JTextField text7;
private JTextField text8;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JLabel label7;
private JLabel label8;
private JPanel bottomPanel;
private JPanel topPanel; // declaring panels
private JPanel holdAll;
private JPanel one;
private JPanel two;
private JPanel three;
private JPanel four;
//----------------------------------------------------------
//----------------------------------------------------------
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
mainInterface myApplication = new mainInterface();
myApplication.setLocation(100, 100);
myApplication.setSize(700, 400);
myApplication.setTitle("Kevin's Jukebox");
myApplication.setVisible(true);
}
});
}
//----------------------------------------------------------
//----------------------------------------------------------
/** Creates new form mainInterface */
public mainInterface()
{
jButton1 = new JButton("Add CD");
jButton2 = new JButton("Add Video");
jButton3 = new JButton("Total Play Time");
jButton4 = new JButton("Create Playlist");
jButton5 = new JButton("Show Library");
jButton6 = new JButton("Quit");
topPanel = new JPanel();
holdAll = new JPanel();
bottomPanel = new JPanel();
one = new JPanel();
two = new JPanel();
three = new JPanel();
four = new JPanel();
text1 = new JTextField(15);
label1 = new JLabel("Title: ");
text2 = new JTextField(15);
label2 = new JLabel("Artist: ");
text3 = new JTextField(15);
label3 = new JLabel("Length: ");
text4 = new JTextField(15);
label4 = new JLabel("Num of Tracks: ");
label5 = new JLabel("Welcome to Kevins Jukebox");
int flag = 0;
drawApp(flag);
jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
//----------------------------------------------------------
//----------------------------------------------------------
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
int flag = 1;
drawApp(flag);
}
}
//----------------------------------------------------------
//----------------------------------------------------------
public void drawApp(int flag)
{
topPanel.setLayout(new FlowLayout());
topPanel.add(jButton1);
topPanel.add(jButton2);
topPanel.add(jButton3);
topPanel.add(jButton4);
topPanel.add(jButton5);
topPanel.add(jButton6);
bottomPanel.add(label5);
holdAll.setLayout(new BorderLayout());
holdAll.add(topPanel, BorderLayout.NORTH);
holdAll.add(bottomPanel, BorderLayout.CENTER);
if (flag == 0)
bottomPanel.add(label5);
else
bottomPanel.remove(label5);
if (flag == 1)
{
one.add(label1);
one.add(text1);
bottomPanel.add(one);
two.add(label2);
two.add(text2);
bottomPanel.add(two);
three.add(label3);
three.add(text3);
bottomPanel.add(three);
four.add(label4);
four.add(text4);
bottomPanel.add(four);
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
}
getContentPane().add(holdAll, BorderLayout.CENTER); // places everything on the frame
}
//----------------------------------------------------------
}
Execute this.validate() after you update the UI's layout. Calling this method tells the UI to relayout its components.