Java Swing - Text and buttons not showing up - java

Trying everything, just not showing up:
package me.ultimate.ST;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class ST extends JFrame {
private static final long serialVersionUID = 1L;
public ST() {
setSize(500, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
getContentPane().setBackground(Color.BLACK);
JLabel label = new JLabel("Test");
label.setText("Some Test!");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ST ex = new ST();
ex.setVisible(true);
}
});
}
}
I then just get a black box.

You need to add the label to the frame:
label.setText("Some Test!");
add(label);
I suggest you read the Swing tutorial for the basics. Maybe the section on How to Use Labels would be a good place to start. The tutorial will also show you a better way to design your class wo that you follow Swing guidelines.

You forgot to add the label to the frame :)
add(label, BorderLayout.CENTER);
Whatever layout you wish to use...

Related

Java JLabel background color not working?

I'm learning how to create application in Java.
I'm having trouble getting the JLabel to have a background color whilst the JPanel is white, behind it. Also, is there a way to resize the JPanel to half of what the JFrame is?
Any help would be very much appreciated. Thank you.
package PracticeOne;
import java.awt.BorderLayout;
public class PracticeOne {
public static void main(String[] args) {
Frame container = new Frame();
Panel box = new Panel();
Label txt = new Label();
box.add(txt);
container.add(box, BorderLayout.CENTER);
}
}
package PracticeOne;
import javax.swing.JFrame;
public class Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
Frame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setTitle("Testing this out");
}
}
package PracticeOne;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
public class Panel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public Dimension d = new Dimension(100,100);
Panel(){
this.setSize(d);
this.setAlignmentX(CENTER_ALIGNMENT);
this.setBackground(Color.WHITE);
}
}
package PracticeOne;
import java.awt.Color;
import javax.swing.JLabel;
public class Label extends JLabel {
/**
*
*/
private static final long serialVersionUID = 1L;
Label(){
this.setSize(50, 50);
this.setText("ya boy is working here");
this.setForeground(Color.BLACK);
this.setBackground(Color.ORANGE);
}
}
I'm having trouble getting the JLabel to have a background color whilst the JPanel is white
You need to call setOpaque(true); in your JLabel
Also, is there a way to resize the JPanel to half of what the JFrame is?
You could use a GridLayout, and place 2 JPanels in it, that way, you're going to have 2 JPanels using half the size of your JFrame each.
Also, rename your classes, Panel belongs to the name of a class in AWT, same for Frame and Label, this might confuse your (and whoever reads your code).
Never extend JFrame, instead build your GUI based on JPanels. See extends JFrame vs creating it inside of class and The use of multiple JFrames, Good / Bad practice? The general consensus says it's bad.
Also you should also check Should I avoid the use of setPreferred|Maximum|MinimumSize() in Swing? Again, yes, you should and instead override the getPreferredSize() method.
Don't forget to place your program on the Event Dispatch Thread (EDT) by changing your main() method as follows:
public static void main(String[] args) {
//Java 8 with lambda expressions
SwingUtilities.invokeLater(() ->
//Your code here
);
//Java 7 and below (Or 8 without lambda expressions)
SwingUtilities.invokeLater(new Runnable() {
//Your code here
});
}
Now, with all the above recommendations, your code should now look like this:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class HalfSizePanelWithLabelInDifferentColor {
private JFrame frame;
private Container contentPane;
private JPanel pane;
private JPanel pane2;
private JLabel label;
private static final Dimension dim = new Dimension(100, 100);
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new HalfSizePanelWithLabelInDifferentColor().createAndShowGui());
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
contentPane = frame.getContentPane();
pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return dim;
}
};
pane2 = new JPanel();
pane.setOpaque(false);
pane2.setOpaque(false);
pane.setBorder(BorderFactory.createLineBorder(Color.RED));
pane2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
label = new JLabel("Hello World!");
label.setBackground(Color.GREEN);
label.setOpaque(true);
contentPane.setLayout(new GridLayout(2, 1));
pane.add(label);
contentPane.add(pane);
contentPane.add(pane2);
contentPane.setBackground(Color.WHITE);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And your output would be like this:
Note that I added some colored borders to show where a pane starts and ends and where the other one starts and ends

How to edit JTextField?

I want to write a simple Swing application with a button and a text field at the bottom. I'm using a JTextField but it is not clickable. I searched on the web and SO, but I could not find a solution. In question How to Set Focus on JTextField?, I found the following :
addWindowListener( new WindowAdapter() {
public void windowOpened( WindowEvent e ){
entry.requestFocus();
}
});
but this does not help. In this other question (How do you set a focus on Textfield in Swing?) I found Component.requestFocus() but this does not work either. I also tried
entry.setFocusable(true);
entry.setEditable(true);
entry.setEnabled(true);
without effects. My code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class StackSample extends JFrame {
public StackSample() {
initUI();
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void initUI() {
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout());
panel.add(bottomPanel, BorderLayout.SOUTH);
JButton buttonDraw = new JButton("Draw");
bottomPanel.add(buttonDraw);
JTextField entry = new JTextField();
bottomPanel.add(entry);
setPreferredSize(new Dimension(250, 150));
setLocationRelativeTo(null);
}
private static final long serialVersionUID = 8359448221778584189L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApp app = new MyApp();
app.setVisible(true);
}
});
}
}
Your JTextField is clickable. The only problem is that it's too small.
This is because you're using FlowLayout, which will make components as small as possible.
One solution is to simply switch to a layout that allows components to fill as much space as possible, such as BoxLayout:
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.X_AXIS));
You haven't specified a size for your JTextField, so it defaults to zero characters wide. Try using the constructor that specifies the number of columns.
Also, what is MyApp? I can't see any evidence that your StackSample is ever created or used.

JFileChooser in front of fullscreen Swing application

I know there are some topics relative to this question (mainly this unanswered one and this one which is not handling full screen app).
I basically tried every combination of first topic sample and available methods (requestFocus, requestFocusInWindow, ...) but JFileChooser is always displaying behind the fullscreen app. I tried to change filechooser's parent too (setting it to null, itself or the parent frame) with no more success.
Have anyone a working example of this not-that-much-particular use case? Or is there a workaround to let user select files in a fullscreen app?
Unfortunately I can't say how you realised the implementation of the fullscreen app. But I tried a few things and came up with this:
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Gui extends JFrame {
public Gui() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
// Set some charateristics of the frame
this.setExtendedState(Frame.MAXIMIZED_BOTH);
this.setBackground(Color.black);
this.setUndecorated(true);
JButton a = new JButton("PRESS ME!");
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(getParent());
}
});
this.add(a);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
}
}
Pay attention to the fact, that I created a new JFileChooser with the parent of the current JFrame as parameter.
EDIT:
I now even tried to set
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(new Gui());
and without the
this.setUndecorated(true);
it worked for me (got a nice fullscreen view and the JFileChooser was in the front). I believe the problem with the window decoration is linked to my window manager (I'm using linux with gnome).
Hopefully this solution works for you, if not:
Could you explain a little bit more, how you create the fullscreen app?
I would suggest instead of using using a Popup, just embed the JFileChooser into your application. It doesn't really make sense to have popups in a windowless application (Personally, I don't like popups much anyways).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FullScreenApp {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setTitle("Frame");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60)); // Ugh.
frame.setVisible(true);
final Box panel = Box.createVerticalBox();
JButton btn = new JButton();
btn.setText("Button");
panel.add(btn);
frame.add(panel);
final CustomFileChooser chooser = new CustomFileChooser(panel);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
chooser.show();
}
});
}
public static class CustomFileChooser extends JFileChooser{
/** Node this chooser should be added to.
* There's likely a better way of doing this,
* but it was convenient for a quick example */
Container parent;
public CustomFileChooser(Container parent){
super();
this.parent = parent;
//Make configurations for your file chooser
setApproveButtonText("Open");
}
#Override
public void approveSelection(){
super.approveSelection();
//Perform accept action here
System.out.println(getSelectedFile().getAbsolutePath());
parent.remove(CustomFileChooser.this);
parent.repaint();
}
#Override
public void cancelSelection(){
super.cancelSelection();
//Perform cancel action here
System.out.println("Canceled");
parent.remove(CustomFileChooser.this);
parent.repaint();
}
#Override
public void show(){
rescanCurrentDirectory();
parent.add(this);
revalidate();
repaint();
}
#Override
public Dimension getMaximumSize(){
//Not necessary - But I felt the chooser should have a maximum size
return new Dimension(500,300);
}
}
}
FullscreenLib
//import
import argha.util.Fullscreen;
//this for JFrame
//true for setting Undecorated on/off
Fullscreen screen = new Fullscreen(this, true);
screen.DoTheWorkFor();
You can use my library for creating fullscreen windows and the problem you are facing hope it solved after that i tested and its working.
Hope it may helped you

JLabel tooltiptext not showing

I expected this to be very simple and straightforward, but tooltiptext is not showing upon hovering the mouse over. I tried printing the text and it prints correctly. Any comments what I'm doing wrong?
public class gui2 extends JFrame {
private JLabel item1;
public gui2() {
super("The title bar");
setLayout(new FlowLayout());
item1 = new JLabel("label 1");
item1.setToolTipText("This is a message");
String str = item1.getToolTipText();
System.out.println(str);
add(item1);
}
class gui {
public static void main(String[] args) {
gui2 g2 = new gui2();
g2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g2.setSize(400, 200);
g2.setVisible(true);
}
}
}
Your code does not compile even if you add the imports. Here is your code corrected and working :
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui {
public static void main(String[] args) {
Window window = new Window();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);
window.setVisible(true);
}
}
class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jlabel;
public Window() {
super("The title bar");
setLayout(new FlowLayout());
jlabel = new JLabel("label 1");
jlabel.setToolTipText("This is a message");
String str = jlabel.getToolTipText();
System.out.println(str);
add(jlabel);
}
}
As mentioned by #restricteur your code does not compile.
This is due to the fact that your class gui which holds the main(..) is nested within another class, hence no static declaration of method is allowed unless the nested class is marked static. ( I simply moved/un-nested Gui out from Gui2)
Besides that your code does work, I think you are being hasty - hold the mouse over JLabel for like 3-4 seconds and you should see the ToolTip appear:
(using your code with no compilation error of course):
Suggestions on code:
1) Please watch java naming conventions i.e class names should begin with a capital letter and each new word thereafter should also i.e gui becomes Gui or GUI but I prefer the former.
2) Dont call setSize on JFrame use and= appropriate LayoutManager and call pack() on JFrame before setting it visible (but after components have been added).
3) Dont extend JFrame unnecessarily simply create an instance and use that.
4) Always create and manipulate Swing Components on Event Dispatch Thread via SwingUtilities.invokeLater(Runnable r) block.
5) Opt for setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); unless using Timers as this will allow main(..) to continue regardless if GUI is exited.
Here is code with above fixes:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
class Gui2 {
private JLabel item1;
private JFrame frame;
public Gui2() {
frame = new JFrame("The title bar");
frame.setLayout(new FlowLayout());
item1 = new JLabel("label 1");
item1.setToolTipText("This is a message");
String str = item1.getToolTipText();
System.out.println(str);
frame.add(item1);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Gui {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui2();
}
});
}
}

Why does my JFrame stay empty, if I subclass JPanel and JFrame?

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.

Categories

Resources