Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
i want to create java component looks like my picture, because i'm gonna use it manytimes in my application .my idea is add a jpanel[left panel] and a Jlable [right lable] to a jpanel[main panel]. Main panel is the final object which i want to use again and again.
so my first step is create a main panel.and try to use it as a template.but i realized it's not work as i expected .this is my template class this is the class which i going to use again and again.
/////////////////////////////////////////
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
class customCompo extends JPanel {
void customCompoMeth() {
JPanel green = new JPanel();
green.setPreferredSize(new Dimension(80, 150));
green.setBackground(Color.GREEN);
}
}
//////////////////////////////////////////////
i have a another class which consist main method.here it is.how i use my above template again and again.
////////////////////////////////////////////////////////////////////
customCompo c1=new customCompo();
jPanel1.add(c1);
///////////////////////////////////////////////////////////////////
what i'm doing here is create new instance and add it to a component in this case Jpanel1.but it's not working .it gives me errors .i need a help what's my wrong ?am i completely wrong?
If I am able to understand the question in the correct way now, you simply wanted to create one JPanel with some added thingies to it, that one can reuse again and again, without writing the whole code. If that be the case, one simply needs to extend the JPanel and simply put the modifications one needs and reuse it, whereever needed, as already said by #peeskillet.
Do see this code example, and see if this is what you referring to:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ExampleTemplate {
private static final int GAP = 5;
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1, GAP, GAP));
contentPane.setBorder(new EmptyBorder(GAP, GAP, GAP, GAP));
contentPane.add(new TemplatePanel());
contentPane.add(new TemplatePanel());
contentPane.add(new TemplatePanel());
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ExampleTemplate().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class TemplatePanel extends JPanel {
private Random r;
private JPanel leftPanel;
private static final int GAP = 5;
private GridBagConstraints gbc;
public TemplatePanel() {
r = new Random();
setOpaque(true);
setBackground(getRandomColor());
setLayout(new BorderLayout(GAP, GAP));
JPanel footerPanel = getPanel();
footerPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
leftPanel = getPanel();
footerPanel.add(leftPanel, gbc);
gbc.gridx = 1;
gbc.weightx = 0.2;
JLabel rightLabel = new JLabel("Right Label", JLabel.CENTER);
footerPanel.add(rightLabel);
JLabel centerLabel = new JLabel("Main Panel", JLabel.CENTER);
add(centerLabel, BorderLayout.CENTER);
add(footerPanel, BorderLayout.PAGE_END);
}
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(getRandomColor());
return panel;
}
private Color getRandomColor() {
return new Color(r.nextFloat(), r.nextFloat(),
r.nextFloat(), r.nextFloat());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
}
"but it's not working .it gives me errors"
The first error I see in that little bit of code you provided, is the fact that you are trying to add an instance of a non-component class to a JPanel. That will fail. You should make the class extend JComponent, JPanel, or any other JComponent, if you want to add it to another panel.
See Creating GUI with Swing. You may need to get up to speed on the basics :)
Related
I am making a java GUI in which I have some vertical boxes. Inside those boxes, there are some buttons and Labels. I am trying to put the buttons and labels in the center but doesn't work!
I am using this code to set the label in the center.
JLabel update = new JLabel("update");
update.setHorizontalTextPosition(CENTER);
where update is the last component of my vertical box.
The other problem is that I need the window to resize automatically depending on the changes in my GUI (since it is a dynamic one)!
How can I make this too?
I am trying to put the buttons and labels in the center but doesn't work! I am using this code to set the label in the center.
There are several ways to do this, but the easiest for me is to use a GridBagLayout.
If the boxes/container (which hopefully extend from JPanel or JComponent) uses a GridBagLayout, and you add components into the container with GridBagConstraints: gridX and gridY set, but with weightX and weightY set to default of 0, those added components will center in the container.
I can't show code since I have no knowledge of the code you're currently using or the images of your observed/desired GUI's. If you need more help, please edit your question and provide more pertinent information.
The other problem is that I need the window to resize automatically depending on the changes in my GUI (since it is a dynamic one)! How can I make this too?
This will all depend on the layout managers that your GUI is using, something that we have no knowledge of as yet. Again, if you're still stuck, please create and post your Minimal, Complete, and Verifiable Example Program.
For example the following resizable GUI with centered buttons and JLabel texts:
Is created by the following code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class VertBoxes extends JPanel {
private static final String[] LABEL_TEXTS = { "A", "One", "Two", "Monday",
"Tuesday", "January", "Fourth of July",
"Four score and seven years ago" };
public static final int PREF_W = 260;
public static final int PREF_H = 80;
public VertBoxes() {
setLayout(new GridLayout(0, 1, 5, 5));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (String labelTxt : LABEL_TEXTS) {
add(new InnerBox(labelTxt));
}
}
private class InnerBox extends JPanel {
public InnerBox(String labelTxt) {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createLineBorder(Color.black, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JButton("Button"), gbc);
gbc.gridy++;
add(new JLabel(labelTxt), gbc);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
private static void createAndShowGui() {
VertBoxes mainPanel = new VertBoxes();
JFrame frame = new JFrame("Vertical Boxes");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having problems with the components alignment added to JPanel. I am working on a chat application. Which layout should be used be used to get the intended aim. I tried all the layouts but I didn't get the wants. Mostly problems occur when window is resized. Moreover get the idea from the included image about what I want to be achieved.
Thanks in advance.
enter image description here
I whipped up a prototype using BoxLayout, for no other reason than I rarely use it and felt like trying it. Normally, GridBagLayout would be my first choice for this.
EDIT: Added a pic (thanks trashgod!)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MessageAppDemo implements Runnable
{
private String[] messages = new String[] {
"Hello?",
"Hey, what's up?",
"Where are you?",
"Right behind you.",
"Stop following me!",
"But you owe me money.",
"I'll gladly repay you on Tuesday.",
"You said that last week!",
"But now I actually have a job."
};
private int msgCounter = 0;
private JPanel panel;
private JScrollPane scrollPane;
private Timer timer;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new MessageAppDemo());
}
public void run()
{
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
scrollPane = new JScrollPane(panel);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(true);
JFrame frame = new JFrame("Message App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(260, 180);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(1500, new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (msgCounter < messages.length)
{
addMessage(messages[msgCounter]);
}
else
{
timer.stop();
}
}
});
timer.start();
}
private void addMessage(String text)
{
boolean rightAligned = msgCounter % 2 != 0;
Color color = rightAligned ? Color.CYAN : Color.ORANGE;
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBackground(color);
label.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLUE),
BorderFactory.createEmptyBorder(2,4,2,4)
));
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));
if (rightAligned)
{
p.add(Box.createHorizontalGlue());
p.add(label);
}
else
{
p.add(label);
p.add(Box.createHorizontalGlue());
}
panel.add(p);
panel.revalidate();
int x = panel.getPreferredSize().width;
int y = panel.getPreferredSize().height;
panel.scrollRectToVisible(new Rectangle(x-1 ,y-1, 1, 1));
msgCounter++;
}
}
I'm writing a Java GUI application, and is something like this:
JPanel main = new JPanel(new GridLayout(1, 1));
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
main.add(buttonPanel)
I want to add a button to the grid, but i want it centered on the grid panel.
Adding the button to another JPanel allows me to center it to the Grid.
Is there any shorter way to do this?
For example:
JPanel main = new JPanel(new GridLayout(1, 1));
JPanel buttonPanel = JPanel();
main.add(new JPanel().add(button));
This is not working for me.
Thanks :)
I agree with the other commenters that reducing the number of lines of code probably isn't as neccessary as you think it is: Generally speaking, your goal should be to reduce code complexity, not code length, and efforts to minimize length often lead to code that is more complex/hard to understand rather than less.
That said, applying basic OO principles can enable you to shorten your code while maintaining (if not increasing) its clarity:
class CenteredContentPanel extends JPanel {
CenteredContentPanel(JComponent addTo){
this.setLayout(new GridLayout(1,1));
JPanel parentPanel = new JPanel();
parentPanel.add(addTo);
this.add(parentPanel);
}
}
Now, you can add as many of these as you please to a parent container with a single line of code:
JPanel main = new JPanel();
main.add(new CenteredContentPanel(button));
//repeat above line to add as many "centered" components as you need to
(code is untested, as I don't have access to an IDE at the moment, but you get the gist...)
You need to add main to the frame:
add(main.add(new JPanel().add(button)));
This works fine for me:
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrameClass extends JFrame
{
public MyFrameClass(){
JPanel main = new JPanel(new GridLayout(1, 1));
JButton button = new JButton();
add(main.add(new JPanel().add(button)));
setSize(800,600);
setVisible(true);
}
public static void main (String [] args)
{
new MyFrameClass();
}
}
I will place these buttons in the center of the frame and above each other, like this.
BUTTON
BUTTON
BUTTON
I've searched multiple topics on this forum but everything I tried didn't work for so far. I hope that somebody has the solution.
This is my code for so far:
package ípsen1;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Paneel extends JPanel implements ActionListener {
Image achtergrond;
private JButton spelHervatten;
private JButton spelOpslaan;
private JButton spelAfsluiten;
public Paneel(){
//buttons
spelHervatten = new JButton("Spel hervatten");
spelHervatten.setPreferredSize(new Dimension(380, 65));
spelOpslaan = new JButton("Spel opslaan");
spelOpslaan.setPreferredSize(new Dimension(380, 65));
spelAfsluiten = new JButton("Spel afsluiten");
spelAfsluiten.setPreferredSize(new Dimension(380, 65));
//object Paneel luistert naar button events
spelAfsluiten.addActionListener(this);
add (spelHervatten);
add (spelOpslaan);
add (spelAfsluiten);
}
public void paintComponent(Graphics g) {
//achtergrond afbeelding zetten
achtergrond = Toolkit.getDefaultToolkit().getImage("hout.jpg");
//screensize
g.drawImage(achtergrond, 0,0, 1024,768,this);
}
//actie na klik op button
public void actionPerformed(ActionEvent e) {
if(e.getSource() == spelAfsluiten){
System.out.println("Spel afsluiten");
System.exit(0);
}
}
}
You could use a GridBagLayout
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);
add(new JButton("Button"), gbc);
See How to Use GridBagLayout for more details
A BoxLayout might be what you're after. You can specify that you want to add components along the y-axis in the constructor for that particular layout manager.
You could add this line to the constructor of your Paneel class.
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
As for center-aligning everything, I don't know if it's good practice but you can set the horizontal alignment for each of your buttons individually. Example:
spelHervatten.setAlignmentX(CENTER_ALIGNMENT);
Uses a GridLayout for a single column of buttons of equal width.
The buttons stretch as the window's size increases. To maintain the button size, put the GridLayout as a single component into a GridBagLayout with no constraint. It will be centered.
The size of the buttons is increased by setting a margin.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/*
* Uses a GridLayout for a single column of buttons of equal width.
* The buttons stretch as the window's size increases. To maintain
* the button size, put the GridLayout as a single component into a
* GridBagLayout with no constraint. It will be centered.
*/
public class CenteredSingleColumnOfButtons {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new GridLayout(0,1,10,10));
gui.setBorder(new EmptyBorder(20,30,20,30));
String[] buttonLabels = {
"Spel hervatten",
"Spel opslaan",
"Spel afsluiten"
};
Insets margin = new Insets(20,150,20,150);
JButton b = null;
for (String s : buttonLabels) {
b = new JButton(s);
b.setMargin(margin);
gui.add(b);
}
JFrame f = new JFrame("Centered Single Column of Buttons");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setMinimumSize(f.getSize());
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
System.out.println(b.getSize());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
I thought there is no way to do that.
You should get size of Panel/Frame then calculate manually to find to center position for your button.
Rephrased some parts:
You might want to try to put the buttons in JFrame's "wind direction"-style BorderLayout:
http://www.leepoint.net/notes-java/GUI/layouts/20borderlayout.html
Just create a block in the CENTER with one EAST and WEST block with a certain size around it. Then insert the buttons inside of the center block. If you don't want them to be the full size, just add another EAST and WEST.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame{
String fields[] = {"Name", "Address 1", "Address 2", "City", "State", "Zip Code"};
ArrayList<JPanel> pannelArray;
public GUI(){
pannelArray = new ArrayList<JPanel>();
addJPanels();
for(int i = 0; i<pannelArray.size(); ++i){
add(pannelArray.get(i));
}
}
public static void main(String[] args){
GUI window = new GUI();
window.setLayout(new GridLayout(7, 1));
window.setTitle("Enter Your Shipping Address");
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 800);
window.setVisible(true);
}
public void addJPanels(){
for(int i = 0; i<fields.length; ++i){
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,2));
panel.add(new JLabel(fields[i]));
panel.add(new JTextField(""));
pannelArray.add(panel);
}
JPanel panel = new JPanel();
panel.add(new JButton("cancel"));
panel.add(new JButton("okay"));
pannelArray.add(panel);
}
I used that code to create a simple GUI for my class. The following question has asked me to implement the GUI to create a class using the information inside the JTextAreas. I'm quite aware of how to pull data out of a JTextArea, but seeing as I used anonymous references, I'm not sure if it's possible anymore. If not, I'll need to go back to the drawing board to see how I can make this work. A simple point in the right direction would be great, I'm not asking anyone to do my homework for me.
You are already using a String array of fields, why not create an array of JTextFields:
JTextField[] textFields = new JTextField[fields.length];