I have JPanel with a border, the problem is that when I add the panel on the JFrame it takes the panel size although I set the preferred size for the panel using setPreferredSize. The layout of the frame is 'BoxLayout' and here's the code:
public class ActionForm extends JFrame {
JPanel namePanel;
JPanel descPanel;
JLabel actionName;
JLabel nameLabel;
JTextField nameTextField, descTextField;
FlowLayout toolBarLayout = new FlowLayout();
public ActionForm() {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
TitledBorder nameBorder= BorderFactory.createTitledBorder(
"Change Description");
nameBorder.setTitleJustification(TitledBorder.LEFT);
namePanel = new JPanel(toolBarLayout);
namePanel.setPreferredSize(new Dimension(150, 150));
nameLabel = new JLabel("ButtonName");
nameTextField = new JTextField("Action's Name", 50);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
namePanel.setBorder(nameBorder);
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
this.add(namePanel);
}
public static void main(String[] args) {
ActionForm form = new ActionForm();
form.setVisible(true);
form.setSize(970, 500);
form.setResizable(false);
}
}
Why the size of the panel doesn't change?
BoxLayout accepting Min/Max/preferredSize that came from JComponents layed by this LayoutManager
(I'm don't want to comment something, because my answer will be so long) please to compare your code with this code example, there are implemented all good (required and important) Swing rulles
for example
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ActionForm {
private static final long serialVersionUID = 1L;
private JFrame frame;
private JPanel namePanel;
private JLabel nameLabel;
private JTextField nameTextField;
private FlowLayout toolBarLayout = new FlowLayout();
public ActionForm() {
TitledBorder nameBorder = BorderFactory.createTitledBorder(
"Change Description");
nameBorder.setTitleJustification(TitledBorder.LEFT);
namePanel = new JPanel(toolBarLayout);
namePanel.setPreferredSize(new Dimension(150, 150));// hardCoded sizing
namePanel.setMaximumSize(new Dimension(250, 150)); // hardCoded sizing
namePanel.setMinimumSize(new Dimension(150, 150)); // hardCoded sizing
nameLabel = new JLabel("ButtonName");
nameTextField = new JTextField("Action's Name", 10);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
namePanel.setBorder(nameBorder);
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame = new JFrame("Mix / Max / PreferredSize for BoxLayout");
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
BoxLayout.Y_AXIS)); // otherwise nice exceptions java.awt.AWTError:
// BoxLayout can't be shared
frame.add(namePanel);
frame.setPreferredSize(new Dimension(970, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ActionForm form = new ActionForm();
}
});
}
}
Related
I am trying to get this code to work, such that I have a cardlayout container and each panel be defined in its own class and actual file. This code is not 100% my own and is a modified version of my previous stuff by another Stack overflow user. It is more or less what I need, but I need it such that it isn't automated and I can write 15 different panels with decisions made inside each one. The Main and Arrow class was modified by said user, and Imagepanel is my attempt to write a class that will be accepted by the working part of the code. The issue is the Imagepanel I insert into the container will register as existing, but nothing shows up on the panel, it's blank. The commented out portion in ImagePanel is my code that I set on the back burner in favor of the established stuff previously used in the Arrow class.
Here is the Main class
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
public class Main extends JPanel {
private Arrow arrow = new Arrow(); //creates a new Arrow object
public Main() {
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new NextAction("Next")));
setLayout(new BorderLayout());
add(arrow, BorderLayout.NORTH);
add(btnPanel, BorderLayout.PAGE_END);
}
private class NextAction extends AbstractAction {
public NextAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
arrow.next(); // *** call arrow's public next method that you created
// no need to make a new CardLayout instance
}
}
private static void createAndShowGui() {
Main mainPanel = new Main();
JFrame frame = new JFrame("Iowa Budget Simulation");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Here is the Arrow class where the container is created
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
class Arrow extends JPanel {
private static final long serialVersionUID = 1L;
private CardLayout cardLayout = new CardLayout(); // make me a field
private JPanel cardHolder = new JPanel(cardLayout); //creates a master JPanel
public Arrow() {
for (int i = 0; i < 5; i++) {
cardHolder.add(createCard(i), "card " + i);
}
ImagePanel pear = new ImagePanel();
cardHolder.add(pear, "Pear");
setLayout(new BorderLayout());
add(cardHolder, BorderLayout.NORTH);
}
// public method that other objects can call
public void next() {
cardLayout.next(cardHolder); // call next on the correct object
}
// simply creates a "pretty" new JPanel
private JComponent createCard(int i) {
JLabel label = new JLabel("Card " + i);
label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));
float h = (float)Math.random();
Color c = Color.getHSBColor(h, 1f, 1f);
label.setForeground(c.darker());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
panel.setBackground(c.brighter().brighter());
panel.setPreferredSize(new Dimension(400, 300));
return panel;
}
Here is ImagePanel, my attempt at a 3rd, individual panel/class
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private String imgString;
private JLabel imgLabel;
public JComponent ImagePanel() {
/*
setName("Pear");
JLabel john = new JLabel("Pear");
float h = (float)Math.random();
Color c = Color.getHSBColor(h, 1f, 1f);
john.setForeground(c.darker());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(john);
panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
panel.setBackground(c.brighter().brighter());
// Ensure size is correct even before any image is loaded.
setPreferredSize(new Dimension(400, 300));
return panel;
*/
JLabel label = new JLabel("Pear");
label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));
float h = (float)Math.random();
Color c = Color.getHSBColor(h, 1f, 1f);
label.setForeground(c.darker());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
panel.setBackground(c.brighter().brighter());
panel.setPreferredSize(new Dimension(400, 300));
return panel;
}
There is no error to post, it simply displays a blank panel. Thank you for any assistance I might receive, and I apologize in advance as I am learning Java Swing GUI through YouTube and stack overflow.
public JComponent ImagePanel() { isn't a constructor, it's a method, to make it work in your code you would have to change ImagePanel pear = new ImagePanel(); to JComponent pear = new ImagePanel().ImagePanel();, but frankly that just doesn't make much sense.
Instead, change public JComponent ImagePanel() { to public ImagePanel() {, now it's the class's constructor
Next, change...
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
panel.setBackground(c.brighter().brighter());
panel.setPreferredSize(new Dimension(400, 300));
return panel;
to
setLayout(new GridBagLayout());
add(label);
setBorder(BorderFactory.createLineBorder(c.darker(), 20));
setBackground(c.brighter().brighter());
//panel.setPreferredSize(new Dimension(400, 300));
//return panel;
Don't get me started on why setPreferredSize is a bad idea
Now you can simply use
ImagePanel pear = new ImagePanel();
cardHolder.add(pear, "Pear");
How can I make the JMenuBar streak dissapear after the menuitems? I want to put a 2nd menu in the middle of the frame, and it looks weird with this streak.
I tried to set the background to Panel.background but it doesn't work.
import java.awt.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class SwingMenuDemo extends JPanel {
public SwingMenuDemo(){
setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(UIManager.getColor("Panel.background"));
menuBar.setBounds(0, 0, 450, 25);
add(menuBar);
JButton btn1 = new JButton("Menu1");
menuBar.add(btn1);
JButton btn2 = new JButton("Menu2");
menuBar.add(btn2);
JButton btn3 = new JButton("Menu3");
menuBar.add(btn3);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SwingMenuDemo");
frame.setPreferredSize(new Dimension(400,400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.PAGE_AXIS));
frame.getContentPane().add(new SwingMenuDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you want to create your own "menu" of several JButtons, then don't use JMenu and don't use null layout and setBounds(...) (you should avoid the latter just as a general rule). Instead nest JPanels, each using its own layout manager to allow for simple creation of complex GUI's.
For instance you could create a JPanel to hold the buttons, say called menuPanel, give it a new GridLayout(1, 0) layout, meaning it will hold a grid of components in 1 row, and a variable number of columns (that's what the 0 means). Then put your buttons in that.
Then place that JPanel into another JPanel that uses say FlowLayout.LEADING, 0, 0) as its layout -- it will push all its components to the left.
Then make the main GUI use a BorderLayout and add the above panel to it's top in the BorderLayout.PAGE_START position. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingMenuDemo2 extends JPanel {
private static final String[] MENU_TEXTS = {"Menu 1", "Menu 2", "Menu 3"};
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public SwingMenuDemo2() {
JPanel menuPanel = new JPanel(new GridLayout(1, 0));
for (String menuText : MENU_TEXTS) {
menuPanel.add(new JButton(menuText));
}
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
topPanel.add(menuPanel);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwingMenuDemo2 mainPanel = new SwingMenuDemo2();
JFrame frame = new JFrame("Swing Menu Demo 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You can do that with
menuBar.setBorderPainted(false);
So I'm trying to get the button on the bottom right and the text field taking up the bottom left but it keeps switching around for some reason. I think its borderLayout being stupid. I'm a noob at Java btw. Here's my code:
package textchat;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class window extends JFrame{
public static void main(String[] args)
{
new window();
}
public window()
{
//Window Config
//JFrame frame = new JFrame();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dm = tk.getScreenSize();
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("CALI V1");
this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
//this.setLayout(null);
int Width = this.getWidth();
//Panel(s)
JPanel Panel = new JPanel();
Panel.setLayout(new BorderLayout());
JPanel PanelSouth = new JPanel();
JPanel PanelEast = new JPanel();
JPanel PanelWest = new JPanel();
//button
JButton btn = new JButton("SEND");
//Text Area
JTextArea txt = new JTextArea(100 , 100);
txt.setText("TEXT IS HERE");
//Text Field
JTextField fld = new JTextField("Type Here",15);
//Adding to the panel
Panel.add(txt);
PanelSouth.add(PanelEast, BorderLayout.EAST);
PanelSouth.add(PanelWest, BorderLayout.WEST);
PanelEast.add(btn);
PanelWest.add(fld);
//adding to frame
this.add(Panel);
this.add(PanelSouth , BorderLayout.SOUTH);
this.setVisible(true);
}
}
While using BorderLayout in such a way kind of works, you should
not use it in such a way. Besides, your example has several issues.
For instance, you did not start the application on the EDT (Event Dispatch Tread).
Here is a working example that creates your inteded layout. It uses the powerful GroupLayout manager.
package com.zetcode;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TextChatEx extends JFrame {
public TextChatEx() {
initUI();
}
private void initUI() {
JTextArea area = new JTextArea(15, 15);
JTextField field = new JTextField(15);
JButton sendButton = new JButton("Send");
createLayout(area, field, sendButton);
setTitle("Text chat");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setAutoCreateGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup()
.addComponent(arg[0])
.addGroup(gl.createSequentialGroup()
.addComponent(arg[1])
.addComponent(arg[2]))
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(arg[1])
.addComponent(arg[2]))
);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
}
}
GroupLayout is a powerful layout manager; with this manager, you don't have to create a bunch of panels to create some basic layout.
public TextChatEx() {
initUI();
}
The GUI creation is delegated to the initUI() method. Rather than placing all the code into the constructor, we use a specialized method.
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
Each Swing application should be placed on the EDT. Failing to do this can lead to hard to find bugs in the future.
I created a modal JDialog (to be correct, a children of JDialog) and set it visible when the user clicks on a JButton on a JFrame. To make sure the content on the JDialog is vertically centered I've overridden the setVisible() method and do some operations before calling super.setVisible(true). The problem here is that no component, that's placed on the dialog, does have an other size than 0 before calling setVisible(true) if the dialog is set to be modal. Also setVisible() does block the execution.
Any suggestions/tips how to bypass/fix this issue?
Sample code:
public class SampleDialog extends JDialog {
protected JPanel contentPane;
public SampleDialog() {
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
JPanel headerPane = new JPanel();
headerPane.setBackground(Color.GREEN);
add(headerPane, BorderLayout.NORTH);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
add(contentPane, BorderLayout.CENTER);
JPanel footerPane = new JPanel();
footerPane.setBackground(Color.YELLOW);
add(footerPane, BorderLayout.SOUTH);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JLabel("Code"));
contentPane.add(new JTextField());
contentPane.add(new JLabel("Password"));
contentPane.add(new JPasswordField());
contentPane.add(new JButton("Login"));
}
#Override
public void setVisible(boolean b) {
/*
* Get total height of all components added to 'contentPane'
* Place Box.createVerticalStrut() before and after the 'contentPane' components,
* so the input fields look like they are centered vertically
* !!! Cannot determine size of any component because it is not rendered
*/
super.setVisible(b);
}
}
to make sure the content on the JDialog is vertically centered i've overriden the setVisible()
You should NOT be overriding setVisible() for this.
To center the component use an appropriate layout manager.
For example to center components vertically and horizontally you can just use a GridBagLayout:
JDialog dialog = new JDialog();
dialog.setLayout( new GrigBagLayout() );
JPanel panel = new JPanel(...);
panel.add(...);
dialog.add(panel, new GridBagConstraints());
You can use MigLayout manager to easily create your intended layout:
package com.zetcode;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
* Centering components on screen.
* Author Jan Bodnar
* Website zetcode.com
*/
class MyDialog extends JDialog {
public MyDialog() {
initDialog();
}
private void initDialog() {
JLabel lbl1 = new JLabel("Code");
JTextField field1 = new JTextField(15);
JLabel lbl2 = new JLabel("Password");
JPasswordField field2 = new JPasswordField(15);
JButton btn = new JButton("Login");
createLayout(lbl1, field1, lbl2, field2, btn);
setTitle("Login");
setLocationRelativeTo(null);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("wrap, align 50% 50%", "[center]"));
add(arg[0]);
add(arg[1]);
add(arg[2]);
add(arg[3]);
add(arg[4]);
pack();
}
}
public class MigLayoutCenterEx extends JFrame {
public MigLayoutCenterEx() {
initUI();
}
private void initUI() {
JPanel pnl = new JPanel();
JButton btn = new JButton("Show dialog");
btn.addActionListener((ActionEvent e) -> {
JDialog dialog = new MyDialog();
dialog.setVisible(true);
});
pnl.add(btn);
add(pnl);
setSize(400, 300);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCenterEx ex = new MigLayoutCenterEx();
ex.setVisible(true);
});
}
}
Screenshot:
This is a java template i found about Card Layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main {
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(200, 200));
/* Here we be making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton previousButton = new JButton("PREVIOUS");
previousButton.setBackground(Color.BLACK);
previousButton.setForeground(Color.WHITE);
final JButton nextButton = new JButton("NEXT");
nextButton.setBackground(Color.RED);
nextButton.setForeground(Color.WHITE);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
previousButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
And this is my Window1.java
import java.awt.Color;
import java.awt.FlowLayout;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Window1 extends JPanel
{
/*
* Here this is our first Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JButtons.
*/
private ActionListener action;
public Window1()
{
init();
}
private void init()
{
final JButton clickButton = new JButton("Click ME");
final JButton dontClickButton = new JButton("DON\'T CLICK ME");
final JTextField title = new JTextField(12);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == clickButton)
{
String myString = title.getText();
System.out.println(myString);
}
else if (ae.getSource() == dontClickButton)
{
JOptionPane.showMessageDialog(null, "I told you not to click me!"
, "Wrong Button", JOptionPane.PLAIN_MESSAGE);
}
}
};
clickButton.addActionListener(action);
dontClickButton.addActionListener(action);
add(clickButton);
add(dontClickButton);
add(title);
}
}
Now my problem is that how do i set the position of the textfields and buttons in Window1?
With this code they are set in the center of the view aligned horizontally.
I tried to use title.setLocation(5,5); but it's not working. Any suggestions?
Now my problem is that how do i set the position of the textfields and buttons in Window1?
Rows like Jlabel - JTextField then new row ,and in the end of the page the button
The thing is you're not using any layout managers. The default layout manager for JPanel is FlowLayout, which will do exactly what you're experiencing (horizontal layout of the components).
Getting vertical alignment could be achieved by using different layout managers. You could use a GridBagLayout for all the component, or a GridLayout, or you could nest JPanel with different layout managers. The possibilities are endless. It just comes down to the exact look you want.
See Laying out Components Within a Container to learn how to use different layout managers. I'll give you an example, but don't let it stop you from looking at the tutorials. You need to learn them.
Also besides just positioning of the components layout managers use dynamic sizing either by respecting the preferred of components are not respecting them. You can see a picture in this answer of some of the layout managers that do and don't respect preferred sizes.
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class LayoutManagers extends JPanel{
public LayoutManagers() {
JLabel label = new JLabel("Text Field");
JTextField textField = new JTextField(20);
JRadioButton rb1 = new JRadioButton("Radio 1");
JRadioButton rb2 = new JRadioButton("Radio 2");
JButton button = new JButton("Button");
JPanel panel1 = new JPanel();
panel1.add(label);
panel1.add(textField);
JPanel panel2 = new JPanel();
panel2.add(rb1);
panel2.add(rb2);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel3.add(button);
JPanel panel4 = new JPanel(new GridLayout(3, 1));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
setLayout(new GridBagLayout());
add(panel4);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new LayoutManagers());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}