How to make a Java GUI panel component sleep? - java

Lets say i have 2 GUI panels A and B
In Panel A, I have a jTextArea that you can input a String ,
and a jbutton that if it is pressed, it appends the String inside a jTextArrea on a jTextField that is inside Panel B
What i want to do is make the String append on Panel B after waiting 2 seconds
without having the Thread Going on to Sleep
It has to be able to input another string into jTextArea during the wait period
How do i do this without using Thread.sleep()?

Start by taking a look at Concurrency in Swing, How to use Swing Timers and Worker Threads and SwingWorker to understand the issues and the possible solutions.
If you really don't want to use Thread#sleep (which you could use with a SwingWorker), a Swing Timer is probably the best solution. It allows you to setup a callback after a given delay (you can also repeat the callback, but in this case, we only need it once).
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField field;
private JTextArea ta1;
private JTextArea ta2;
private JButton btn;
private Timer timer;
public TestPane() {
JPanel panelA = new JPanel(new BorderLayout());
JPanel panelB = new JPanel(new BorderLayout());
setLayout(new GridLayout(1, 2));
add(panelA);
add(panelB);
field = new JTextField(10);
ta1 = new JTextArea(10, 20);
ta1.setEditable(false);
btn = new JButton("Add");
panelA.add(field, BorderLayout.NORTH);
panelA.add(new JScrollPane(ta1));
panelA.add(btn, BorderLayout.SOUTH);
ta2 = new JTextArea(10, 20);
ta2.setEditable(false);
panelB.add(new JScrollPane(ta2));
ActionListener startListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta1.append(field.getText() + "\n");
if (!timer.isRunning()) {
field.setEnabled(false);
btn.setEnabled(false);
timer.start();
}
}
};
field.addActionListener(startListener);
btn.addActionListener(startListener);
timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta2.append(field.getText() + "\n");
field.setEnabled(true);
btn.setEnabled(true);
field.setText(null);
field.requestFocusInWindow();
}
});
timer.setRepeats(false);
}
}
}

Related

Java - how to zoom in/zoom out text in JTextArea

I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}

I am having trouble implementing ActionListener, into a swing based GUI

I want to be able to detect when my button, ever so conveniently named button is clicked, I am having trouble making it be that way. here is some code
import java.awt.GridLayout;
import java.awt.event;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class Main implements ActionListener
//im having immense problems implementing the action listener.
{
public static void main(String[] args)
{
new GUI(); // calling in main.
System.out.print("test for bad wifi because my wifi hates me"); // I'm using a cloud based ide
}
JFrame frame1 = new JFrame();
JPanel panel1 = new JPanel();
JFrame frame2 = new JFrame(); //not in use yet
JPanel panel2 = new JPanel(); //""
public void GUI()
{
JButton button = new JButton("moment");
button.addActionListener(this);
panel1.setBorder(BorderFactory.createEmptyBorder( 30, 30, 30, 30 ));
panel1.setLayout(new GridLayout(0, 1));
panel1.add(button);
frame1.add(panel1, BorderLayout.CENTER); // frame is on the pannel or vice versa
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // funny close
frame1.setTitle("Final.");
frame1.pack();
frame1.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Any help is appreciated
Download and use an IDE.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section.
The JFrame methods must be called in a specific order. This is the order I use for all my Swing applications.
Here's the complete runnable code I wound up with.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleJButtonExample implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SimpleJButtonExample().createAndShowGUI(); // calling in main.
}
});
// I'm using a cloud based ide
System.out.println("test for bad wifi because my wifi hates me");
}
JFrame frame1 = new JFrame();
JPanel panel1 = new JPanel();
JFrame frame2 = new JFrame(); // not in use yet
JPanel panel2 = new JPanel(); // ""
public void createAndShowGUI() {
JButton button = new JButton("moment");
button.addActionListener(this);
panel1.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
panel1.setLayout(new GridLayout(0, 1));
panel1.add(button);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // funny close
frame1.setTitle("Final");
frame1.add(panel1, BorderLayout.CENTER); // panel is within the frame
frame1.pack();
frame1.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
}

How to set caret position at the end of JFormattedTextField when it is clicked/focused?

I have frame with JFormattedTextField(s). My simplified code can look like:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
frame.setLayout(new GridLayout(2,2));
JFormattedTextField field1 = new JFormattedTextField(NumberFormat.getInstance());
field1.setValue(0.4);
frame.add(new JLabel("value A"));
frame.add(field1);
JFormattedTextField field2 = new JFormattedTextField(NumberFormat.getInstance());
field2.setValue(0.8);
frame.add(new JLabel("value B"));
frame.add(field2);
frame.setVisible(true);
which generates:
Goal
When I click/focus on any of JFormattedTextField I would like it to automatically place caret at the end
Problem
I tried using following solutions before calling frame.setVisible(true); but none of them seems to work
from How to set AUTO-SCROLLING of JTextArea in Java GUI?
field1.setCaretPosition(field1.getDocument().getLength());
from https://tips4java.wordpress.com/2008/10/22/text-area-scrolling/ ((DefaultCaret)field2.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
Works without issue for me....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField textField = new JTextField("This is a test");
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Provide a runnable example which doesn't work if you still have issues
Update with JFormattedTextField....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Updated with "set at beginning"
Okay, I just want to point out that I have personally dislike of JFormattedTextField, it does a lot of "things" at times which don't always make sense.
An "old" trick I've used, when implementing a "auto select all on focus gain", is to offload the request to the end of the Event Dispatching Thread, this places the request AFTER all the "funky stuff" that the JFormattedTextField does when the field becomes focused...
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
textField.setCaretPosition(textField.getText().length());
}
});
}
});
Yes, I'm serious ...

Java KeyListener not responding

Forgive me if I'm asking too big of a question, I trying to learn to code and I think I'm missing a big detail about KeyListiner. I am trying to make a simple program that "rolls a dice" and displays a picture of a number 1 to 6 when the users presses a key. My program doesn't seem to respond to any user input.
What am I doing wrong?
Thank you for any help, I'm just trying to learn so any advice is appreciated.
public class Dice {
public static void main (String arg[]) {
new DD();
}
}
class DD extends JPanel {
DD(){
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("dice.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
addKeyListener(new Roll());
}
}
class Roll extends JFrame implements KeyListener {
public void keyPressed(KeyEvent event){}
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){
int d = event.getKeyCode();
if(d == KeyEvent.VK_UP){
int roll = (int) (Math.random()*6) + 1;
System.out.println(roll);
}
}
}
Let's take a closer look at your DD class...
class DD extends JPanel {
DD() {
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("dice.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
addKeyListener(new Roll());
}
}
You create an instance of JFrame, from within the constructor of the JPanel, which is a questionable act...
You create a JLabel and add it to the JFrame
You show the JFrame
You add a KeyListener to the DD JPanel
But wait a minute, DD is never attached to any visible component, how could it ever possible be capable of receiving key events?!
KeyListener will only work when the component that it's registered to is focusable AND has focus, but if it's never displayed on the screen, it could never have focus!
To start with, I'd avoid using KeyListener, it has focus related issues, and instead use the Key Bindings API
For example...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Dice {
public static void main(String[] args) {
new Dice();
}
public Dice() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DD());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
class DD extends JPanel {
DD() {
setLayout(new GridBagLayout());
JLabel label = new JLabel(" - ");
add(label);
addKeyBindingFor(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Action.roll", new DiceRollAction(label));
}
protected void addKeyBindingFor(KeyStroke keyStroke, String name, Action action) {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(keyStroke, name);
actionMap.put(name, action);
}
public class DiceRollAction extends AbstractAction {
private JLabel label;
public DiceRollAction(JLabel label) {
this.label = label;
}
#Override
public void actionPerformed(ActionEvent e) {
int roll = (int) (Math.random() * 6) + 1;
label.setText(Integer.toString(roll));
}
}
}
}

Why can't I resize or relocate my JButton on my JPanel?

package swingtraining;
import static java.awt.Color.BLACK;
import static java.awt.Color.RED;
import java.awt.EventQueue;
import static java.awt.Font.BOLD;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class JFrameWithAButton extends JFrame {
public JFrameWithAButton(){
setSize(400,400);
setTitle("Swing is hard");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
JButton Jbt = new JButton();
Jbt.setLayout(null);
Jbt.setSize(200,200);
Jbt.setBounds(new Rectangle(new Point(200, 200)));
Jbt.setText("Hello!");
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
Jp1.add(Jbt);
}
});
}
}
Sorry if the code's a bit mom's spaghetti-esque, but I just can't crack this cookie >.> Even with layout set to null it doesn't move. Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
I can think of a few, none of which use null layouts
GridBagConstraints
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 200;
gbc.ipady = 200;
add(new JButton("Hello"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
JButton#setMargin
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton btn = new JButton("Hello");
btn.setMargin(new Insets(100, 100, 100, 100));
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
EmptyBorder
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(50, 50, 50, 50));
JButton btn = new JButton("Hello");
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
You could use combination of them, maybe using an EmptyBorder and GridBagConstraints to further constrain the layout.
The great benefit of these examples, is, for the most part, if the font size changes or the rendering requirements for the fonts change, the layout is capable of compensating
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
And because it's always a fun read, Why is it frowned upon to use a null layout in SWING?
if you wanna define any component size manually you have to set the mother component's layout: null
so you have to set Jframe layout null to define Jpanel size and location
then you have to set JPanel layout null to define Jbutton size and location in it
final JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
Jp1.setLayout(null);
final JButton Jbt = new JButton();
// Jbt.setLayout(null); not needed!
Jbt.setBounds(10, 10, 100, 40);
// Jbt.setBounds(new Rectangle(new Point(200, 200))); not in this style
Jbt.setText("Hello!");
Jp1.add(Jbt);
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
}
});
don't forget to define size and location both when you are adding a component in a null layout Jpanel or Jframe and ...

Categories

Resources