hi I have tried to implement group layout fro my assignment requirement below is my code snippet but I am having one problem within this code snippet when i do pack(); it throws me exception also I don't know how to make it visible please guide me where I am wrong code suggestion would be helpful
thanks in advance
public class AMS_GUI extends JFrame
{
private JFrame frame;
public AMS_GUI()
{
makeFrame();
}
public void makeFrame()
{
JLabel unitLabel = new JLabel("Units"); // units label
JComboBox unitCombo = new JComboBox(); // units empty combo box
JButton addUnit = new JButton("Add"); // add units button for adding units
JLabel AssessmentLabel = new JLabel("Assessments"); // assessments Label
JComboBox AssessmentCombo = new JComboBox(); // assessments empty combo box
JButton addAssessment = new JButton("Add"); // assessments add button
JLabel TasksLabel = new JLabel("Tasks"); // tasks Label
JComboBox TasksCombo = new JComboBox(); // tasks empty combo box
JButton addTasks = new JButton("Add"); // tasks add button
JButton editTasks = new JButton("Edit");// tasks Edit button
JLabel planLabel = new JLabel("Plans");
JButton makePlan = new JButton("MakePlan");
JButton showPlan = new JButton("ShowPlan");
JButton savePlan = new JButton("SavePlan");
//Set up the content pane.
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(unitLabel)
.addComponent(AssessmentLabel)
.addComponent(TasksLabel)
.addComponent(planLabel)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(unitCombo)
.addComponent(AssessmentCombo)
.addComponent(TasksCombo)
.addComponent(makePlan)
.addComponent(showPlan)
.addComponent(savePlan))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(addUnit)
.addComponent(addAssessment)
.addComponent(addTasks)
.addComponent(editTasks)
)
);
setTitle("AMS_GUI");
pack();
Exception
Exception in thread "main" java.lang.IllegalStateException: javax.swing.JButton
[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,
border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#bb6ab6,flags=296,
maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,
margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,
paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,
selectedIcon=,text=Edit,defaultCapable=true]
is not attached to a vertical group
Exception in thread "main" java.lang.IllegalStateException: javax.swing.JButton
[..]
is not attached to a vertical group
Add a vertical group and add the components to it.
From the JavaDocs:
GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. The horizontal group is responsible for determining the minimum, preferred and maximum size along the horizontal axis as well as setting the x and width of the components contained in it. The vertical group is responsible for determining the minimum, preferred and maximum size along the vertical axis as well as setting the y and height of the components contained in it. Each Component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout, or when the minimum, preferred or maximum size is requested.
Related
I have the following code taken from GeeksforGeeks that displays the contents of a 2-d array in JTable using JScrollPane:
public class JTableExamples {
// frame
JFrame f;
// Table
JTable j;
// Constructor
JTableExamples()
{
// Frame initiallization
f = new JFrame();
// Frame Title
f.setTitle("JTable Example");
// Data to be displayed in the JTable
String[][] data = {
{ "Kundan Kumar Jha", "4031", "CSE" },
{ "Anand Jha", "6014", "IT" }
};
// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };
// Initializing the JTable
j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300);
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}
What I am trying to do is add a simple Component (like JButton) underneath the table but it does not seem to work. I tried modifying the code by adding the JButton to JPanel and adding JPanel to the frame:
JButton button = new JButton("Back");
JPanel panel = new JPanel();
panel.add(button);
f.add(sp);
f.add(panel);
But this simply deletes the entire table and replaces it with a single button. I also tried adding the button to JPanel and adding that JPanel to JScrollPane:
JButton button = new JButton("Back");
JPanel panel = new JPanel();
panel.add(button);
sp.add(panel);
f.add(sp);
But this did not seem to change anything. I also tried to tinker with preferred and maximum size of JScrollPanel to no avail - it always occupies the entire screen and prevents JButton from appearing on the screen.
Not shooting for design here, just functionality: have a JButton appear underneath my JTable. Any suggestions will be greatly appreciated. Thank you in advance!
The default layout manager of a JFrame is the BorderLayout.
f.add(sp);
f.add(panel);
When you don't specify a constraint for the BorderLayout the CENTER is assumed. You can only have a single component added to the CENTER.
Instead your code should be:
f.add(sp, BorderLayout.CENTER);
f.add(panel, BorderLayout.PAGE_END);
Note the default layout manager for a JPanel is the FlowLayout. So the button will be horizontally centered in the panel.
Also, instead of using a JPanel, try adding the button directly to the PAGE_END of the frame to see the difference.
Read the section from the Swing tutorial on Using Layout Manager for more information and examples for using each of the different layout managers to understand the differences of the above suggestions.
Edit:
Is there a way to decrease the height of the table
If you know you have a small table then you can use:
table.setPreferredScrollableViewportSize(table.getPreferredSize());
This will make the scroll pane the size of the table.
Then you use:
//f.setSize(500, 200);
f.pack();
Now all components will be displayed at their preferred size.
im having a little issue with my code. I have created a gridlayout of 5,1,0,0. I have a textfield, 3 buttons and a label where the result analysis of whatever the user had input is displayed at the bottom. Now the results can come on multiple lines depending on how big words are in the sentence, my problem is when multiple lines of results are displayed, the layout of my program changes and i dont know how to keep it the same but just the label or Applet window itself resize if need be?
public class assignment_tauqeer_abbasi extends JApplet implements ActionListener {
JTextArea textInput; // User Input.
JLabel wordCountLabel; // To display number of words.
public void init() {
// This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons
setBackground(Color.black);
getContentPane().setBackground(Color.black);
textInput = new JTextArea();
textInput.setBackground(Color.white);
JPanel south = new JPanel();
south.setBackground(Color.darkGray);
south.setLayout( new GridLayout(5,1,0,0) );
/* Creating Analyze and Reset buttons */
JButton countButton = new JButton("Analyze");
countButton.addActionListener(this);
south.add(countButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
south.add(resetButton);
JButton fileButton = new JButton("Analyze Text File");
fileButton.addActionListener(this);
south.add(fileButton);
/* Labels telling the user what to do or what the program is outputting */
wordCountLabel = new JLabel(" No. of words:");
wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(true);
south.add(wordCountLabel);
/* Border for Applet. */
getContentPane().setLayout( new BorderLayout(2,2) );
/* Scroll bar for the text area where the user will input the text they wish to analyse. */
JScrollPane scroller = new JScrollPane( textInput );
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(south, BorderLayout.SOUTH);
} // end init();
public Insets getInsets() {
// Border size around edges.
return new Insets(2,2,2,2);
}
// end of Applet customisation
This is my code for the layout. Any help would be apprecited!
A GridLayout will size every cell according to the content of the largest cell. Consider using a different layout, or a combination of layouts instead.
The gridLayout that you have used would possibly complicate the five contents that you have used. Try using flow Layout instead this would automatically make space for the new contents that are being entered.
I would like to create something like the following in Swing:
The top part is relatively easy: I can just create a table and display it. What I'm having trouble with is the square plus and minus buttons at the bottom, which are designed to add a new item or remove the selected item respectively. In particular, I haven't been able to make the square shape because on Mac OS X and some other platforms, JButtons are rectangles with rounded corners and I can't find a way to change that. Also, I'm wanting to make sure it's a perfect square and without any space in between buttons.
How can this be accomplished in a cross-platform way on Swing?
JButtons are rectangles with rounded corners and I can't find a way to change that.
Change the Border:
button.setBorder( new LineBorder(Color.BLACK) );
Edit.
Another approach is to create your own icon from an existing button. Something like the following:
JButton button = new JButton("+");
Dimension size = button.getPreferredSize();
size.x += 6;
size.y += 6;
button.setPreferredSize(size);
Rectangle rectangle = new Rectangle(3, 3, size.x - 3, size.y - 3);
ScreenImage buttonImage = ScreenImage(button, rectangle);
ImageIcon icon = new ImageIcon(buttonImage);
JButton plus = new JButton(icon);
plus.setBorder( ... );
The above code should create an image of your button on any platform. I increased the preferred size to avoid taking an image of the border.
You will need to use the Screen Image class.
This is most easily achieved by returning a preferred size that is NxN - where N is the larger of preferred width or height.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int s = (int)(d.getWidth()<d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension (s,s);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JComponent gui = new JPanel(new FlowLayout());
for (int ii=0; ii<5; ii++) {
gui.add(new SquareButton("" + ii));
}
gui.setBorder(new EmptyBorder(4, 8, 4, 8));
JFrame f = new JFrame("Square 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();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
You can set the size of a button using using setPreferredSize():
JButton button = new JButton("+");
button.setPreferredSize(new Dimension(10, 10));
You might be able to remove the rounded corners using:
button.setBorder(BorderFactory.createEmptyBorder());
If this does not work then you can override the paintComponent() method on JButton.
Well in order to make them square, you have 2 options: 1. Make the button hold an icon image of just a square image of a transparent image. 2. you could set the button dimensions on your own. I am not sure how to set the dimensions, but that is a an option you could choose. You can just create a JToolBar that is set on the BorderLayout.SOUTH end of the window whenever you add, and whatever buttons are added onto that, will be right next to each other. To add the buttons do this:
JButton button1 = new JButton("+");
JButton button2 = new JButton("-");
JToolBar toolbar = new JToolBar();
<JPanel,JFrame,Whatever>.add(toolbar, BorderLayout.SOUTH);
toolbar.add(button1);
toolbar.add(button2);
This will add the toolbar onto the JFrame, JPanel, or whatever you're adding it onto, and it will set it to the bottom of the screen as you see above.
Hope this helps!
This is my first time really using graphics with Java.
I have a problem where I'm trying to populate a JScrollPane with an undefined number of panels (The following code is just a test; I know it's written using bad practices, but it's a test to see how to do it is all).
In the final program I'm going to have an ArrayList of orders (ArrayList size not predetermined), and in a JScrollPane I'm going to have a JPanel that holds a JPanel (each containing several labels) that will have details of each order.
here's the current test code (the JScrollPane is simply named scrollPane):
JPanel panel = new JPanel();
GroupLayout experimentLayout = new GroupLayout(panel);
ArrayList<JPanel> panelArray = new ArrayList();
for(int i = 0; i <3; i++){
JPanel panel2 = new JPanel();
JLabel label2 = new JLabel("Hello");
JLabel label3 = new JLabel("Hi");
panel2.add(label2);
panel2.add(label3);
//panel.add(panel2);
panelArray.add(panel2);
}
experimentLayout.setHorizontalGroup(
experimentLayout.createParallelGroup()
.addComponent(panelArray.get(0))
.addComponent(panelArray.get(1))
.addComponent(panelArray.get(2))
);
experimentLayout.setVerticalGroup(
experimentLayout.createSequentialGroup()
//.addGroup(experimentLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(panelArray.get(0))
.addComponent(panelArray.get(1))
.addComponent(panelArray.get(2))
);
scrollPane.setViewportView(panel);
When this runs, the JPanels that contain the labels are displayed horizontally (next to each other) instead of under one another.
Any help on how I could go about displaying them vertically would be a great help - Thank you all :)
You might find GridLayout to be useful.
How to place components in layout on specific position.
Like I want to place 2 text boxes in first row, below 3 combo boxes.
But when I am trying to put they all appear in one line and I have used flowlayout. I have used the border as well. When I am resizing, the window sizes of the components are going out from border.
Can you suggest me some layouts to use and how to use it?
Here is my code :
topPanel=new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.setBorder(new TitledBorder(new EtchedBorder(), "Customer Data"));
CNameTextField = new JTextField (20); // create the Customer Name text field
CNameTextField.setEditable(true); // set editable text box
CIDLabel=new JLabel("Customer ID");
C_IDTextField = new JTextField (10);
C_IDTextField.setEditable(true); // set editable text box
topPanel.add(CNameTextField);
topPanel.add(C_IDTextField);
// Create and populate Room type combo box
roomTypeCombo = new JComboBox();
roomTypeCombo.addItem( "Budget($50)" );
// Create and populate Meal type combo box
mealCombo = new JComboBox();
mealCombo.addItem( "None" );
// Create and populate Days combo box
daysCombo = new JComboBox();
for(int i=0;i<31 ; i++) {
// populate combobox with days
daysCombo.addItem(i);
}
// Adding rest of the components to top panel
topPanel.add(roomTypeCombo);
topPanel.add(mealCombo);
topPanel.add(daysCombo);
Thanks.
The most specific type of layout is absolute positioning.
Warning: Absolute positioning should rarely, if ever, be used. There are many reasons why. Here is one: Absolute positioning (No layout manager) vs. absolute positioning in MiGlayout
- Thanks to user brimborium for the good idea of adding a warning.
That being said, here is how to use absolute positioning:
In your code above, instead of setting topPanel's layout to FlowLayout, set it to null.
topPanel.setLayout(null);
Later on in the code, right before you start adding components to topPanel, call the container's setBounds method:
someJComponent.setBounds(x-coord, y-coord, width, height);
So for example you created an instance of JComboBox() and named it roomTypeCombo, the following code shows how to absolutely position roomTypeCombo.
topPanel.setLayout(null);
// code...
roomTypeCombo = new JComboBox();
// code...
roomTypeCombo.setBounds(100, 100, 200, 50);
topPanel.add(roomTypeCombo);
The setBounds method, used above, has four parameters:
int x-coord - set roomTypeCombo's x-coordinate relative to
its parent, topPanel.
int y-coord - set roomTypeCombo's y-coordinate relative to its parent, topPanel.
int width - specify roomTypeCombo's width.
int height - specify roomTypeCombo's height.
I would just play around with the coordinates and see if you like anything that comes out of it. The worst thing that could happen is that you go back to using a layout, which is probably better than absolute positioning. Or you could implement your own layout manager, if you follow this hyperlink the first answer talks about implementing your own layout manager and has helpful links.
More information on absolute positioning
Try to change the layout.
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
You could go for a GridLayout with two lines (for example, there is some others possible combinations), with each line containing respectively 3 JComboBoxs, and two JTextFields.
Look carefully at the documentation and check out some examples easily reachable on the web.
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingResizeJFrame {
public SwingResizeJFrame() {
JTextField TextField1 = new JTextField("firstTextField");
JTextField TextField2 = new JTextField("secondTextField");
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(0, 2, 10, 10));
firstPanel.add(TextField1);
firstPanel.add(TextField2);
JComboBox comboBox1 = new JComboBox(new Object[]{"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});
JComboBox comboBox2 = new JComboBox(new Object[]{"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});
JComboBox comboBox3 = new JComboBox(new Object[]{"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(0, 3, 10, 10));
secondPanel.add(comboBox1);
secondPanel.add(comboBox2);
secondPanel.add(comboBox3);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2, 1, 10, 10));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(firstPanel);
frame.add(secondPanel);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SwingResizeJFrame demo = new SwingResizeJFrame();
}
});
}
}