Allignment issue with the JLabel: - java

I'm trying to align my JLabel at the top of the screen but it is showing at the bottom instead. It can be fixed if put some negative values in the Top-Bottom parameter in setBounds, However ! I wish to know why it's behaving like this and how it can be fixed the other way.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class T2{
private JFrame jf;
private JLabel jL;
private JButton b1, b2;
private JRadioButton jr1;
private JTextField tf1, tf2;
private Font ft;
public void run(){
//JFrame
jf = new JFrame("Program");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setLayout(null);
jf.setBounds(0,40,500,500);
//Container
Container c = jf.getContentPane();
//Font
ft = new Font("Consolas",1,25);
//JLABEL
jL = new JLabel();
jL.setText("Enter Name:");
c.add(jL);;
//Top-Bottom Positioning isn't working here..
jL.setBounds(50, 0 , 600, 600);
jL.setFont(ft);
//JTextField
tf1 = new JTextField("Type here...");
c.add(tf1);
tf1.setBounds(200, 0 , 200, 20);
}
public static void main(String args[]){
T2 obj = new T2();
obj.run();
}
}
Here's the screenshot:
LINK

Use a layout (the default BorderLayout does what you want), add the components you want to appear at the top to the layout with the constraint "NORTH", then magically it all works.
Further comments in the code.
class T2 {
private JFrame jf;
private JLabel jL;
private JButton b1, b2;
private JRadioButton jr1;
private JTextField tf1, tf2;
private Font ft;
public void run() {
//JFrame
jf = new JFrame( "Program" );
jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// jf.setVisible( true ); // don't do this until the frame is composed
// jf.setLayout( null ); // yucky in all respects
// jf.setBounds( 0, 40, 500, 500 ); // use setSize() instead
//Container
// Container c = jf.getContentPane(); // normally you just call add()
//Font
ft = new Font( "Consolas", 1, 25 );
// Make panel first
JPanel panelNorth = new JPanel();
//JLABEL
jL = new JLabel();
jL.setText( "Enter Name:" );
jL.setFont( ft );
panelNorth.add( jL );
//Top-Bottom Positioning isn't working here..
// jL.setBounds( 50, 0, 600, 600 );
//JTextField
tf1 = new JTextField( "Type here..." );
// c.add( tf1 );
panelNorth.add( tf1 );
// tf1.setBounds( 200, 0, 200, 20 );
// now just add the panel to the "north" of the jframe border layout
jf.add( panelNorth, BorderLayout.NORTH );
// now make visible
jf.setSize( 600, 480 );
jf.setLocationRelativeTo( null );
jf.setVisible( true );
}
public static void main( String args[] ) {
// Swing is not thread safe, do on EDT
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
T2 obj = new T2();
obj.run();
}
} );
}
}

Related

How to move button to exact location?

I want the buttons and textfield to go in the spaces marked red in the same layout as they are in. look at the picture to understand what I mean.
update: the buttons are in the place now, but the image wont appear on the second panel
how can I move them to there? heres my code so far
package gasindicator;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import java.io.*;
import javax.imageio.*;
import java.net.*;
public class GasIndicator extends JPanel
{
private Image image;
GasIndicator()
{
try
{
image = ImageIO.read(new URL("http://i68.tinypic.com/2ceja8i.png"));
}
catch (IOException ioe)
{
System.out.println("Unable to fetch image.");
ioe.printStackTrace();
}
setLayout( new BorderLayout() );
JLabel background = new JLabel( new ImageIcon(image) );
background.setLayout( new FlowLayout(FlowLayout.LEFT) );
add( background );
JPanel buttonPanel = new JPanel( new GridLayout(0, 3, 6, 5) );
buttonPanel.setBorder( new EmptyBorder(338, 233, 0, 0) );
buttonPanel.setOpaque( false );
//for (int i = 0; i < 7; i++)
{
JButton button = new JButton("Button");
JButton button1 = new JButton("Button");
JButton button2 = new JButton("Button");
JButton button3 = new JButton("Button");
JButton button4 = new JButton("Button");
JButton button5 = new JButton("Button");
button.setPreferredSize( new Dimension(160, 45) );
buttonPanel.add(button);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
buttonPanel.add(button5);
button.addActionListener(new Action());
}
background.add( buttonPanel );
}
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame frame2 = new JFrame("Museums in London");
frame2.setVisible(true);
frame2.setSize(550, 650);
JPanel panel = new JPanel();
frame2.add(panel);
Custom contentPane;
// JFrame frame = new JFrame("JTextField");
contentPane = new Custom();
frame2.setContentPane(contentPane);
}
}
private static void ShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GasIndicator());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> ShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
class Custom extends JPanel {
public BufferedImage image;
public Custom() {
try {
image = ImageIO.read(new URL
("http://www.destination360.com/europe/uk/images/s/museums.jpg"));
} catch (IOException ioe) {
System.out.println("Unable to fetch image.");
ioe.printStackTrace();
}
}
public Dimension getPreferredSize() {
return (new Dimension(image.getWidth(), image.getHeight()));
}
public void paintComponent(Graphics x) {
super.paintComponent(x);
x.drawImage(image, 10, 10, this);
}
}
}
Simple example to demonstrate the concept of using a layout manager with a Border. The size of the buttons has also been tweaked to the size of the buttons in the image:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import java.io.*;
import javax.imageio.*;
import java.net.*;
public class SSCCE extends JPanel
{
private Image image;
SSCCE()
{
try
{
image = ImageIO.read(new URL("http://i68.tinypic.com/2ceja8i.png"));
}
catch (IOException ioe)
{
System.out.println("Unable to fetch image.");
ioe.printStackTrace();
}
setLayout( new BorderLayout() );
JLabel background = new JLabel( new ImageIcon(image) );
background.setLayout( new FlowLayout(FlowLayout.LEFT) );
add( background );
JPanel buttonPanel = new JPanel( new GridLayout(0, 3, 6, 5) );
buttonPanel.setBorder( new EmptyBorder(338, 233, 0, 0) );
buttonPanel.setOpaque( false );
for (int i = 0; i < 6; i++)
{
JButton button = new JButton("Button " + i);
button.setPreferredSize( new Dimension(160, 45) );
buttonPanel.add(button);
}
background.add( buttonPanel );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Yes, there is still some tweaking of the values. But it is easier to adjust the location of the entire panel with one EmptyBorder and all the buttons move at the same time than it is to adjust the location of each button individually.
Note: Don't use the JLabel to display the image as the components will shift if the frame is resized. Instead use your custom panel to paint the image.
The problem here is that your panel has the standart Layoutmanager set onto it.
Try disable it with
contentPane.setLayout(null);
Then you can move the buttons around like you want with button.setBountds(x,y,w,h);
I always draw directly on the Frame, not using a custom panel like you do, but I see that there are use cases where this would be the better way.
If you write
new JFrame.getContentPane().setLayout(null);
your frame gets the default pane and still has it's layout set to null.
The difference is you can add directly to the frame instead of using a panel where you drop your stuff on.
frame.add(new Button().setBounds(x,y,w,h));
Try out this version of the code I tried to debugg:
Custom1 contentPane;
//at first create and set the frame
JFrame frame = new JFrame("Windowname goes here");
frame.setSize(1160, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//next add your custom panel
contentPane = new Custom1();
frame.setContentPane(contentPane);
//better add this to the panel instead of the frame
JTextField textfield = new JTextField(20);
frame.add(textfield);
textfield.setBackground(Color.black);
textfield.setForeground(Color.white);
//you are using 2 panels with null layout here
JPanel panel = new JPanel();
panel.setSize(frame.getHeight(),frame.getWidth()); //give the panel some bounds!
panel.setOpaque(false); //unnecesary
panel.setLayout(null);
panel.setBackground(Color.BLACK);
frame.add(panel);
JButton button = new JButton("London");
JButton button1 = new JButton("Oxford");
JButton button2 = new JButton("Cambridge");
//you seemed to not have added these before
JButton button4 = new JButton("Click");
JButton button5 = new JButton("Click");
JButton button6 = new JButton("Click");
button.setBounds(60, 400, 220, 30);
button.setBackground(Color.black);
button.setForeground(Color.WHITE);
button1.setBounds(x,y,w,h); // !!!! <------
button1.setBackground(Color.black);
button1.setForeground(Color.WHITE);
button2.setBounds(x,y,w,h); // !!!! <------
button2.setBackground(Color.black);
button2.setForeground(Color.WHITE);
button4.setBounds(80, 50, 100, 30);
button5.setBounds(x,y,w,h); // !!!! <------
button6.setBounds(x,y,w,h); // !!!! <------
panel.add(button);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
//SETVISIBLE ALWAYS GOES LAST
frame.setVisible(true);
I patched your code and wrote some comments in it.
I marked the spots where you need to set the bounds for the buttons with !!!!<----, you seemed to have made this for button4 but not for the other ones. Also you should get a better structure in your code, I don't want to insult you but I would call this "spaghetti code".
There are aswell some things that where a problem, for example you seemed to not have added the buttons at all but they where present in your picture...
Let me know if it would work or not after playing around with the bounds value and investigating for eventual mistakes in the code.
Also if you sent me the whole project I could watch over it, but better try it yourself, it won't give you anything if someone else made your work.
Good luck and happy coding ( ͡° ͜ʖ ͡°)

setText method with panel and button

I tried fixing this in so many ways, and tried searching for answers everywhere, my color buttons are working, but same way built number buttons do not....
package tralala;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class DugmiciKojiMenjajuBoju extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 4317497849622426733L;
private JButton dugme1;
private JButton dugme2;
private JButton dugme3;
private JPanel panel;
private JOptionPane a;
private JPanel panel1;
private JButton dugmeBroja0;
private JButton dugmeBroja1;
private JButton dugmeBroja2;
private JButton dugmeBroja3;
private JButton dugmeBroja4;
private JButton dugmeBroja5;
private JButton dugmeBroja6;
private JButton dugmeBroja7;
private JButton dugmeBroja8;
private JButton dugmeBroja9;
private JButton dugmeZaPlus;
private JButton dugmeZaMinus;
private JButton dugmeZaPuta;
private JButton dugmeZaPodeljeno;
private JButton dugmeZaJednako;
private JTextField polje;
DugmiciKojiMenjajuBoju(){
getContentPane().setBackground(Color.white);
this.setLayout(new FlowLayout());
a = new JOptionPane("");
dugme1 = new JButton("zuta");
dugme2 = new JButton("plava");
dugme3 = new JButton("crvena");
dugmeBroja0 = new JButton("0");
dugmeBroja1 = new JButton("1");
dugmeBroja2 = new JButton("2");
dugmeBroja3 = new JButton("3");
dugmeBroja4 = new JButton("4");
dugmeBroja5 = new JButton("5");
dugmeBroja6 = new JButton("6");
dugmeBroja7 = new JButton("7");
dugmeBroja8 = new JButton("8");
dugmeBroja9 = new JButton("9");
dugmeZaPlus = new JButton("+");
dugmeZaMinus = new JButton("-");
dugmeZaPuta = new JButton("*");
dugmeZaPodeljeno = new JButton("/");
dugmeZaJednako = new JButton("=");
polje = new JTextField("", 20);
panel = new JPanel();
panel1 = new JPanel();
dugmeBroja0.setSize(50,50);
dugmeBroja1.setSize(50,50);
dugmeBroja2.setSize(50,50);
dugmeBroja3.setSize(50,50);
dugmeBroja4.setSize(50,50);
dugmeBroja5.setSize(50,50);
dugmeBroja6.setSize(50,50);
dugmeBroja7.setSize(50,50);
dugmeBroja8.setSize(50,50);
dugmeBroja9.setSize(50,50);
panel1.add(dugmeBroja0);
panel1.add(dugmeBroja1);
panel1.add(dugmeBroja2);
panel1.add(dugmeBroja3);
panel1.add(dugmeBroja4);
panel1.add(dugmeBroja5);
panel1.add(dugmeBroja6);
panel1.add(dugmeBroja7);
panel1.add(dugmeBroja8);
panel1.add(dugmeBroja9);
panel1.add(dugmeZaPlus);
panel1.add(dugmeZaMinus);
panel1.add(dugmeZaPuta);
panel1.add(dugmeZaPodeljeno);
panel1.add(dugmeZaJednako);
panel1.add(polje);
panel1.setLayout(new FlowLayout(50, 0 ,0));
FlowLayout mojLayout = new FlowLayout(FlowLayout.CENTER , 20 , 20);
panel.setLayout(mojLayout);
panel.add(dugme1);
panel.add(dugme2);
panel.add(dugme3);
this.setTitle("Kalkulator Koji Menja Boju Pozadine");
this.setSize(500,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.add(panel1);
this.add(panel);
dugme1.addActionListener(this);
dugme2.addActionListener(this);
dugme3.addActionListener(this);
polje.addActionListener(this);
panel.setBackground(Color.white);
panel1.setBackground(Color.white);
}
public static void main(String[] args) {
DugmiciKojiMenjajuBoju a = new DugmiciKojiMenjajuBoju();
a.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if( arg0.getSource() == dugme1){
panel.setBackground(Color.yellow);
panel1.setBackground(Color.yellow);
getContentPane().setBackground(Color.yellow);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D" ,"Postavili ste zutu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme2){
panel.setBackground(Color.blue);
panel1.setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste plavu", JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme3){
panel.setBackground(Color.red);
panel1.setBackground(Color.red);
getContentPane().setBackground(Color.red);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste crvenu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugmeBroja0){
polje.setText("0");
System.out.println("blabla");
}
}
}
My button 0 is not working... so i cannot continue writing the code.
My button 0 is not working... so i cannot continue writing the code.
You didn't add an ActionListener to the button.
However, before just fixing that problem you should simplify your code an learn how to use loops to create multiple components with the same functionality. Here is an example that creates a single ActionListener and add it to each button:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Also, don't use setSize() on your components. The layout manager is responsible for determining the size of a component.
You have never added ActionListener to that button, just to three color buttons and a JTextField polje
I think you didn't added this as the actionListener of dugmeBroja0:
you need this:
dugmeBroja0.addActionListener(this);

Placing buttons under the combo box

How do i make the buttons appear under the combo box here? In other words have button 1 and button 2 right underneath the combo box?
public class GUI extends JFrame implements ListSelectionListener, ActionListener {
private JPanel myPanelA;
private JSplitPane itemPane;
public static void startWindowsGui ( ) {
SwingUtilities.invokeLater ( new Runnable ( ) {
public void run ( ) {
GUI gui = new GUI ( );
gui.setVisible ( true );
}
} );
}
public GUI() {
// Set the layout to a grid
setLayout ( new BorderLayout ( 5, 5 ) );
setTitle ( "UI " );
setSize ( 800, 600 );
setDefaultCloseOperation ( EXIT_ON_CLOSE );
setBackground ( new Color ( 15, 255, 10 ) );
addComponents ( );
}
private void addComponents ( ) {
JSplitPane mainPane = new JSplitPane ( JSplitPane.HORIZONTAL_SPLIT );
itemPane = new JSplitPane ( JSplitPane.VERTICAL_SPLIT );
mainPane.add ( PanelA ( ), JSplitPane.LEFT );
mainPane.add ( itemPane, JSplitPane.RIGHT );
mainPane.setOneTouchExpandable ( true );
itemPane.setOpaque(true);
itemPane.setBackground(new Color(0xffffffc0));
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("C:/Users/Desktop/image.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
//add(picLabel);
itemPane.add(picLabel);
add ( mainPane, BorderLayout.CENTER );
}
private JPanel PanelA ( ) {
myPanelA = new JPanel ( );
myPanelA.setLayout ( new BorderLayout ( 0, 0 ) );
myPanelA.add ( buttonPanel ( ), BorderLayout.NORTH );
myPanelA.setBorder ( new EmptyBorder ( 0, 0, 0, 0 ) );
myPanelA.setBackground(new Color(0,0,0));
return myPanelA;
}
#Override
public void actionPerformed(ActionEvent e) {
}
#Override
public void valueChanged(ListSelectionEvent arg0) {
}
private JPanel buttonPanel ( ) {
// Create the panel
JPanel addButton = new JPanel ( );
JPanel cards; //a panel that uses CardLayout
String BUTTONPANEL = "Card with JButtons";
String TEXTPANEL = "Card with JTextField";
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
//cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "cards".
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 10));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
addButton.add(comboBoxPane, BorderLayout.PAGE_START);
addButton.add(cards, BorderLayout.CENTER);
return addButton;
}
}
Use BoxLayout for the panel instead of it's default layout which is FlowLayout.
See this link: How to Use BoxLayout. In your case, BoxLayout.Y_AXIT will helps.
For example:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
You need to arrange your layout, GridLayout is very good.
You need first to GridLayout(2, 1).
The first row will be assigned to the combo box,
and the second row for a panel with GridLayout(1, 2) for the two buttons.
setLayout(new GridLayout(2, 1));
add(comboBox);
JPanel inner = new JPanel();
inner.setLayout(new GridLayout(1, 2));
add(inner);
inner.add(button1);
inner.add(button2);

JLabel misplaced after adding JPanel

I'm almost blind after reading lots of java swing articles, and still can not get panel to work.
When i add 2 JLabels, they are nicely aligned to left, with 5px padding defined by EmptyBorder, just as i want them to be.
I found that after adding ProgressBar with extra border for padding, does not work as expected, added 1 more panel, where i add ProgressBar. Progress looks good, but all my labels are displaced.
And finally it look like this (RED background is for debug, to see how JPanel draws):
Question1: How to fix this?
Question2: Is it standard approach for swing to place panel inside of other panel with other panels just to get formating i want?
Source:
public class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private static final Border viewPaddingBorder = new EmptyBorder( VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL );
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel( int w, int h ) {
view = new JPanel();
view.setBorder( BorderFactory.createRaisedSoftBevelBorder() );
view.setBackground( Color.LIGHT_GRAY );
view.setSize( w, h );
view.setLayout( new BorderLayout() );
panel = new JPanel();
panel.setBorder( viewPaddingBorder );
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS) );
//panel.setLayout( new SpringLayout() );
panel.setOpaque( false );
JFrame parent = AppContext.getMe().getAppWindow().getFrame();
int posx = (parent.getWidth() - w)/2;
int posy = (parent.getHeight() - h)/2;
view.add( panel, BorderLayout.CENTER );
view.setLocation( posx, posy );
}
private void initTitle() {
title = new JLabel( "Progress title" );
title.setAlignmentX( JComponent.LEFT_ALIGNMENT );
panel.add(title);
}
private void initProgress() {
progressPanel = new JPanel( new BorderLayout() );
progressPanel.setBackground( Color.LIGHT_GRAY );
progressPanel.setBorder( new EmptyBorder( 15, 30, 15, 30) );
progressPanel.setBackground( Color.RED );
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX( JComponent.LEFT_ALIGNMENT );
progressPanel.add(progressBar);
panel.add( progressPanel );
progressDesc = new JLabel( "Progress description" );
panel.add(progressDesc);
}
public AppInitProgressDialog() {
initPanel( 400, 100 );
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
Alternatively, you can use BorderLayout for panel:
panel = new JPanel(new BorderLayout());
...
panel.add(title, BorderLayout.NORTH);
...
panel.add(progressPanel); // default CENTER
...
panel.add(progressDesc, BorderLayout.SOUTH);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;
/**
* #see http://stackoverflow.com/a/16837816/230513
*/
public class Test {
private JFrame f = new JFrame("Test");
private void display() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new AppInitProgressDialog().getView());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel(int w, int h) {
view = new JPanel();
view.setBorder(BorderFactory.createRaisedBevelBorder());
view.setBackground(Color.LIGHT_GRAY);
view.setSize(w, h);
view.setLayout(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setOpaque(false);
view.add(panel, BorderLayout.CENTER);
}
private void initTitle() {
title = new JLabel("Progress title");
title.setAlignmentX(JComponent.LEFT_ALIGNMENT);
panel.add(title, BorderLayout.NORTH);
}
private void initProgress() {
progressPanel = new JPanel(new BorderLayout());
progressPanel.setBackground(Color.LIGHT_GRAY);
progressPanel.setBorder(new EmptyBorder(15, 30, 15, 30));
progressPanel.setBackground(Color.RED);
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX(JComponent.LEFT_ALIGNMENT);
progressPanel.add(progressBar);
panel.add(progressPanel);
progressDesc = new JLabel("Progress description");
panel.add(progressDesc, BorderLayout.SOUTH);
}
public AppInitProgressDialog() {
initPanel(400, 100);
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
Use Layout Managers rather than just adding panels to each other. Specifically in your case I think you can use GridLayout.
panel.setLayout(new GridLayout(1,1,0,0));
Fore more details on layout refer to this tutorial.

How to limit the height of an auto-resizing JTtextArea

I have several text areas aligned vertically. I want them to expand as more text is typed, but put a limit on how tall they'll become.
I've tried setting the max size, but that seems to be ignored. Any ideas?
_recipients = new JTextArea();
_recipients.setBorder( BorderFactory.createEtchedBorder() );
_recipients.setLineWrap( true );
_recipients.setWrapStyleWord( true );
_recipients.setMaximumSize( new Dimension( 111, 55 ) );
_subject = new JTextArea();
_subject.setBorder( BorderFactory.createEtchedBorder() );
_subject.setLineWrap( true );
_subject.setWrapStyleWord( true );
_subject.setMaximumSize( new Dimension( 111, 55 ) );
//JComponent area = LAF.Area.clear( );
JPanel area = new JPanel( new GridLayout( 1, 2, 6, 0 ) );
area.setOpaque( false );
area.add( _recipients );
area.add( _subject );
add( area, BorderLayout.CENTER );
I recieved advice that i should use a scroll pain, but that just created an uneditable area
JScrollPane pain = new JScrollPane();
pain.add( _recipients );
area.add( pain );
pain = new JScrollPane();
pain.add( _subject );
area.add( pain );
EDIT
not much more to it, but
public class TestFrame extends JFrame
{
TestFrame()
{
setSize( new DimensionUIResource( 800, 668 ) );
JPanel area = new JPanel( new FlowLayout( 0, 0, 0 ) );
Stuff thing = new Stuff();
area.add( thing );
add( area );
}
public static void main( String args[] )
{
TestFrame frame = new TestFrame();
frame.show();
}
private static class Stuff extends JComponent
{
private final JTextArea _subject;
Stuff()
{
setLayout( new BorderLayout() );
_subject = new JTextArea();
_subject.setBorder( BorderFactory.createEtchedBorder() );
_subject.setLineWrap( true );
_subject.setWrapStyleWord( true );
_subject.setSize( new Dimension( 111, 55 ) );
_subject.setMaximumSize( new Dimension( 111, 55 ) );
JPanel area = new JPanel( new GridLayout( 1, 2, 6, 0 ) );
area.setOpaque( false );
area.add( _subject );
add( area, BorderLayout.CENTER );
}
}
}
Personally, I prefer not to limit my JTextArea's size lest I prevent the user from adding as much information as needed. Again, I feel you're better off wrapping the JTextArea in a JScrollPane and limiting the JScrollPane vewport's size. This can be done explicitly or implicitly by telling the JTextArea how many rows and columns to start out with. For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class TestPanel extends JPanel {
private static final int AREA_COUNT = 4;
public TestPanel() {
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new GridLayout(0, 1, 0, 5));
for (int i = 0; i < AREA_COUNT; i++) {
JTextArea area = new JTextArea(5, 30);
area.setLineWrap(true);
area.setWrapStyleWord(true);
JPanel wrapPanel = new JPanel(new BorderLayout());
wrapPanel.add(new JLabel("JTextArea " + i), BorderLayout.PAGE_START);
wrapPanel.add(new JScrollPane(area), BorderLayout.CENTER);
add(wrapPanel);
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("TestPanel");
frame.getContentPane().add(new TestPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories

Resources