I'm learning Java and Swing, but my JButton doesn't work.
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Programma {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e){
e.printStackTrace();
}
JFrame frame = new JFrame("DIG");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setBounds(100, 100, 130, 35);
panel.add(button);
frame.add(panel);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JLabel label = new JLabel("Hello World");
label.setVisible(true);
panel.add(label);
}
});
}
}
The frame and button are visible, nut when I click it, the label doesn't appear. How can I fix this?
Do I write this before the other component like JPanel, JButton, etc., or do I write this at the end of code:
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
What is the difference ?
By the way, button.setBounds(100, 100, 130, 35) doesn't work, either.
I see some issues in your code:
button.setBounds(100, 100, 130, 35); that line will be ignored and you shouldn't be manually be determining the position of the components. See Null layout is evil and Why is it frowned upon to use a null layout in swing? altough you're not using null layout, there is explained why you shouldn't be manually determining the positions of the components.
You're running everything in your program in the main method, that will be hard to maintain later.
You're calling frame.setVisible(true) before you've added all your elements to it, that will cause you random issues.
You're not running your program on the Event Dispatch Thread (EDT), you can solve this by starting your program with the following code, which places it in the EDT. It's recommended as Swing is not thread safe.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
You're setting the size of the JFrame with setSize(...), instead call frame.pack() and override the getPreferredSize() method of the JPanel.
After all the above has been said, you need to call revalidate() and repaint() on your ActionListener so your program paints its new state.
This program follows all the above recommendations and produces the following outputs (before clicking and after clicking the button 3 times), I on purpose to not make the images so large, made the GUI shorter (200 x 200 instead of 400 x 400)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Programma {
private JFrame frame;
private JPanel panel;
private JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Programma().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame("DIG");
panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
button = new JButton("Click Me");
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel label = new JLabel("Hello World");
panel.add(label);
panel.revalidate();
panel.repaint();
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Do i write this before the other componente like JPanel,JButton... or do i write this at the end of code ?
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
What is the difference ?
Altough I answered this on the recommendations, the difference is that if you call setVisible before adding all your elements to the frame, then you'll find yourself with some random issues where the components are not all visible until you pass your mouse over them (or where they should be). frame.pack() and setVisible should be the last ones to be called in your program, and frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); can be at the start or the end, it doesn't affects, but I prefer to have it at the end too.
button.setBounds(100, 100, 130, 35); doesn't work too.
Well, that's because of you're using a layout manager (and that's the right way to do your GUIs) instead of a null-layout (which you shouldn't be using anyway) (See point #1).
Edit
What is the difference between frame.setSize(); and frame.setpack() ?
If you read the docs for pack():
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.
So, it will calculate the minimum size for your JFrame where all the elements are visible and in their preferred size while setSize will only set the window size, but if you place a JScrollBar inside it for example this will reduce the window size, because of that, that's why you should override the getPreferredSize(...) method of your container, so it will calculate its preferred size including the width of the JScrollBar or some other elements that could modify its size. See Should I avoid the use of setPreferred|Maximum|MinimumSize in Swing? (the general consensus says yes)
When you add components dynamically to panel, you need to repain it.
Do this
panel.revalidate();
after
panel.add(label);
Related
I have the following code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main
{
public static void main(String[] args)
{
Window window = new Window("This is a title", 450, 350);
JButton buttonExit = new Button("Exit", 75, 25);
window.addElement(buttonExit);
window.build();
}
}
class Window // extend the current class
{
public Window window;
public JFrame frame;
public JPanel panel;
public String title;
// instantiate object with the constructor
public Window(String title, int width, int height)
{
this.frame = new JFrame(title);
this.frame.setPreferredSize(new Dimension(width, height));
this.frame.setLocationRelativeTo(null); // centers the main window relative to the center of the screen dimension
this.panel = new JPanel();
this.panel.setPreferredSize(new Dimension(width, height));
//this.panel.setLayout(new FlowLayout());
this.frame.add(panel);
}
public void build()
{
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.pack(); // removes all unnecessary pixel space from the form
this.frame.setVisible(true);
this.frame.setSize(frame.getPreferredSize());
}
public void addElement(JButton element)
{
this.panel.add(element);
}
}
class Button extends JButton // extend the current class
{
public Button(String text, int width, int height)
{
JButton button = new JButton();
button.setPreferredSize(new Dimension(width, height));
button.setText(text);
button.setVisible(true);
new ButtonHandler(button);
}
}
class ButtonHandler implements ActionListener
{
public ButtonHandler(JButton button)
{
button.addActionListener(this);
}
public void actionPerformed(ActionEvent actionEvent) {
System.exit(0);
}
}
I have two problems with this:
The button is compressed and won't show its text
I cannot get the event handler to work and don't appear to get why
As a side note, I know that I don't specify a LayoutManager here, but I had this implemented before and it didn't solve my issue (I tried the FlowLayoutManager and the GridBagLayout [this would be my desired one, due to its flexibility]).
Can someone tell me, what I am doing wrong here? I've only worked with C# and WPF/WinForms before...
Issue 1:
Your custom Button class is-a JButton but also has-a JButton (named button) in the constructor.
The problem here is you install the ButtonHandler class to the button of the constructor, not the custom Button itself (which is referred to as this inside the constructor).
Issue 2:
When you set the [preferred] size of the JFrame property named frame (in the custom class named Window), you are not setting the frame's contents' [preferred] size, but the size of the whole JFrame, which includes the bar located at the top of the frame (which has the title of the frame).
That lets the contents of the frame to have a space less than the preferred size, because the preferred size is set to the whole frame.
I know, you are also setting the preferred size of the JPanel named panel, which is added to the frame, but when you pack the frame, then the preferred size of the frame is prioritized rather than the preferred size of the contents of the frame, so that's probably why you are seeing the button compressed.
Let me demonstrate what I mean, with a bit of code:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestFramePrefSz {
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> {
final JFrame frame = new JFrame("Testing JFrame preferred size");
final JPanel contents = new JPanel();
contents.setPreferredSize(new Dimension(200, 200));
frame.setPreferredSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(contents);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println(contents.getSize());
});
}
}
As you can see, the dimension object printed (which is the actual size of the panel) is about 184x161 rather than 200x200 requested, because the preferred size of the frame is also set to 200x200 (which includes the title of the frame etc...).
The solution, is to only set the preferred size of the contents, not the frame (in this particular scenario at least).
So you should:
Remove the line this.frame.setSize(frame.getPreferredSize()); inside the build method.
Remove the line this.frame.setPreferredSize(new Dimension(width, height)); inside the constructor of the custom class named Window.
Issue 3:
The line this.frame.setLocationRelativeTo(null); inside the constructor of the custom class named Window, is not effective in that place.
Imagine that, when you call this method, it has to determine the location of the frame to set it.
So it needs to know first of the size of the screen and then the size of the frame itself.
But what is the size of the frame at the point where you call this method? It is about 0x0. Not the preferred size as you might expect.
That makes the calculation of the frame's location to be such that the frame will not be centered at the screen.
That's because the preferred size is a property of the frame, which is a different property than the size.
So you either have to setSize prior making the call, or better to set the preferred size of the contents of the frame (ie this.panel), then call pack on the frame and finally call the method this.frame.setLocationRelativeTo(null).
Then you are free to set the frame to visible to see where it is located in the screen (ie should be centered).
So the solution is to follow a pattern like the following:
Create the frame, add the contents of the frame to it and set the contents' preferred size.
Call pack on the frame (remember this call will change the size of the frame, according to the preferred sizes of the contents of the frame or the frame's itself).
Call setLocationRelativeTo(null) on the frame.
Call setVisible(true) on the frame.
If you take a look at your code, you are instead doing:
Create the frame.
Set the preferred size of the frame.
Call setLocationRelativeTo(null) on the frame (but the size of the frame is not set yet).
Add the contents of the frame to it (ie the panel).
Call addElement which adds more content to the panel.
Call pack on the frame (remember the preferred size of the frame is set up to this point, so it will override any other preferred sizes, such as the contents' preferred size).
Call setVisible(true) on the frame.
Call setSize on the frame, with the preferred size of it. So you are overwriting the size the frame has had from step 6.
I don't know what you're using as a tutorial. I recommend the Oracle tutorial, Creating a GUI With JFC/Swing. You can skip the Netbeans section, but I recommend going through the rest of the sections.
I created the following GUI.
The Exit button works, disposing of the GUI. The X in the upper right also disposes of the GUI.
Here's the runnable example code. The explanation follows the code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JButtonExample implements Runnable{
public static void main(String[] args) {
SwingUtilities.invokeLater(new JButtonExample());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("This is a title");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
exitProcedure();
}
});
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(300, 200));
panel.setBorder(BorderFactory.createEmptyBorder(
75, 100, 75, 100));
JButton button = new JButton("Exit");
button.addActionListener(new ExitListener(this));
panel.add(button, BorderLayout.CENTER);
return panel;
}
public void exitProcedure() {
frame.setVisible(false);
frame.dispose();
System.exit(0);
}
public class ExitListener implements ActionListener {
private JButtonExample example;
public ExitListener(JButtonExample example) {
this.example = example;
}
#Override
public void actionPerformed(ActionEvent event) {
example.exitProcedure();
}
}
}
I make a call to the SwingUtilities invokeLater method from the main method. This method makes sure that the Swing components are created and executed on the Event Dispatch Thread.
I separate the JFrame code from the JPanel code. This is so I can focus on one part of the GUI at a time.
The JFrame methods have to be called in a specific order. This is the order that I use for most of my Swing applications.
The WindowListener (WindowAdapter) gives my code control over the closing of the JFrame. This will allow the Exit button actionListener to close the JFrame. A WindowListener is not a simple concept.
The JFrame defaultCloseOperation is usually set to EXIT_ON_CLOSE. In order for the WindowListener to work, I had to set the defaultCloseOperation to DO_NOTHING_ON_CLOSE.
I let the JFrame determine its own size by using the pack method.
I set the preferred size of the JPanel.
I created an empty border for the JPanel, so the JButton would expand to fill the rest of the JPanel. That's what happens to the component placed in the center of a BorderLayout.
I created an ExitListener class. Because it's an inner class, I didn't have to create a constructor or pass the JButtonExample instance. I created a constructor so you can see how it's done, and how the actionListener method can execute the exitProcedure method of the JButtonExample class.
I hope this JButton example is helpful. The WindowListener is a bit advanced for a simple example, but you can see how it's done.
Please note that this is a more theoretical question about problems with this approach, as I'm trying to understand the underlying mechanics - genuine curiosity. For the actual implementation I'm likely to use something different.
Say we have the following frame with a split pane. The right hand side of the split pane has a button to slide out a panel on the left and show another one in its place (here I'm using overlay layout to make it look smoother). The code is as follows:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Main {
JPanel panel;
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
public void makeUI() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.setLocation(0,0);
JPanel panel3 = new JPanel();
panel3.setBackground(Color.BLUE);
panel3.setMinimumSize(new Dimension(100,400));
JPanel panelContainer = new JPanel();
panelContainer.setLayout(new OverlayLayout(panelContainer));
panelContainer.add(panel);
panelContainer.add(panel3);
JButton button = new JButton("slide out");
// Slide out the red panel to reveal blue
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setEnabled(false);
new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setLocation(panel.getX() - 1, 0);
if (panel.getX() + panel.getWidth() == 0) {
((Timer) e.getSource()).stop();
panel.setVisible(false);
System.out.println("Timer stopped");
}
}
}).start();
}
});
JFrame frame = new JFrame("Sliding Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
splitPane.setDividerLocation(100);
splitPane.setLeftComponent(panelContainer);
JPanel panel2 = new JPanel();
panel2.add(button);
// panel2.add(button2);
panel2.setMinimumSize(new Dimension(200,400));
splitPane.setRightComponent(panel2);
frame.setContentPane(splitPane);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main().makeUI();
}
});
}
}
Now if I add a button that reverses the animation, by setting location to (-panel.getWidth(), 0) and then increase the x coordinate, this fails. In theory the code is the same, with the only differences being in the start position, end position, and increments. However it does no longer work.
JButton button2 = new JButton("slide in");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setEnabled(false);
panel.setVisible(true);
panel.setLocation(-panel.getWidth(),0);
System.out.println(panel.getX()); // gives -99, which is about right
new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(panel.getX()); // starts from 0
panel.setLocation(panel.getX() + 1, 0);
System.out.println(panel.getX()); // keeps increasing until forcibly stopped
if (panel.getX() == 0) {
((Timer) e.getSource()).stop();
System.out.println("Timer stopped");
}
}
}).start();
}
});
More precisely the problem lies in the new Timer(...) line. As per console logging, setting location puts the X coordinate at -99, but two lines later it's at 0, and when increments occur, it goes on to infinity.
Perhaps I am misunderstanding how timers work, however after reading the documentation on it and JPanels, I still don't see why such an approach would not work. Not to mention that there is very little on negative coordinates of JPanels to begin with.
Thank you in advance for all the explanations!
EDIT (27.07.2016)
#camickr 's answer makes it work, however I still don't undersand it, although it helped me narrow the question a little:
Why is the layout re-done after setting the location to negative? What is causing it to be re-done?
In theory the code is the same, with the only differences being in the start position, end position, and increments
Actually it is not the same.
You play with the visibility of the panel and the logic is different depending on which button you click. I'm guessing the setVisible(true) statement is invoking the layout manager which is resetting the location of the component.
There is no need to change the visibility of the panel. Get rid of both setVisible(...) statements.
Also, you might want to keep the buttons enabled you can test sliding in/out repeatedly without restarting the program.
Edit:
if that was the case, why does getX() gives -99
Because the layout hasn't been done when that statement is executed.
Code does not always execute sequentially. Sometimes Swing methods will use SwingUtiltites.invokeLater() to add code the end of the Event Dispatch Thread (EDT).
This is easy enough to verify. Just change your code as follows to see when the layout is invoked.
JPanel panelContainer = new JPanel()
{
#Override
public void doLayout()
{
System.out.println("layout");
super.doLayout();
}
};
So far all i have managed to get is the JButton to close the first JFrame (frame) but the other will not open.
Frame class code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame {
public static void main(String[] args) {
// Frame - Labelled BrickFall
final JFrame frame = new JFrame();
frame.setSize(1290, 730);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("BrickFall");
frame.setLayout(null);
frame.setLocationRelativeTo(null);
// Start Button
JButton Start = new JButton("Start");
Start.setBounds(100, 300, 1080, 50);
frame.add(Start);
// Exit Button
JButton Exit = new JButton("Exit");
Exit.setBounds(369, 375, 540, 50);
frame.add(Exit);
// Closes when Exit Clicked
Exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//New Frame opens when Start Clicked
Start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
// Background Image
JLabel background = new JLabel("");
background.setBounds(0, 0, 1280, 720);
background.setIcon(new ImageIcon(Frame.class.getResource("/resources/images/Title.png")));
frame.getContentPane().setLayout(null);
frame.getContentPane().add(background);
frame.setVisible(true);
}
protected static void dispose() {
// TODO Auto-generated method stub
}
}
On the (frame) action listener i have left out the second line to open the other JFrame as my attempts wont work
Game class code
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class game {
public static void main(String[] args) {
// Frame - Labelled BrickFall
JFrame game = new JFrame();
game.setSize(1290, 730);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setTitle("BrickFall");
game.setLayout(null);
game.setLocationRelativeTo(null);
// Background Image
JLabel GameBackground = new JLabel("");
GameBackground.setBounds(0, 0, 1280, 720);
GameBackground.setIcon(new ImageIcon(Frame.class.getResource("/resources/images/Fill In.png"))); //Change Picture When Required
game.getContentPane().setLayout(null);
game.getContentPane().add(GameBackground);
game.setVisible(true);
}
}
If anyone has any suggestions on how I can sort this I will be very thankful.
You're disposing the JFrame and setting its default close operation to JFrame.EXIT_ON_CLOSE which closes the JVM, shutting down your entire program.
Solution 1: Make your JFrame invisible via setVisible(false)
or if you do use dispose(), make sure that you set its default close operation to anything but what you're currently doing: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); as this also closes the JVM.
Solution 2: better yet, make the closing window a JDialog.
Solution 3: Even better, don't spit different windows at the user, but rather swap views by swapping JPanels with a CardLayout. For details, please check out the CardLayout Tutorial.
Suggestion: don't use null layouts like you're doing, but rather learn to use the different layout managers.
Suggestion: get out of the main method. Don't make your classes nothing but large static main methods, basically 1970's procedural programming. Learn to use and then create OOP-compliant classes with constructors, non-static fields, non-static methods, with states and behaviors, and have these classes interact in a pleasing and useful fashion.
I'm making some test code to practice OOP, and I want to append a JTextArea from the "writeToArea" to the "initialize" method where the JTextArea is defined and initialized. I already tried to directly call the "output" variable, but this returns an "output cannot be resolved" error. I want so that whenever I call the "writeToArea" method in the main class, I'll be able to add lines to the "output" JTextArea in the "initialize" method.
Here's the main class:
public class Pangea {
public static void main(String[] args) {
UI.initialize();
UI.writeToArea();
}
}
Here's the initialize class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class UI {
static void initialize() {
System.out.println("Initializing GUI.");
JFrame frame = new JFrame();
Font myFont = new Font("Courier", Font.BOLD, 14);
JTextField input = new JTextField("");
JTextArea output = new JTextArea("Initiated Succesfully.");
output.setWrapStyleWord(true);
output.setLineWrap(true);
input.setFont(myFont);
output.setFont(myFont);
input.setForeground(Color.WHITE);
output.setForeground(Color.WHITE);
input.setBackground(Color.BLACK);
input.setCaretColor(Color.WHITE);
output.setBackground(Color.BLACK);
output.setEditable(false);
JScrollPane jp = new JScrollPane(output);
frame.setTitle("PANGEA RPG [0.01 ALPHA][WIP]");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(input, BorderLayout.SOUTH);
frame.add(jp, BorderLayout.CENTER);
frame.pack();
frame.setSize(800, 500);
frame.setVisible(true);
System.out.println("GUI Initialized.");
}
static void writeToArea() {
System.out.println("\"writeToArea\" running.");
output.append("Hello!");
System.out.println("\"writeToArea\" finished.");
}
}
I've tried to do something similar to this: Updating jtextarea from another class but it didn't work. If anyone has any suggestions I'd be very thankful.
The main error in your code is the lack of OOP design. Making all static is poor design.
Also swing is event based, so you should append text to the textArea when an event happens. See the example i write for you.
public class UI {
private JPanel panel;
private JTextArea output;
public UI(){
initialize();
}
private void initialize() {
panel = new JPanel();
Font myFont = new Font("Courier", Font.BOLD, 14);
final JTextField input = new JTextField(""); // must be declared final cause you use it in anonymous class, you can make it instance variable if you want to as textArea
//add an actionListener then when you press enter this will write to textArea
input.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
writeToArea(input.getText());
}
});
output = new JTextArea("Initiated Succesfully",50,100);// let the component determinate its preferred size.
output.setWrapStyleWord(true);
output.setLineWrap(true);
input.setFont(myFont);
output.setFont(myFont);
input.setForeground(Color.WHITE);
output.setForeground(Color.WHITE);
input.setBackground(Color.BLACK);
input.setCaretColor(Color.WHITE);
output.setBackground(Color.BLACK);
output.setEditable(false);
JScrollPane jp = new JScrollPane(output);
panel.setLayout(new BorderLayout());
panel.add(input, BorderLayout.SOUTH);
panel.add(jp, BorderLayout.CENTER);
}
private void writeToArea(String something) {
System.out.println("\"writeToArea\" running.");
output.append(something);
System.out.println("\"writeToArea\" finished.");
}
public JPanel getPanel(){
return panel;
}
}
And in your client code
public class Pangea {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
createAndShowGUI();
}
});
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
System.out.println("Initializing GUI.");
JFrame frame = new JFrame();
frame.setTitle("PANGEA RPG [0.01 ALPHA][WIP]");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new UI().getPanel());
frame.pack();//sizes the frame
frame.setVisible(true);
System.out.println("GUI Initialized.");
}
}
Here you have a tutorial with better examples than this How to Use Text Areas
I remove your setSize and use pack()
The pack method sizes the frame so that all its contents are at or
above their preferred sizes. An alternative to pack is
to establish a frame size explicitly by calling setSize or setBounds
(which also sets the frame location). In general, using pack is
preferable to calling setSize, since pack leaves the frame layout
manager in charge of the frame size, and layout managers are good at
adjusting to platform dependencies and other factors that affect
component size.
Read the section from the Swing tutorial on How to Use Text Areas. It will show you how to better structure your code so that you don't use static methods and variables everywhere.
Once you have a panel that has a reference to the text area you can add methods that allow you to update the text area on the panel.
I'm trying to write custom JFrame and JPanel for my Java application. Currently, I just want to have a JPanel with a start button in the very middle of the screen. So, here's the code I have:
package gui;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class SubitizingFrame extends JFrame implements KeyListener {
public SubitizingFrame() {
super("Subitizing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
add(new LaunchPanel());
pack();
setVisible(true);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F5)
System.out.println("F5 pressed");
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
and here is my panel:
package gui;
import instructions.Settings;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LaunchPanel extends JPanel implements ActionListener {
private JButton startButton;
public LaunchPanel() {
int width = Settings.getScreenSizeX(), height = Settings.getScreenSizeY();
setPreferredSize(new Dimension(width, height));
setLayout(null);
startButton = new JButton("Start");
startButton.setLocation((width/2) - (startButton.getWidth()/2), (height/2) - (startButton.getHeight()/2));
add(startButton);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
But when the application launches, I don't see anything. Just a big gray screen.
Do not use a null layout. If you simply use the default layout manager of JPanel (i.e. FlowLayout), the JButton with "automagically" be placed in the center. Also, in order to place the JFrame in the middle of the screen, invoke setLocationRelativeTo(null).
Since it's hard to tell what you mean by "screen", this example shows how you center a JButton in a JPanel in a JFrame, that is then centered on the monitor.
public final class CenterComponentsDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("Center Components Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonPane());
frame.setSize(new Dimension(300, 100)); // Done for demo
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class ButtonPane extends JPanel{
public ButtonPane(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBackground(Color.PINK);
final JButton button = new JButton("Start");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
add(Box.createVerticalGlue());
add(button);
add(Box.createVerticalGlue());
}
}
}
Recommendations:
Avoid using null layout as this makes your app difficult to upgrade and maintain and makes it potentially very ugly or even non-usable on boxes with different OS's or screen resolutions.
If you have your JPanel use a GridBagLayout and add a single component to it without using GridBagConstraints, it will be placed in the center of the JPanel.
You almost never have to or should extend JFrame and only infrequently need to extend JPanel. Usually it's better to enhance your GUI classes through composition rather than inheritance.
Avoid having your "view" or gui classes implement your listener interfaces. This is OK for "toy" programs, but as soon as your application gains any appreciable size or complexity, this gets hard to maintain.
If you don't use any LayoutManager (which btw you probably should), then you'll need to set the size of the panel as well (along with its position).
Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.
From: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class LaunchPanel extends JPanel {
private JButton startButton;
public LaunchPanel() {
int width = 200, height = 100;
setPreferredSize(new Dimension(width, height));
setLayout(new GridBagLayout());
startButton = new JButton("Start");
add(startButton);
setBorder( new LineBorder(Color.RED, 2));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new LaunchPanel());
}
});
}
}
addKeyListener(this);
Don't use KeyListeners. Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings for more information.
The tutorial also has a section on Using Layout Manager which you should read. You should not create GUI's with a null layout.