Java Swing Tabs with multiple panels [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
is it possible to create a (new)panel inside a tab when you press a button inside the (current)panel?So that the layout is different to the (current) panel? For example the button is just "next".
i can't find anything on google, i have the feeling that my approach is not possible. I tried to illustrate it which a picture but i don't have enough points.

Yes this is definitely possible as Tim B described using a CardLayout. Take a look and maybe this example will help out a bit.
public class JavaApplication2 extends JFrame {
private JPanel mainPanel, cpOne, cpTwo;
private JButton btnContine, btnGoBack;
private CardLayout c1;
public JavaApplication2()
{
super("Card Layout");
mainPanel = new JPanel(new CardLayout());
mainPanel.add(cardOne(), "card1");
mainPanel.add(cardTwo(), "card2");
c1 = (CardLayout) (mainPanel.getLayout());
add(mainPanel);
setSize(200,200);
setVisible(true);
btnContine.addActionListener((ActionEvent e) -> {
c1.show(mainPanel,"card2");
});
btnGoBack.addActionListener((ActionEvent e) -> {
c1.show(mainPanel,"card1");
});
}
private JPanel cardOne()
{
cpOne = new JPanel();
btnContine = new JButton("Next Panel");
cpOne.add(btnContine);
cpOne.add(new JLabel("First Panel"));
return cpOne;
}
private JPanel cardTwo()
{
cpTwo = new JPanel();
btnGoBack = new JButton("Previous Panel");
cpTwo.add(btnGoBack);
cpTwo.add(new JLabel("SECOND PANEL!!!"));
return cpTwo;
}
public static void main(String[] args) {
JavaApplication2 jp = new JavaApplication2();
}
}
If you look at my example we are just creating a frame and adding one main panel to this frame. To that main panel we are setting a CARD LAYOUT as the layout manager. From here we can add as many cards as our heart desires! So there are just some little methods to make our panels with buttons. We add them to the main panel as mainPanel.add(cardOne,"card1") by showing the method as what to add as the card and then naming it card1. When we run the above program you get something like this:
and after clicking the button we get this:

Yes, you can easily do this. Use a CardLayout, place all the panels you want inside that layout, and then switch between them when they press the button.
See this for more information: https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

Related

How do I transfer a Java console program into a window application? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've been looking but have not been able to find something in simple enough terms for me to understand. I currently have a program running on a java console, and I make options available through text. I now want to make this into a window program that uses buttons instead of a text option.
I found info on how to create a JFrame, but I am having issues finding info on how to make a button that calls a method, and have text that changes to show updates.
Any links or info would be much appreciated, I dont know where to go and any nudge is a help!
You can put something like the following code into your "public static void main(String[] args)" method.
JFrame frmMain = new JFrame(); // Create our JFrame
// Set the layout for main frame. This controls how things get arranged on the screen
frmMain.setLayout(new BorderLayout());
// panels are what you put everything else on
JPanel panel1 = new JPanel(new FlowLayout()); // another layout
JPanel panel2 = new JPanel();
BoxLayout box = new BoxLayout(panel2, BoxLayout.PAGE_AXIS); // another layout
panel2.setLayout(box);
// here are a couple of buttons
JButton btnAdd = new JButton("Add");
JButton btnRemove = new JButton("Remove");
// here are a couple of textboxes. They accept typed in information
JTextField txtFirstName = new JTextField();
JTextField txtMiddleInitial = new JTextField();
JTextField txtLastName = new JTextField();
// add our buttons to panel1. It has a FlowLayout, so they will be centered left to right as we add them
panel1.add(btnAdd);
panel1.add(btnRemove);
// Create a panel to hold First Name
JPanel pnlFirstName = new JPanel(new BorderLayout()); // also set its layout
// here we add a JLabel.class they just display text, they don't allow input
pnlFirstName.add(new JLabel("first name"), BorderLayout.WEST);
// here we put our text box onto the First name panel
pnlFirstName.add(txtFirstName, BorderLayout.CENTER);
// repeat for middle initial panel
JPanel pnlMiddleInitial = new JPanel(new BorderLayout());
pnlMiddleInitial.add(new JLabel("M.I."), BorderLayout.WEST);
pnlMiddleInitial.add(txtMiddleInitial, BorderLayout.CENTER);
// repeat for last name panel
JPanel pnlLastName = new JPanel(new BorderLayout());
pnlLastName.add(new JLabel("last name"), BorderLayout.WEST);
pnlLastName.add(txtLastName, BorderLayout.CENTER);
// put a 3 pixel border arounnd panel 2 to keep things away from the edge
panel2.setBorder(new EmptyBorder(3, 3, 3, 3));
// add all of our input panels to panel 2, according to BoxLayout (up above)
panel2.add(pnlFirstName);
panel2.add(pnlMiddleInitial);
panel2.add(pnlLastName);
// add panel1 and panel2 to the Frame. You have to add to the .getContentPane(), or you might mess things up.
frmMain.getContentPane().add(panel1, BorderLayout.NORTH);
frmMain.getContentPane().add(panel2, BorderLayout.CENTER);
// This is how we tell the program what to do when the user presses the "Add" button.
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("My First Name");
}
});
// This is how we tell the program what to do when the user presses the "Remove" button.
btnRemove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("");
}
});
// pack just makes everything take up it's proper space on the screen in as tight of a package as possible
frmMain.pack();
// if you don't set visible to true, you won't see your Frame
frmMain.setVisible(true);
// what to do when the user clicks the "X" to close or used "Close" from the context menu
frmMain.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Go to bellow link here is the full example how to use button in java using Frame.
Here you got all the details about the Example.
http://www.javatpoint.com/java-jbutton
write your code in actionPerformed() method which you want to do on button click.
going to file menu and export your project in runnable JAR file
than you have a jar file to start in windows

Is it possible to apply FlowLayout to a JButton within a JFrame? [duplicate]

This question already has answers here:
how to reposition JButton on resizing the window
(3 answers)
Closed 6 years ago.
I was completing an assignment for my Java II class and I wanted to position the button underneath the labels in the JFrame. I tried:
button.setLayout(new FlowLayout());
as well as:
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
button.setLayout(flow);
and neither affected the position of the button. Positioning the button wasn't required for the assignment so perhaps I am just complicating things for myself, I just thought it would look better centered.
You should Create an JPanel, then set a layout to the JPanel and then add the buttons you need to that panel, and then add that JPanel to the JFrame so you can change the layout of the buttons with affecting the rest of the components.
public class ControlPanel extends JPanel {
private JButton stop_jb;
private JButton start_jb;
public ControlPanel() {
initComponents();
}
private void initComponents() {
//this.setLayout(new GridLayout(0, 2));
this.setLayout(new FlowLayout());
stop_jb = new JButton("Stop");
stop_jb .setVisible(true);
stop_jb .setActionCommand("stop");
this.add(stop_jb );
start_jb = new JButton("Start");
start_jb .setVisible(true);
start_jb .setActionCommand("Start");
this.add(start_jb );

Java JComboBox glitching graphics [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Basically, the problem is that when I either click or hover the mouse over a JComboBox my program's appearance gets all glitched.
Here is how my program look like right after I load it (how it should always look):
And here is what happens after a while of clicking one of the JComboBox'es a few times:
I was researching around for similar problems, and in this page someone was suggesting not to use absolute positioning; but I am not doing that in my program so I'm out of ideas.
Here is the the part of my code where I construct the layout and combo-boxes for my program, which goes in the constructor of my class, and which I launch from main by using: EventQueue.invokeLater(() -> new DownloadCalculator());.
<EDIT: Code replaced with a runnable example. See update #1 below.>
UPDATE 1:
Here is a runnable demo to illustrate the problem. The exact same problem will occur with the combo boxes after a while of fiddling with them. Only the code necessary to reproduce the glitch is included, the functional part that does the main calculations has been removed because it is unrelated to the problem:
import java.awt.*;
import javax.swing.*;
public class RunnableExample
{
private final JFrame mainframe;
private JTextField downloadSize, downloadSpeed, answerBox;
private JComboBox<String> byteTypeSize, byteTypeSpeed, answerTimeUnit;
public RunnableExample()
{
mainframe = new JFrame("Download Calculator");
mainframe.setLayout(new BoxLayout(mainframe.getContentPane(), BoxLayout.Y_AXIS));
mainframe.setSize(new Dimension(600, 300));
mainframe.setResizable(false);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setLocationRelativeTo(null);
initLook();
mainframe.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> new RunnableExample());
}
private void calculateDownloadTime(String size, int sizeUnitType, String speed,
int speedUnitType)
{
return; // program's core logic goes here
}
private void initLook()
{
JPanel subLine1 = new JPanel(), subLine2 = new JPanel(), subLine3 = new JPanel();
JLabel question1 = new JLabel("File size to be downloaded:");
downloadSize = new JTextField(10);
byteTypeSize = new JComboBox<>(new String[]{"Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"});
byteTypeSize.setSelectedIndex(3);
JLabel question2 = new JLabel("Average download speed:");
downloadSpeed = new JTextField(10);
byteTypeSpeed = new JComboBox<>(new String[]{"Bytes / s", "Kilobytes / s", "Megabytes / s", "Gigabytes / s", "Terabytes / s"});
byteTypeSpeed.setSelectedIndex(1);
JButton buttonCalc = new JButton("Calculate");
answerTimeUnit = new JComboBox<>(new String[]{"Seconds", "Minutes", "Hours", "Days"});
answerTimeUnit.setSelectedIndex(2);
buttonCalc.addActionListener((e) -> new Thread(() -> calculateDownloadTime(downloadSize.getText(), byteTypeSize.getSelectedIndex(), downloadSpeed.getText(), byteTypeSpeed.getSelectedIndex())).start());
answerBox = new JTextField("Hit \"Calculate\" button to see answer here.", 25);
answerBox.setEnabled(true);
subLine1.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine2.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine3.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine1.add(question1);
subLine1.add(downloadSize);
subLine1.add(byteTypeSize);
subLine2.add(question2);
subLine2.add(downloadSpeed);
subLine2.add(byteTypeSpeed);
subLine3.add(answerBox);
subLine3.add(answerTimeUnit);
subLine3.add(buttonCalc);
mainframe.getContentPane().add(subLine1);
mainframe.getContentPane().add(subLine2);
mainframe.getContentPane().add(subLine3);
mainframe.pack();
}
}
UPDATE 2:
It seems the graphics work fine as long as I don't click/change any of the combo-boxes. As soon as I click on any of the combo-boxes and then move the mouse outside the area of the combo-box I clicked, then it starts painting those weird glitched graphics. From the feedback I've received, it seems this problem might be platform-specific.
UPDATE 3:
I thought I would share what I found in the end so others with similar problems can try it too: After reinstalling Java and rebooting, the problem seems to have gone away. Thanks to everyone who suggested this and all the other suggestions too!

How do you make an input that is entered in a textfield in the first jframe appear on a jlabel on another jframe? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
jframe 1: the user will input the information that is asked on the text fields and when they click the get started button, the input should show in another jframe.
jframe 2: the information that was inputted in the text fields on jframe1 should appear on the jlabels.
Is it considered good practice to use two multiple frames? NO
Are there alternatives to using two frames? Yes
What are the alternatives? CardLayout, modal JDialog, among others
Will I still help you solve this query? Sure, why not?
Have an instance of the second frame in the first frame. Pass the information to the second JFrame constructor. It's that simple.
public class Frame1 extends JFrame {
String text1;
String text2;
Frame2 frame2; <--- second frame
....
public void actionPerformed(ActionEvent e) {
text1 = textField1.getText();
text2 = textField2.getText();
frame2 = new Frame2(text1, text2);
}
}
public class Frame2 extends JFrame {
String text1;
String text2;
public Frame2(String text1, String text2){
this.text1 = text1;
this.text2 = text2;
}
}
When the second frame is instantiated in the actionPerformed, It will make the second frame appear. It is also being passed the information from the text fields. You may also want to dispose of the first frame.
A modal JDialog is just as easy to make as a JFrame it's the same structure. Only difference is you can set it up to be modal (meaning nothing else that it not the JDialog) can be accessed. See this answer to see hoe to set up a JDialog for a login
Here's a very simple program using a JDialog with your requirements
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JDialogDemo {
MyDialog dialog;
JLabel label;
JFrame frame;
public JDialogDemo() {
label = new JLabel(" ");
frame = new JFrame("Hello World");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
dialog = new MyDialog(frame, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new JDialogDemo();
}
});
}
class MyDialog extends JDialog {
private JButton button = new JButton("Submit");
private JTextField jtf1;
private JTextField jtf2;
public MyDialog(final Frame frame, boolean modal) {
super(frame, true);
jtf1 = new JTextField(15);
jtf2 = new JTextField(15);
add(button, BorderLayout.SOUTH);
add(jtf1, BorderLayout.CENTER);
add(jtf2, BorderLayout.NORTH);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text1 = jtf1.getText();
String text2 = jtf2.getText();
label.setText(text1 + " " + text2);
dispose();
frame.revalidate();
frame.repaint();
frame.setVisible(true);
}
});
pack();
setVisible(true);
}
}
}
It should be fairly easy to follow. Let me know if you have any questions about it
If jframe 1 call jframe 2, then u can create a constructor in jframe 2, and pass this values.
Or you can do that by haveing a object contains jframe 1, then get in the second frame, get them by getter methods.
But for a good practice you should use single jframe and dialogs.
JFrame frame1 = new JFrame("frame1");
JPanel panel = new JPanel();
final JTextField textField = new JTextField("Text Here");
JButton button = new JButton("Copy label to other frame");
panel.add(textField);
panel.add(button);
frame1.add(panel);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setLocationByPlatform(true);
frame1.setVisible(true);
JFrame frame2 = new JFrame("frame2");
final JLabel label2 = new JLabel("Label 2 Text");
frame2.add(label2);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.pack();
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label2.setText(textField.getText());
}
});
Of course, your question isn't worded very well to show what you're really trying to accomplish or better yet, what you've already tried. Nevertheless, this code does what your specifications ask for.
If you want to put on jlabels the text that the user has inputted, you must create first the jframe1, and then jframe1 will create jframe2 passing it the text. The jframe2 will create the jlabels setting the text in the constructor.
If you want that jframe1 desappears, I think you can't close it (because if you close it, like jframe1 created jframe2, this one will be closed too). You can hide the jframe1 setting it as not visible when the user has clicked the get started button.
jframe1.setVisible(false);

Move from a frame to a frame in Swing [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Unfortunately, our team leader has decided that we'll use Swing for this light desktop app. I have no previous experience in working with Swing. I will be working on the GUI side of the project. I've already created a frame with elements within it and wrote the logic in the event listeners. Now I want to redirect the user to a new frame after he's logged in.
How do I do that? Thanks
P.S. I'd appreciate if you could point me to a good tutorial for beginners
It sounds like you have your terminology mixed up. When we hear "Frame" we think JFrame which is equivalent to "Window". So most of the time we'd recommend not using multiple windows, but changing the content of the window. The content is generally made with a "JPanel".
So generally, you set up your JFrame, you set the content with this:
JPanel loginPanel = new JPanel();
frame.setContentPane(loginPanel);
If you want to replace your login panel with a new panel, just pass the new panel to that function:
JPanel mainMenuPanel = new JPanel();
frame.setContentPane(mainMenuPanel);
(of course you want some content in those panels)
Here's a simple example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelRetriever{
Box panel1;
JPanel panel2;
public PanelRetriever(final JFrame frame){
//Build the first login panel
panel1 = Box.createVerticalBox();
panel1.setBackground(Color.orange);
panel1.setOpaque(true);
panel1.add(Box.createVerticalGlue());
panel1.add(new JTextField(10));
JButton login = new JButton("Login");
login.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setContentPane(getPanel2());
frame.validate();
}});
panel1.add(login);
panel1.add(Box.createVerticalGlue());
//Build second panel
panel2 = new JPanel();
panel2.setBackground(Color.blue);
panel2.setOpaque(true);
JButton logout = new JButton("Logout");
logout.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(getPanel1());
frame.validate();
}});
panel2.add(logout, BorderLayout.CENTER);
}
public Container getPanel1(){
return panel1;
}
public Container getPanel2(){
return panel2;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
PanelRetriever pr = new PanelRetriever(frame);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(pr.getPanel1());
frame.setPreferredSize(new Dimension(500, 400));
frame.pack();
frame.setVisible(true);
}
});
}
}
Your frame should stay the same, just create and show new JPanel instead old one.
See below JPanel painting process:
As #Gilbert Le Blanc has pointed out (+1 to him). In Swing it is bad practice to use multiple JFrames.
To accomplish what you want:
Use CardLayout which allows dynamic switching of components
Or use JFrame#removeAll() and add a new JPanel (+1 Fess)
Try using JDialog/JOptionPane and then redirect to main JFrame
here is a good link on the topic: How to Make Dialogs
In Swing, you have one JFrame. You use JDialogs to get user id and password input from the user.
Here's a link to the Oracle Swing Tutorial.
You can just create a new frame in much the same way as you already have;
MyFrame f = new MyFrame(); //MyFrame extends javax.swing.JFrame
And then bring it to the front with;
f.setVisible(true);
f.toFront();

Categories