I have a JPanel that is not part of a JFrame. For various reasons I have to call the panel's paint method through my own "update" method.
This is my code:
public void onLoad ()
{
panel = new JPanel ();
panel.setBounds (0,0,Main.WIDTH,Main.HEIGHT);
panel.setLayout (new BoxLayout (panel, BoxLayout.Y_AXIS));
addButton ("button1", panel);
addButton ("button2", panel);
}
private void addButton (String text, Container container)
{
JButton button = new JButton (text);
button.setPreferredSize (new Dimension (100,20));
button.setAlignmentX (Component.CENTER_ALIGNMENT);
container.add (button);
}
public void onRender (Graphics2D g)
{
panel.paint (g);
}
This only paints the panel's background color. If I add button.setBounds(...) in the addButton method then it does paint the buttons but not affected by the BoxLayout.
So I want the buttons to be affected by the BoxLayout obviously. I'm not that savvy on how exactly Swing works so I'm not sure how to do this. JFrame has a pack() method which I think is what I need but some equivalent for JPanels since JPanels doesn't have that method.
I don't know what you're looking for, but for me this works well.
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestApplet extends JApplet{
public static void main(String[] args){
new TestApplet();
}
public TestApplet(){
this.setSize(400,400);
this.add(getCustPanel());
this.setVisible(true);
}
private JPanel getCustPanel() {
JPanel panel = new JPanel ();
panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS));
addButton ("button1", panel);
addButton ("button2", panel);
return panel;
}
private void addButton (String text, JPanel container)
{
JButton button = new JButton (text);
button.setPreferredSize (new Dimension(100,20));
button.setAlignmentX (Component.CENTER_ALIGNMENT);
container.add (button);
}
}
Related
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:
I am new to java, and learning new things everyday.
Today i stumbled upon an error i just can not get fixed.
So i've got a JFrame with a JPanel inside, now I want to remove the Jpanel when i click on my Start game JLabel, and make it transition into my game JPanel ( for now i use a test JPanel)
JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JFrame {
JPanel panel;
JFrame frame;
JButton playlabel;
public void mainmenu() {
frame = new JFrame();
panel = new JPanel();
playlabel = new JButton ("Nieuw Spel");
//frame
frame.setSize(new Dimension(800, 600));
frame.getContentPane().setBackground(new Color(14,36,69));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize());
frame.setVisible(true);
//panel
Dimension expectedDimension = new Dimension(690, 540);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(new Color(14, 36, 69));
panel.add(playlabel);
playlabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
//playlabel
playlabel.setFont(new Font("Old English Text MT", Font.BOLD, 40));
playlabel.setBounds(250, 350, 50, 20);
playlabel.setForeground(new Color(217,144,39));
playlabel.setBackground(new Color(14,36,69));
playlabel.setBorderPainted(false);
playlabel.setFocusPainted(false);
playlabel.addActionListener(new PlayListener());
}
private class PlayListener extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel panelgame = Game.Game();
this.remove(panel);
this.add(panelgame);
this.revalidate();
}
}
}
Game class:
package labyrinthproject.View;
import java.awt.Color;
import javax.swing.JPanel;
public class Game {
public static JPanel Game(){
JPanel panel = new JPanel();
panel.setSize(690, 540);
panel.setBackground(new Color(255,36,69));
return panel;
}
}
if anyone could explain this to me why this doesn't work, it would be greatly appreciated!
Thank you very much!
Sincerely,
A beginner java student.
There are quite some issues in your code
Create the GUI on the event dispatch thread
Don't extend JFrame (you have three (three!) JFrames floating around there!)
Follow the naming conventions
Don't overuse static methods
Only store the instance variables that you really need to represent your class state
Don't use manual setSize or setBounds calls. Use a LayoutManager instead
The call to frame.setVisible(true) should be the last call, after the frame has been completely assembled
Consider a CardLayout for switching between panels ( http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html )
Slightly cleaned up, but the exact structure depends on what you actually want to achieve at the end:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainMenu extends JPanel
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new MainMenu();
mainFrame.getContentPane().add(mainMenu);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
MainMenu()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Dimension expectedDimension = new Dimension(690, 540);
setPreferredSize(expectedDimension);
setBackground(new Color(14, 36, 69));
JButton newGameButton = new JButton ("Nieuw Spel");
newGameButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
newGameButton.setFont(new Font("Old English Text MT", Font.BOLD, 40));
newGameButton.setForeground(new Color(217,144,39));
newGameButton.setBackground(new Color(14,36,69));
newGameButton.setBorderPainted(false);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(new PlayListener());
add(newGameButton);
}
private class PlayListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
removeAll();
GamePanel gamePanel = new GamePanel();
add(gamePanel);
revalidate();
}
}
}
class GamePanel extends JPanel
{
GamePanel()
{
setBackground(new Color(255,36,69));
}
}
You should use a JButton and not a JLabel. Then:
you add to your JButton : Your_JB.addActionListener(this); (don't forget to implement ActionListener to your class).
Now, we are gonna add the detector:
#Override
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Your_JB){
panel.setVisible(false);
}
}
When you click the button, it will make your panel disapear.
Try this:
this.remove(panel);
this.validate();
this.repaint(); //if you use paintComponent
this.add(panelgame);
this.revalidate();
Swing is hard to making nice UI. You just need to use validate() after remove().
I hope it's helpfull.
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);
}
});
}
}
Can anybody tell me what is the problem in following program? I want to fit JScrollPane on JtextArea but when I add it then JTextArea is not visible.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Area extends JFrame
{
private JTextArea ta;
private JTextField tf;
JScrollPane jp;
public Area()
{
super("Text Area");
tf=new JTextField();
tf.setBounds(100,350,300,30);
add(tf);
ta=new JTextArea();
ta.setBounds(100,100,300,200);
jp= new JScrollPane(ta);
add(jp);
setLayout(null);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String...s)
{
new Area();
}
}
I see several problems:
Don't use a null layout; do use a real layout.
The default layout of JFrame is BorderLayout; the default position is CENTER; only one component can occupy a position at a time; the example below uses NORTH & CENTER.
Use the appropriate constructor parameters to size the text components initially.
The scrollbar will appear automatically whenever the scrollpane is smaller than the enclosed component; resize the frame to see the effect.
As shown here, the frame's size is made smaller for effect.
See also Initial Threads.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/** #see https://stackoverflow.com/a/19215436/230513 */
public class Area extends JFrame {
public Area() {
super("Text Area");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField tf = new JTextField(12);
add(tf, BorderLayout.NORTH);
JTextArea ta = new JTextArea(24, 12);
JScrollPane jp = new JScrollPane(ta);
add(jp, BorderLayout.CENTER);
pack();
// arbitrary size to make vertical scrollbar appear
setSize(240, 240);
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Area();
}
});
}
}
Try this:
public Area()
{
super("Text Area");
tf=new JTextField();
tf.setBounds(100,350,300,30);
add(tf);
ta=new JTextArea();
jp= new JScrollPane(ta);
jp.setBounds(5, 5, 100, 100);
add(jp);
setLayout(null);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
You have to use setBounds on JScrollPane, not on JTextArea
sounds like its added but its not shown because of the policy try this:
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
I designed an interface for the welcome screen with one JFrame included two JPanels (JPanel1 on right and JPanel2 on left). The buttons on the left is to switch the Panels in JPanel1. I want to press on a button to replace JPanel1 content with another JPanel but I don`t know how. Please help.
Here is a very simple example of something that should approximate your description. On the left, we have a hug button to toggle the content of the right panel. On the right, you have a panel with a given border and a label. When you press the button, the content on the right is swapped with the other panel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout2 {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel leftPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Left panel");
leftPanel.add(label, BorderLayout.NORTH);
JButton button = new JButton("Toggle right panel");
leftPanel.add(button);
frame.add(leftPanel, BorderLayout.WEST);
final CardLayout cardLayout = new CardLayout();
final JPanel rightPanel = new JPanel(cardLayout);
rightPanel.setPreferredSize(new Dimension(200, 500));
JPanel rightPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
rightPanel1.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel rightPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JLabel label1 = new JLabel("Right panel 1 with a red border");
JLabel label2 = new JLabel("Right panel 2 with a blue borer");
rightPanel1.add(label1);
rightPanel2.add(label2);
rightPanel.add(rightPanel1, "panel1");
rightPanel.add(rightPanel2, "panel2");
frame.add(rightPanel, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(rightPanel);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestCardLayout2().initUI();
}
});
}
}
An alternative to CardLayout would be JRootPane and its JRootPane.setContentPane() method. Here's an example:
final JPanel panel1 = ...;
final JPanel panel2 = ...;
boolean showingPanel1 = true;
final JRootPane rootPane = new JRootPane();
rootPane.setContentPane(panel1);
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (showingPanel1) {
rootPane.setContentPane(panel2);
} else {
rootPane.setContentPane(panel1);
}
showingPanel = !showingPanel;
}
});
Add the rootPane and switchButton components to your window, and then clicking switchButton will switch out the panels.
Here's a tutorial. You should mostly be concerned with JRootPane.setContentPane, the other stuff in the tutorial isn't relevant.
The best answer I found is that I will create one JFrame only and gonna make one big JPanel include two JPanels (JPanelLeft include the buttons and JPanelRight include what the button do) then I will copy the main JPanel for each JButton.
When I press on any button I will do (JFrame.getContentPane.removeAll) to remove the old JPanel then (JFrame.getContentPane.Add(NewJPanel).
This works for me and keep my design as I Want. Thanks for every body.