How do i make next button go to next Frame? GUI - java

How do I make the next button go to the next Frame in this GUI? I need to have it where I can click next to display 20 more details:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FilledFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
/*JButton button = new JButton*/
JButton nextButton = new JButton("NEXT");
JLabel label = new JLabel("Frame 1.");
JPanel panel = new JPanel();
panel.add(nextButton);
panel.add(label);
frame.add(panel);
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 100;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("A frame with two components");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

If you want to hide or show the frame, you can use like this
JFrame f1 = new JFrame("Frame 1");
JFrame f2 = new JFrame("Frame 2");
to hide f1, call f1.setVisible(false);
to show f2, call f2.setVisible(true);

A bit unclear. Do you want to move a JButton to another JFrame? I don't think you can manage that without dynamic programming or such (I guess?).
You should look through a tutorial of the Swing components from Oracle http://docs.oracle.com/javase/tutorial/uiswing/
And see your comments. I agree having multiple JFrame is a bad habit.
Edit
Use the eventlistner (see other answer) and make it follow a switch case? Then there you can make it display like a dialog or change a JLable inside your JFrame?
Dialog tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.
I think you should go with a lable and change it's text.
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListner(
private int counter = 0;
public void actionPerformed(ActionEvent e) {
counter++;
switch(counter){
case 1: somelable.setText("Your text here");
};
}));
I wrote this on free hand but I guess something like this would work?

You have to edit the codes in your next frame...
Example for your NextFrame,
public class NextFrame
public static void main(String[] args)
{
private static FilledFrameViewer parentFrame; //ADD THIS FOR CONNECTION TO FIRST FRAME
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NextFrame frame = new NextFrame(null); //CHANGES MADE HERE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
public NextFrame(FilledFrameViewer f) { //CHANGES MADE HERE
this.parentFrame = f; //CHANGES MADE HERE
setTitle("Personal Assistant");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

Ah, Yes...and also you'll have to add some things in the Next button...
Example:
btnNext = new JButton();
btnNext.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
goNext();
{
private void goNext(){
NextFrame nextframe= new NextFrame(null);
nextframe.setVisible(true);
}
}
});

Related

Java Swing: Components automatically change position when a certain component updates

I made a Java program and part of the program's function is to track the user's mouse X and Y coordinates.
The tracking works nicely but there's a small problem that bothers me.
When I move my mouse around the screen, the other components automatically change position.
Here's a MRE(Minimal Reproducible Example):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class Test {
static Timer t;
static JLabel label1;
static InnerTest inner;
static int mouseX;
static int mouseY;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
buildFrame();
runTimer();
}
});
}
public static void buildFrame() {
JFrame frame = new JFrame();
label1 = new JLabel("Test1");
JLabel label2 = new JLabel("Test Test");
JLabel label3 = new JLabel("Test Label Label");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(label2);
panel.add(label3);
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
label3.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.getContentPane().add(panel);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void runTimer() {
inner = new InnerTest();
t = new Timer(20, inner);
t.start();
}
static class InnerTest implements ActionListener {
public void actionPerformed(ActionEvent e) {
mouseX = MouseInfo.getPointerInfo().getLocation().x * 100;
mouseY = MouseInfo.getPointerInfo().getLocation().y * 100;
label1.setText(" ( "+String.valueOf(mouseX)+" , "+String.valueOf(mouseY)+" )");
}
}
}
How do I keep the components still when another component is updating?
The components are added to the same panel so each is centered based on the maximum width of all three components. As the width of the top label changes the others are also adjusted.
The solution is to separate the top label from the other two labels.
One way would be:
//panel.add(label1);
panel.add(label2);
panel.add(label3);
//label1.setAlignmentX(Component.CENTER_ALIGNMENT);
label1.setHorizontalAlignment(JLabel.CENTER); // added
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
label3.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.add(label1, BorderLayout.PAGE_START); // added
frame.getContentPane().add(panel);

Java GUI - Possible to store JPanels inside a single main JPanel?

I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png

JPanel does not appear when i try to add it to ContentPane

I'm having a problem trying to change JPanels by using buttons. I have a JFrame with 2 panels, 1 of them is for the buttons, which i want them to always be showed. The other one is the one that i will be switching everytime i press one ot the buttons of the other panel. The problem is that everytime i press them nothing really ever displays, i keep my buttons but the other panel that i call does not appear.
Code for one of the buttons is as follows
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ReparacaoPanel r = new ReparacaoPanel(this, this.jPanel1);
this.getContentPane().remove(this.jPanel1);
this.getContentPane().add(r);
//this.setContentPane(r);
this.visiblePanel.setVisible(false);
this.visiblePanel = r;
this.pack();
this.setVisible(true);
r.setLocation(200, 200);
this.getContentPane().revalidate();
this.repaint();
}
If i try to use "this.setContentPane(r);" (it sets the frame to only show the panel) the panel shows. But when i try to call it as i'm trying to do in the code above nothing is showed apart from the panel that has the buttons.
I have no idea what i'm doing wrong, it does not seem to be a problem with the JPanel that i'm trying to call as it shows if used alone.
Anyone can help me out?
Consider this working example for switching manually between panels. Which produces this output.
.........
Some tiny NumberPanel
Every new instance shows another number in the center.
import javax.swing.JPanel;
public class NumberPanel extends JPanel {
private static int counter = 0;
public NumberPanel() {
setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel = new JLabel("" + counter++);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(lblNewLabel);
}
}
Setting up a frame
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().remove(numberPanel);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
}
});
panel.add(btnNewButton);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
}
Testprogram
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestPanelSwitch {
private JFrame frame;
private NumberPanel numberPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestPanelSwitch window = new TestPanelSwitch();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestPanelSwitch() {
initialize();
}
private void initialize() {
// see above
}
}
Back to the Question
I think you only need to pack your frame, like in the anonymous ActionListener.
frame.getContentPane().remove(numberPanel);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
EDIT
As leonidas mentioned it is also possible to revalidate the frame. This requires only to replace the upper call to pack by theese.
frame.invalidate();
frame.validate();

Button Layout Issues with JFrame

Picture included I have another issue where my buttons go to the top-right after the user inputs their name. At this point, text shows up in the GUI on the LEFT side of the center which seems it would be "WEST" when I put "CENTER". Code:
public TheDungeon()
{
setTitle("InsertGameNameHere");
setSize(750, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setLocationRelativeTo(null);
buildButtonPanel();
characterInfoPanel = new JLabel("<html>Character information will go here</html>");
gameScreen = new JLabel();
inventoryPanel = new JLabel("<html>This is for the inventory</html>");
add(gameScreen, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
//Program run
userName();
gameScreen.setText("<html>Welcome "+name+", to the game that has no name!</html>");
classWindow();
}
private void buildButtonPanel()
{
// Create a panel for the buttons.
buttonPanel = new JPanel();
// Create the buttons.
b1 = new JButton("Button 1");
b2 = new JButton("Button 2");
b3 = new JButton("Button 3");
b4 = new JButton("Button 4");
b5 = new JButton("Button 5");
// Add the buttons to the button panel.
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
buttonPanel.add(b4);
buttonPanel.add(b5);
}
private void userName() {
name = JOptionPane.showInputDialog("What will your name be?");
}
I'm not sure why your program is behaving as it seems to be since when I ran it, it did not do this. You may wish to check your code to make sure that it's the code you're posting here. But regardless, I do have some suggestions:
Best to not set the sizes of anything, but rather to let the components and the layout managers do this for you.
Consider if you must overriding getPreferredSize() if you need to control the size of a component more fully.
Call pack() on your top level window after adding all components and before calling setVisible(true). This will tell the layout managers to do their things.
Avoid extending JFrame since you will rarely need to override one of its innate behaviors.
If you do add or remove components, or change their preferredSizes somehow after rendering your top-level window, you will want to call revalidate() and then repaint() on the component's container to have the container re-layout the components it holds and then redraw them.
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
public class TheDungeon2 extends JPanel {
private static final int PREF_W = 750;
private static final int PREF_H = 600;
private static final String[] BUTTON_LABELS = {"Button 1", "Button 2",
"Button 3", "Button 4", "Button 5"};
private static final String WELCOME_TEXT = "Welcome %s to the game that has no name!";
private JLabel welcomeLabel = new JLabel("", SwingConstants.CENTER);
private String name;
public TheDungeon2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (String buttonLabel : BUTTON_LABELS) {
JButton button = new JButton(buttonLabel);
buttonPanel.add(button);
}
setLayout(new BorderLayout());
add(welcomeLabel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void getAndSetName() {
name = JOptionPane.showInputDialog(this, "What will your name be?");
welcomeLabel.setText(String.format(WELCOME_TEXT, name));
}
private static void createAndShowGui() {
TheDungeon2 dungeon2 = new TheDungeon2();
JFrame frame = new JFrame("Nameless Game");
dungeon2.getAndSetName();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(dungeon2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I tested your code with an empty classWindow() method and the buttons are correctly placed in south,
for the CENTER issue, you should place something in WEST to have your text centred (even an empty panel) otherwise CENTER will take all the place,
look at this , i added this line :
add(new JButton("a button for test"),BorderLayout.WEST);
and here is the result :

Working with JFrames

hi I'm basically give up. Ok so this is what I am trying to do. So far I have written code to create a JFrame which contains a text field and combo box. The code is supposed to calculate the area of an input in the text field depending on what shape is selected from the combo box and output the result on the JFrame!
Here's is what the output should look like
And here is my code so far. it's a bit messed up but any help would be much appreciated. Thanks in advance
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
double Area;
double input;
public static void main(String[]args)
{
//Create array containing shapes
String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};
//Use combobox to create drop down menu
JComboBox comboBox=new JComboBox(shapes);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); //set frame layout
JLabel label2 = new JLabel("(select shape first)");
JTextField text = new JTextField(10); //create text field
text.setEnabled(false);
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text);
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text);
//JButton button = new JButton("GO"); //create GO button
//frame.add(button);
//set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
// public void actionPerformed(ActionEvent e)
//{
}
public void AreaCalc()
{
JButton button = new JButton("GO"); //create GO button
frame.add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int input = double.parseDouble(text.getText());
if(e.getSource() == button)
{
String shape = (String).comboBox.getSelectedItem();
if(shape == "(no shape selected)")
{
text.setEnabled(false);
}
else{
text.setEnabled(true);
}
if(input > 1 && shape == "Circle")
{
// label2.getText() = "Enter the radius of the circle: ";
Area = (Math.PI * (input * input));
}
}
else{}
}
}
);
}
}
I try to understand what you did here:
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text); // <---
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text); // <---
Especially frame.add(text); and panel1.add(text);. Don't add text to JFrame. Use JPanel.
Further,
public class AreaFrame3 extends Frame
Use public class AreaFrame3 extends JFrame so you don't need create additional JFrame:
JFrame frame=new JFrame("Area Calculator Window");
Something like:
super.setLayout(new FlowLayout()); //set layout
super.add(panel1);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.pack();
//set JFrame ssize
super.setSize(400,250);
//make JFrame visible. So we can see it
super.setVisible(true);
At last Ill give you some tamplate to start with (that will help you):
public class FrameExmpl extends JFrame{
private static final long serialVersionUID = 1L;
private JTabbedPane tabbedPane;
private JPanel topPanel;
private JTextField txtf_loadDS_;
public static int valueInt = 0; // responsible for Task status updating
public static Boolean isFinish = false;
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
FrameExmpl UI_L = new FrameExmpl();
UI_L.buildGUI();
UI_L.setVisible(true);
}
public void buildGUI(){
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(435, 225);
setLocation(285, 105);
setResizable(false);
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
txtf_loadDS_ = new JTextField();
txtf_loadDS_.setBounds(22, 22, 382, 25);
topPanel.add(txtf_loadDS_);
finishBuildGUI();
}
public void finishBuildGUI(){
tabbedPane = new JTabbedPane();
topPanel.add(tabbedPane, BorderLayout.CENTER);
}
}
There are multiple issues with this application such as extending from Frame rather than JFrame & attempting to assign an int from Double.parseDouble. I would recommend that you start again building a small but working application and incrementally add functionality, this way errors are easier to fix.

Categories

Resources