I've written this:
JButton saveButton = new JButton(saveAction);
How do I then call it so that it displays within the window? (I've already got the code for the window, I just don't know how to call it so it shows)
saveButton.setVisible(true);
your_window.add(saveButton);
Thats all.
Firstly you should create some ContentPane for window (I guess you mean JFrame). Adding a button directly to window is not a good idea :P Next you can add your button to that pane:
panel.addComponent(button);
The last thing to do is:
frame.setContentPane(panel)
And that's all :P Just in a nutshell ;)
Use something like this
public class MainWindow extends JFrame {
public static void main(String[] args) {
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
public MainWindow() throws IOException {
setTitle("Conveyor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 851, 515);
contentPane = new JPanel();
JButton refreshButton = new JButton("refresh");
contentPane.add(refreshButton, BorderLayout.EAST);
}
}
Related
As an improvement to my encryption project I decided to make a little GUI. However, when I run the program, only the top element shows up on the screen and it appears to obscure the others, though I have no way of checking. Does anyone know why?
Below is my code in its entirety besides e() and d() because those simply encrypt a string and have nothing to do with a GUI. I would also like a way to speed it up as much as possible without editing the encryption, just to make it as great as possbile.
#SuppressWarnings("serial")
public class EncDecExample extends JFrame implements ActionListener {
final static JPanel top = new JPanel();
final static JPanel mid = new JPanel();
final static JPanel bot = new JPanel();
final static JTextField in = new JTextField(10);
final static JTextField out = new JTextField(10);
final static JButton enc = new JButton("Encrypt");
final static JButton dec = new JButton("Decrypt");
final static JFrame f = new JFrame("Encryption/decryption");
public static void main(String[] args) {
// EncDec.exampleImplement();
f.setSize(500, 500);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
out.setEditable(false);
out.setText("Hello");
in.setVisible(true);
out.setVisible(true);
enc.setVisible(true);
dec.setVisible(true);
top.add(in);
mid.add(enc);
mid.add(dec);
bot.add(out);
f.add(top);
f.add(mid);
f.add(bot);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enc && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.e(in.getText(), 5));
}
else if(e.getSource() == dec && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.d(in.getText()));
}
}
}
The content pane of a JFrame has a BorderLayout. If you place a component in a BL with no constraints it ends up in the CENTER. The center can only display one component.
For an immediate effect, I suggest:
f.add(top, BorderLayout.PAGE_START);
f.add(mid);
f.add(bot, BorderLayout.PAGE_END);
Other points.
Take out f.setSize(500, 500); and call pack() immediately before setVisible(true)
For a better way to end the GUI, change f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
in.setVisible(true); Except for the frame itself, take these out. A component automatically becomes visible when it is added to a top level container and that container is itself made visible.
Change public class EncDecExample extends JFrame to public class EncDecExample This code keeps a reference to a frame, and that is the right way to go.
I'm a complete beginner to Java, and I'm finding some answers a bit too technical for me (even the most basic tutorials seem to give me syntax errors when I run the code). How, in really simple terms do I add a JButton to a JFrame? I've got as far as:
import javax.swing.JButton;
import javax.swing.JFrame;
public class JF {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
/*some pretty basic code to initialize the JFrame i.e.
myFrame.setSize(300, 200);
This is as far as I got
*/
}
}
I would seriously appreciate some help!
Creating a new JFrame
The way to create a new instance of a JFrame is pretty simple.
All you have to do is:
JFrame myFrame = new JFrame("Frame Title");
But now the Window is hidden, to see the Window you must use the setVisible(boolean flag) method. Like this:
myFrame.setVisible(true);
Adding Components
There are many ways to add a Component to a JFrame.
The simplest way is:
myFrame.getContentPane().add(new JButton());//in this case we are adding a Button
This will just add a new Component that will fill the JFrame().
If you do not want the Component to fill the screen then you should either make the ContentPane of the JFrame a new custom Container
myFrame.getContentPane() = new JPanel();
OR add a custom Container to the ContentPane and add everything else there.
JPanel mainPanel = new JPanel();
myFrame.getContentPane().add(mainPanel);
If you do not want to write the myFrame.getContentPane() every time then you could just keep an instance of the ContentPane.
JPanel pane = myFrame.getContentPane();
Basic Properties
The most basic properties of the JFrame are:
Size
Location
CloseOperation
You can either set the Size by using:
myFrame.setSize(new Dimension(300, 200));//in pixels
Or packing the JFrame after adding all the components (Better practice).
myFrame.pack();
You can set the Location by using:
myFrame.setLocation(new Point(100, 100));// starting from top left corner
Finally you can set the CloseOperation (what happens when X is pressed) by
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
There are 4 different actions that you can choose from:
DO_NOTHING_ON_CLOSE //Nothing happens
HIDE_ON_CLOSE //setVisible(false)
DISPOSE_ON_CLOSE //Closes JFrame, Application still runs
EXIT_ON_CLOSE //Closes Application
Using Event Dispatch Thread
You should initialize all GUI in Event Dispatch Thread, you can do this by simply doing:
class GUI implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new GUI());
}
#Override
public void run() {
JFrame myFrame = new JFrame("Frame Title");
myFrame.setLocation(new Point(100, 100));
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
myFrame.getContentPane().add(mainPanel);
mainPanel.add(new JButton("Button Text"), BorderLayout.CENTER);
myFrame.pack();
myFrame.setLocationByPlatform(true);
myFrame.setVisible(true);
}
}
//I hope this will help
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
public class JF extends JFrame
{
private JButton myButton;//Here you begin by declaring the button
public JF()//Here you create you constructor. Constructors are used for initializing variable
{
myButton = new JButton();//We initialize our variable
myButton.setText("My Button"); //And give it a name
JPanel panel1 = new JPanel();//In java panels are useful for holding content
panel1.add(myButton);//Here you put your button in the panel
add(panel1);//This make the panel visible together with its contents
setSize(300,400);//Set the size of your window
setVisible(true);//Make your window visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
JFrame frame = new JF();
frame.setTitle("My First Button");
frame.setLocation(400,200);
}
}
I have created a JScrollPane with a JPanel inside it and I want to add JPanel/JLabel/Other objects after pressing the button. For example after three button presses I want to get something like this:
I tried myJPane.add(testLabel) with testlabel.setBounds()but no result, I don't want to use GridLayout because of the unchangeable sizes. I would like it if the added objects had different sizes - adjusted to the text content.
What should I use for it and how?
Thanks in advance.
Best regards,
Tom.
Here is a JPanel inside a JScrollPane that adds JLabels to it when pressing the button:
public class Example extends JFrame {
public Example() {
JPanel boxPanel = new JPanel();
boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.PAGE_AXIS));
JTextField textField = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel label = new JLabel(textField.getText());
label.setOpaque(true);
label.setBackground(Color.RED);
boxPanel.add(label);
boxPanel.add(Box.createRigidArea(new Dimension(0,5)));
textField.setText("");
boxPanel.revalidate();
// pack();
}
});
JPanel southPanel = new JPanel();
southPanel.add(textField);
southPanel.add(sendButton);
add(new JScrollPane(boxPanel));
add(southPanel, BorderLayout.PAGE_END);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
The BoxLayout will stack the labels on top of each other.
Notes:
setOpaque(true) must be called on label for it to honor the background color.
Box.createRigidArea is used for creating gaps. Use it as you wish.
The call to revalidate() is imperative in order to display the new components immediately.
Calling pack() (on the JFrame) will resize it each time to fit all the new components. I just put it there for demonstration since the initial frame size is too small to display the initial components added.
I will use a BoxLayout, creating a vertical box, and after each button action, it will add a new JPanel to this box.
Example:
public class YourChat extends JPanel{
private JScrollPane sc;
private Box bv;
public YourChat(){
bv = Box.createVerticalBox();
sc = new JScrollPane(bv);
//your functions (panel creation, addition of listeners, etc)
add(sc);
}
//panel customized to have red backgroud
private class MyPanel extends JPanel(){
private JLabel label=new JLabel();
public MyPanel(String text){
setBackgroundColor(Color.red);
add(label);
}
}
//inside the action listener
public void actionPerformed(ActionEvent e) {
sc.add(new MyPanel(textField.getText()));
textField.setText("");
}
}
For extra information check on:
[https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html]
See also the example
[http://www.java2s.com/Code/Java/Swing-JFC/VerticalandhorizontalBoxLayouts.htm]
Use BoxLayout if you want only add vertically, otherwise you can use FlowLayout for both directions.
I am trying to make a JFrame with a button in it, but my button doesnt have my wanted text! I'm setting it in the button constructor AND afterwards with setText, but it still doesnt show up! Also, the button fills the whole frame, is there a way to make it not stick to the edges of the JFrame?
import javax.swing.*;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}
Why does it work for me and not you? (with the FlowLayout suggested by others
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
//eightButton.setAction(new buttonAction());
//eightButton.setContentAreaFilled(false);
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}
EDIT
an Action needs a title. If you don't specify one, the button will have no title. If you did this
eightButton.setAction(new buttonAction(), "8");
it would work.
Use a layout manager that respects the component's preferred size
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
Swing components expect a layout manager context when they are added to a window.
The default layout is BorderLayout, which is why you're getting that odd behavior. With only a single element, BorderLayout fills the pane with that element.
Try something like FlowLayout or AbsoluteLayout (or null)
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Use another LayoutManager default frame's layout manager is BorderLayout that if you add a component without specification will add to the center. You can use FlowLayout. See example with SwingUtilities.invokeLater you ensure that will run in EDT.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame mainWindow = new JFrame("8 Game");
mainWindow .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setLayout(new FlowLayout());
mainWindow.setLocationRelativeTo(null);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.pack();
mainWindow.setVisible(true);
}
});
}
Take a look of more complete correct examples in official tutorials How to use Buttons
I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).