I wanted components deployment like this picture:
I wrote a code that makes two JPanel in a JFrame and puts components JPanel on left side. I set Frame Layout to BorderLayout and Each panel's Layout to FlowLayout. However, result was not what I wanted. Even List is not appear.
Result picture:
Can you tell me what to do?
There is a code below.
package com.java.APISearch;
import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JPanel search;
JPanel result;
JLabel ksLb;
JTextField ksTf;
JButton ksOK;
JCheckBox choicePackage;
JCheckBox choiceClass;
JCheckBox choiceFunc;
JTextField dsTf;
JButton dsOK;
JLabel rcLb;
JList<String> rcList;
JTextField resultTf;
Container contentPane;
public MainFrame(String title) {
super(title);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
setLocation(screenSize.width/2 - 300, screenSize.height/2 - 200);
setSize(new Dimension(600, 400));
setResizable(false);
setLayout(new BorderLayout());
search = new JPanel();
result = new JPanel();
search.setLayout(new FlowLayout(FlowLayout.LEFT));
search.setSize(new Dimension(300,400));
result.setLayout(new FlowLayout());
result.setSize(new Dimension(300,400));
contentPane = getContentPane();
contentPane.add(search, BorderLayout.WEST);
contentPane.add(result, BorderLayout.EAST);
ksLb = new JLabel("키워드 검색");
ksTf = new JTextField(20);
ksOK = new JButton("검색");
search.add(ksLb);
search.add(ksTf);
search.add(ksOK);
choicePackage = new JCheckBox("package");
choiceClass = new JCheckBox("class");
choiceFunc = new JCheckBox("function");
dsTf = new JTextField(20);
dsOK = new JButton("검색");
search.add(choicePackage);
search.add(choiceClass);
search.add(choiceFunc);
search.add(dsTf);
search.add(dsOK);
rcLb = new JLabel("recent search");
rcList = new JList<String>();
search.add(rcLb);
search.add(rcList);
}
}
The common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers.In this case, for example start by dividing the design into two areas:
Serach panel added to JFrame's NORTH, and a main panel added to JFrame's CENTER. The main panel is a container for all other gui components. See more info in the code.
Here is a skeleton to demonstrate the strategy. Note the comments :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
setSize(new Dimension(600, 400));
setResizable(false);
//setLayout(new BorderLayout());// no need. its the default for JFrame
JPanel search = new JPanel();
search.setLayout(new FlowLayout(FlowLayout.LEFT));
//search.setSize(new Dimension(300,400)); //let layout manager set size
//set preferred size if needed
JLabel ksLb = new JLabel("Search:");
JTextField ksTf = new JTextField(20);
JButton ksOK = new JButton("Click Me");
search.add(ksLb);
search.add(ksTf);
search.add(ksOK);
add(search, BorderLayout.NORTH); //add search to content pane
//construct a container to hold all the rest
//set border layout to it
JPanel mainPanel = new JPanel(new BorderLayout());
//add content to mainPanel:
//add result to NORTH
//add a JPanel to hold list and label to CENTER
add(mainPanel, BorderLayout.CENTER);//main to content pane
setVisible(true);
}
}
More examples of applying this strategy: 1 2 and 3
To make thing like this, use NetBeans (or some other tool that will help you create layout).
In NetBeans, getting something like you want takes ~5 minutes. It's really easier comparing to writing code for yourself.
In my personal opinion, GridBagLayout is the best thing when it comes to most of Swing based components. You can easily take control over each and every cell (whether it should grow or not, how anchors should behave, whether components should fill cell or not, etc.).
Take a look here: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
If you don't know which layout would suit you best, you can always take a look here:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
For NetBeans tutorial, take a look here: https://netbeans.org/kb/docs/java/quickstart-gui.html
Related
Well, actually I have a Layout problem in java Swing. I simply want to add a JPanel on the bottom of a Frame - a coding snipplet that might be done with every web based language in about 5 Minutes. Not so in Java. I tried to add a jPanel to a jFrame, that Contains a jContentPane, set the size of the jPanel to what I need and to repaint and revalidate the jFrame, as well as setting the LayOutManager to null.
Java shows me in this case a full-width jPanel, that fills my whole jFrame.
Therefore I tried another approach: I divided my jPanel in a fully transparent jPanel on top and a 20%opaque jPanel on the bottom. Still it didn't work out as expected.
Since then I tried to resize the child jPanels of my new Panel and the Panel as well and tried to repaint and revalidate the jFrame. Without any effect.
Despite of my efforts, java still shows me a full sized 20%opaque jPanel on the whole jFrame, that now contains another 20%opaque jPanel on Top.
I know that this whole problem is caused by the LayoutManager, Java useless per Default. However, it is not an option to set the LayoutManager to null or even change the LayoutManager of our jFrame, because that would lead us to refactor the whole functionality of our tiny app we worked on for several weeks.
public void showUndoPanel() {
System .out.println("Show Undo Panel");
JPanel myPanel = new JPanel(null);
JPanel glassPanel = new JPanel();
JPanel ContentPanel = new JPanel();
JLabel myJLabel = new JLabel("Great Job!");
myPanel.setBackground(new Color(255,122,122,100));
glassPanel.setSize(650, 550);
glassPanel.setBackground(new Color(255,122,122,100));
myPanel.add(glassPanel);
ContentPanel.setSize(650, 30);
ContentPanel.setBackground(new Color(255,122,122,20));
ContentPanel.add(myJLabel);
myPanel.revalidate();
myPanel.repaint();
undoPanel = myPanel;
myJFrame.add(undoPanel);
myJFrame.revalidate();
}
What I expected:
What it actually does:
Well, I solved the problem by using a BoxLayoutManager and a RigidArea. In case if anyone else may encounter that problem again in the future, I decided to provide the code for this simple solution.
public void showUndoPanel() {
System .out.println("Show Undo Panel");
JPanel myPanel = new JPanel(null);
JPanel glassPanel = new JPanel();
JPanel ContentPanel = new JPanel();
JLabel myJLabel = new JLabel("Great Job!");
myPanel.setBackground(new Color(255,255,255,0));
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.PAGE_AXIS));
glassPanel.setSize(650, 650);
glassPanel.setBounds(0,0,650,550);
glassPanel.setBackground(new Color(255,122,122,0));
myPanel.add(glassPanel);
myPanel.add(Box.createRigidArea(new Dimension(0,450)));
ContentPanel.setSize(650, 30);
ContentPanel.setBounds(0,750,650,30);
ContentPanel.setBackground(new Color(255,122,122,20));
ContentPanel.add(myJLabel);
myPanel.add(ContentPanel);
myPanel.revalidate();
myPanel.repaint();
undoPanel = myPanel;
myJFrame.add(undoPanel);
myJFrame.revalidate();
}
Now it behaves as expected:
BorderLyout would make it easier to implement.
Note the comments in the following mre:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
private static JFrame myJFrame;
public static void main(String[] args) {
myJFrame = new JFrame();
myJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myJFrame.setLocationRelativeTo(null);
showUndoPanel();
myJFrame.pack();
myJFrame.setVisible(true);
}
public static void showUndoPanel() {
JPanel myPanel = new JPanel();
myPanel.setBackground(new Color(255,255,255,0));
myPanel.setLayout(new BorderLayout());
JPanel glassPanel = new JPanel(); //uses FlowLayout by default
//glassPanel.setSize(650, 650); //use preferred size
glassPanel.setPreferredSize(new Dimension(650, 650));
//glassPanel.setBounds(0,0,650,550); //no need to set bounds. bounds are set by the layout manager
glassPanel.setBackground(new Color(255,122,122,0));
myPanel.add(glassPanel, BorderLayout.CENTER);
JPanel contentPanel = new JPanel(); //uses FlowLayout by default
//contentPanel.setSize(650, 30);//use preferred size
contentPanel.setPreferredSize(new Dimension(650, 30));
//contentPanel.setBounds(0,750,650,30); //no need to set bounds. bounds are set by the layout manager
contentPanel.setBackground(new Color(255,122,122,20));
JLabel myJLabel = new JLabel("Great Job!");
contentPanel.add(myJLabel);
myPanel.add(contentPanel, BorderLayout.SOUTH);
myJFrame.add(myPanel);
}
}
How do I use multiple JPanel containers to make this code look like this?
This is the image of what my code is supposed to be like but I cant figure it out.
I can only use GridLayout, BorderLayout and FlowLayout. As a beginner, We've only been over basic concepts but I need more help.
I am also not permitted to use GridBagLayout. I appreciate all the help.
A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers.
In this case, consider dividing the design into 3 areas (JPanels) nested in a main JPanel:
If you can't use GridBagLayout you can implement bottom panel using BoxLayout.
BoxLayout is a valid option also for main panel, to allow for different child panels (top, center, bottom) height.
Demo:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lab1 extends JFrame
{
public Lab1() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel main = new JPanel(new GridLayout(3,1));
//to allow different child-panels height use BoxLayout
//BoxLayout boxLayout = new BoxLayout(main, BoxLayout.Y_AXIS);
add(main);
JPanel top = new JPanel(new GridLayout(1,3));
main.add(top);
top.add(getPanel(Color.RED));
top.add(getPanel(Color.GREEN));
top.add(getPanel(Color.BLUE));
JPanel center = new JPanel(new GridLayout(1,4));
main.add(center);
center.add(getPanel(Color.YELLOW));
center.add(getPanel(Color.CYAN));
center.add(getPanel(Color.BLACK));
center.add(getPanel(Color.LIGHT_GRAY));
JPanel bottom = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.LINE_AXIS));
main.add(bottom);
bottom.add(getPanel(Color.PINK));
JPanel rightPane = getPanel(Color.MAGENTA);
rightPane.setPreferredSize(new Dimension(900, 200));
bottom.add(rightPane);
pack();
setVisible(true);
}
private JPanel getPanel(Color color) {
JPanel panel = new JPanel();
panel.setBackground(color);
panel.setPreferredSize(new Dimension(300, 200));
return panel;
}
public static void main(String args[])
{
new Lab1();
}
}
I need guidance with GUI Layouts
To narrow it down to main points:
I have three main JPanels (info section, operations and data
structure)
I cannot populate these without the JLabels being shifted
I need a sub-panel for operations with a grid layout (cannot get this
to work and it's really annoying me now)
I need it to look like the picture below
Red separator lines are optional to make it a bit more neater
My next step is to implement a stack but I want to first make it look normal.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class StackPanel extends JPanel {
JPanel west, westSub1, east, south, southSub1;
JTextArea infoText, popText, pushText, peekText, resultText;
JLabel aTitle, bTitle, cTitle, Result;
JButton push, pop, peek, test;
public StackPanel() {
// Creating JPanels
setLayout(new BorderLayout());
west = new JPanel();
westSub1 = new JPanel(new GridLayout(3,2));
east = new JPanel();
south = new JPanel();
west.add(westSub1);
// Creating JLabels / JTextArea
aTitle = new JLabel("Operations");
bTitle = new JLabel("Data Structure Contents");
cTitle = new JLabel("Information");
infoText = new JTextArea("This is where commands will be displayed.");
pushText = new JTextArea("pushtxt");
popText = new JTextArea("poptxt");
peekText = new JTextArea("g");
resultText = new JTextArea("");
west.add(aTitle);
westSub1.add(pushText);
westSub1.add(popText);
westSub1.add(peekText);
westSub1.add(resultText);
east.add(bTitle);
south.add(cTitle);
south.add(infoText);
// Creating & Adding JButtons
push = new JButton("PUSH");
pop = new JButton("POP") ;
peek = new JButton("PEEK");
test = new JButton("TEST");
westSub1.add(push);
westSub1.add(pop);
westSub1.add(peek);
westSub1.add(test);
// Setting the placements of GUI objects
add(west, BorderLayout.WEST);
add(east, BorderLayout.CENTER);
add(south, BorderLayout.SOUTH);
// Declaring JPanel sizes // Width|Height
west.setPreferredSize(new Dimension(200,200));
east.setPreferredSize(new Dimension(400,100));
south.setPreferredSize(new Dimension(100,150));
// Setting black borders for JPanels
west.setBorder(BorderFactory.createLineBorder(Color.black));
east.setBorder(BorderFactory.createLineBorder(Color.black));
south.setBorder(BorderFactory.createLineBorder(Color.black));
// Setting JPanel background colours
west.setBackground(new Color(234,237,242));
east.setBackground(new Color(255,255,255));
south.setBackground(new Color(240,240,240));
}
}
Maybe instead of using labels at the top of each of the west/east/south panels you can use a TitledBorder. This will put a rectangular line around the panel with a title at the top.
Read the section from the Swing tutorial on How to Use Borders for more information and working examples.
If you don't want to do this then you will probably need to change the default FlowLayout or each of the panels to another layout. For example you could use a BorderLayout. Then add the label to the PAGE_START and the other components to the CENTER. The main point is you can nest panels with different layout to achieve your desired layout.
Here is something to get you started. Please read comments and don't hesitate to ask for clarifications as needed.
I did not do all needed layout changes: I did just about to demonstrate waht should be done, so you get the idea.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class StackPanel extends JPanel {
JPanel west, westSub1, east, south, southSub1;
JTextArea infoText, popText, pushText, peekText, resultText;
JLabel aTitle, bTitle, cTitle, Result;
JButton push, pop, peek, test;
public StackPanel() {
// Creating JPanels
setLayout(new BorderLayout());
// Creating JLabels / JTextArea
aTitle = new JLabel("Operations");
bTitle = new JLabel("Data Structure Contents");
west = new JPanel();
//you need to set layout manager to the panel, to lay out its components
west.setLayout(new BorderLayout());
west.setPreferredSize(new Dimension(200,200));
west.setBorder(BorderFactory.createLineBorder(Color.black));
west.setBackground(new Color(234,237,242));
add(west, BorderLayout.WEST);
west.add(aTitle, BorderLayout.NORTH);//use panel's layout manager
//you have 4 rows so GridLayout(3,2) is wrong
westSub1 = new JPanel(new GridLayout(4,2));
//for a grid layout: add components in the right order
push = new JButton("PUSH");
westSub1.add(push);
pushText = new JTextArea("pushtxt");
westSub1.add(pushText);
pop = new JButton("POP") ;
westSub1.add(pop);
popText = new JTextArea("poptxt");
westSub1.add(popText);
peek = new JButton("PEEK");
westSub1.add(peek);
peekText = new JTextArea("g");
westSub1.add(peekText);
test = new JButton("TEST");
westSub1.add(test);
resultText = new JTextArea("");
westSub1.add(resultText);
west.add(westSub1, BorderLayout.CENTER);//use panel's layout manager
east = new JPanel();
east.setPreferredSize(new Dimension(400,100));
east.setBorder(BorderFactory.createLineBorder(Color.black));
east.setBackground(new Color(255,255,255));
east.add(bTitle);
add(east, BorderLayout.CENTER);
south = new JPanel();
//you need to set layout manager to the panel, to lay out its components
south.setLayout(new BorderLayout());
south.setPreferredSize(new Dimension(100,150));
south.setBorder(BorderFactory.createLineBorder(Color.black));
south.setBackground(new Color(240,240,240));
add(south, BorderLayout.SOUTH);
cTitle = new JLabel("Information");
south.add(cTitle, BorderLayout.NORTH); //use panel's layout manager
infoText = new JTextArea("This is where commands will be displayed.");
south.add(infoText, BorderLayout.CENTER);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new StackPanel());
frame.pack();
frame.setVisible(true);
}
}
The code has all the imports it needs, as wall as a main to run it.
For more information about how a code should be posted, please read :
https://stackoverflow.com/help/mcve
It's a long time ago that I worked with Swing. But I had the same troubles with the default layouts of Swing. My tip is to change to the TableLayout. It's really easy to use and you can get exact results.
Please check the tutorial: http://www.clearthought.info/sun/products/jfc/tsc/articles/tablelayout/Simple.html
Not perfect but I would chance your code like this
public class StackPanel extends JPanel {
JPanel west, east, south, southSub1;
JTextArea infoText, popText, pushText, peekText, resultText;
JLabel aTitle, bTitle, cTitle, Result;
JButton push, pop, peek, test;
public StackPanel() {
// Creating JPanels
double size[][] = {{0.3, 0.7}, {TableLayout.FILL, 70}};
setLayout(new TableLayout(size));
double sizeWest[][] = {{0.5, 0.5}, {20, 20, 20, 20, 20, 20}};
setLayout(new TableLayout(size));
west = new JPanel(new TableLayout(sizeWest));
east = new JPanel();
south = new JPanel();
// Creating JLabels / JTextArea
aTitle = new JLabel("Operations");
bTitle = new JLabel("Data Structure Contents");
cTitle = new JLabel("Information");
infoText = new JTextArea("This is where commands will be displayed.");
pushText = new JTextArea("pushtxt");
popText = new JTextArea("poptxt");
peekText = new JTextArea("g");
resultText = new JTextArea("");
west.add(aTitle, "0,0,1,0");
west.add(pushText, "0,1");
west.add(popText, "0,2");
west.add(peekText, "0,3");
west.add(resultText, "0,4");
east.add(bTitle);
south.add(cTitle);
south.add(infoText);
// Creating & Adding JButtons
push = new JButton("PUSH");
pop = new JButton("POP") ;
peek = new JButton("PEEK");
test = new JButton("TEST");
west.add(push, "1,1");
west.add(pop,"1,2");
west.add(peek,"1,3");
west.add(test, "1,4");
// Setting the placements of GUI objects
add(west, "0,0");
add(east, "1,0");
add(south, "0,1, 1,1");
// Declaring JPanel sizes // Width|Height
west.setPreferredSize(new Dimension(200,200));
east.setPreferredSize(new Dimension(400,100));
south.setPreferredSize(new Dimension(100,150));
// Setting black borders for JPanels
west.setBorder(BorderFactory.createLineBorder(Color.black));
east.setBorder(BorderFactory.createLineBorder(Color.black));
south.setBorder(BorderFactory.createLineBorder(Color.black));
// Setting JPanel background colours
west.setBackground(new Color(234,237,242));
east.setBackground(new Color(255,255,255));
south.setBackground(new Color(240,240,240));
}}
Hope this works for you!
The basic Swing layout managers are either very rudimentary or very complicated to use.
Therefore maybe FormLayout or MigLayout may be an option to use, which are sophisticated, but not too complicated to use.
So I am a computer science student and I've finished my first year. I wanted to create a simple program and I realized that I am so tired of using no layout;
this.setLayout(null);
It is so tiresome to add bounds to every single component. Well, I have been using JPanel components and GridLayout a lot, which have made my work a bit easier. But I am tired of it.
I care very much about the look of the GUI I make and use almost half the time programming to make the GUI look good before I start adding the functionality of the code. By not using a layout and adding bounds I am forced to setResizable(false) because it looks bad if I change the size of the JFrame.
I've been searching a bit, and I know of BorderLayout, and FlowLayout, but I don't like them. Is there any Layout that keeps the relative size of the components with respect to the size of the window?
For example I want to make a simple program that looks like this: (Quick sketch in Photoshop)
I can easily make this with 3 panels, but as I said, if I change the size of the frame everything stays in place instead of being relative to the window-size.
Can you guys help me?
This design looks for me to fit the BorderLayout, where in the NORTH you have the values that changes the CENTER you have the main part, and the SOUTH you have the buttons.
Link to the Oracle Border Layout
You can apply this BorderLayout to the JFrame, then create 3 JPanels for each of the NORTH,CENTER and SOUTH sections. If you want to use responsive design for the components and panels, take a look at GridBagLayout which is much more flexible than the GridLayout
Layout management is a very complex problem, I don't think people really appreciate just how complex it really is.
No one layout is ever going to achieve everything your want, in most cases, you will need to resort to two or more layouts, especially as your requirements become more complex.
For example, the following is simply a BorderLayout at the base and the buttons on a JPanel using a FlowLayout
Which is achieved by using
JList listOfThings = new JList(...);
JTextField tf = new JTextField();
JButton add = new JButton("Add");
JButton delete = new JButton("Delete");
JButton go = new JButton("Go...");
JPanel buttons = new JPanel();
buttons.add(add);
buttons.add(delete);
buttons.add(go);
add(new BorderLayout());
add(tf, BorderLayout.NORTH);
add(new JScrollPane(listOfThings));
add(buttons, BorderLayout.SOUTH);
For more complex layouts, I would consider using something like GridBagLayout. You may also want to consider MigLayout as an alternative
Take a look at Laying Out Components Within a Container for more details about using layout managers
I'd like to use the combination of BorderLayout and BoxLayout. BorderLayout let me put the component based on their relative location's relation and BoxLayout let me manage the subtle distance ( create some white space). You can use component.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); to achieve this goal too.
Here is a demo and hope it can help you.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class LayoutTest{
private JTextField jTextField;
public void createUI(){
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(new TextFieldPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ListPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ButtonPanel());
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
LayoutTest layoutTest = new LayoutTest();
layoutTest.createUI();
}
#SuppressWarnings("serial")
class TextFieldPanel extends JPanel{
public TextFieldPanel(){
setLayout(new BorderLayout());
jTextField = new JTextField();
jTextField.setEditable(false);
add(jTextField,BorderLayout.CENTER);
}
}
#SuppressWarnings("serial")
class ListPanel extends JPanel implements ListSelectionListener{
private JList<String> list;
public ListPanel(){
setLayout(new BorderLayout());
String stringArr[] = new String[30];
for (int i = 0; i < 30; i++) {
stringArr[i] = "JList :This line is item" + i;
}
list = new JList<String>(stringArr);
JScrollPane scrollPane = new JScrollPane(list);
add(scrollPane,BorderLayout.CENTER);
setBackground(new Color(211,211,211));
list.addListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
jTextField.setText(list.getSelectedValue());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BorderLayout());
add(button1,BorderLayout.WEST);
add(button2,BorderLayout.CENTER);
add(button3,BorderLayout.EAST);
}
}
}
Here is the effect:
You can use BoxLayout for ButtonPanel if you don't want to let the button's size change.
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(button1);
add(Box.createHorizontalStrut(8));
add(button2);
add(Box.createHorizontalStrut(8));
add(button3);
}
}
And the effect is like this:
For more infomation about using BoxLayout to generate whitespace, you can refer to https://stackoverflow.com/a/22525005/3378204
Try GridBagLayout.
Your sketch is actually quite close to the one of the examples in the official tutorial.
HVLayout keeps the relative size of the components with respect to the size of the window, that is, if you configure components to have a relative size (e.g. buttons usually do not grow or shrink - they stick to their preferred size). This SO question was one of the motivations for me to push HVLayout to a release and a screenshot is included (showing big window size, smalll size and preferred "default" size):
Source code for the window is in RelativeToWindowSize.java
A number of helper-classes from HVLayout are used to build the window, so I don't think it will be of much use here, but to get an impression, the "build window" part shown below:
public RelativeToWindowSize build() {
CSize cs = new CSize();
CForm form = new CForm(new VBox(new Insets(2, 4, 2, 4)), cs);
addTitledBorder(form.get(), "Vertical box", Color.BLACK);
form.add(new JScrollPane(
tfield = new JTextArea("Value that changes with value choosen from list.\nhttp://stackoverflow.com/questions/24462297/layout-relative-to-screensize/")
)).csize().setAreaSize(1.0f, 2.5f).fixedMinHeight().setMaxHeight(4.0f);
// tfield shows mono-spaced font by default.
tfield.setFont(SwingUtils.getUIFont());
form.add(new JScrollPane(vlist = new JList<String>(getListValues())))
.csize().setAreaSize(1.0f, 5.0f);
form.addChild(new HBox());
addTitledBorder(form.get(), "Horizontal box", Color.RED);
form.addChild(new HBox(SwingConstants.CENTER));
addTitledBorder(form.get(), "Centered box.", Color.BLUE);
form.add(createButton(cs, "Add"));
form.add(createButton(cs, "Modify"));
form.up();
form.addChild(new HBox(SwingConstants.TRAILING));
addTitledBorder(form.get(), "Trailing box", Color.GREEN);
form.add(createButton(cs, "Delete"));
setContentPane(form.getRoot());
pack();
setLocationByPlatform(true);
//applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
vlist.addListSelectionListener(this);
log.debug(getClass().getName() + " build.");
return this;
}
private Component createButton(CSize cs, String text) {
// For purpose of demo, let button shrink in width.
return cs.set(new TButton(text)).setFixed().shrinkWidth(0.33f).get();
}
I need to have a GUI like this:
Here all the rectangles must be buttons. How can I achieve this? Suggest me some tools like JFormDesigner.
I have had a lot of good experience with JGraph!
See the docs and some examples of what you can achieve here
Each node in the diagrams can be clicked and events can be listened for and acted upon, just like buttons. In fact I think you can put JButtons into the nodes in the diagram, but I may be wrong.
EDIT: Just the layout using regular Java Swing code would be something like this
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LayoutTest {
public static void main(String[] args) {
JFrame window = new JFrame();
Container container = window.getContentPane();
container.setLayout(new BorderLayout());
JPanel centerPanel = new JPanel();
centerPanel.add(new JButton("Center"));
container.add(centerPanel, BorderLayout.CENTER);
JPanel topPanel = new JPanel();
topPanel.add(new JButton("b1"));
container.add(topPanel, BorderLayout.NORTH);
JPanel rightPanel = new JPanel();
rightPanel.add(new JButton("b3"));
container.add(rightPanel, BorderLayout.EAST);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
JPanel bottomNorthPanel = new JPanel();
bottomNorthPanel.add(new JButton("b2"));
bottomPanel.add(bottomNorthPanel, BorderLayout.NORTH);
JPanel bottomSouthPanel = new JPanel();
bottomSouthPanel.add(new JButton("b2-1"));
bottomSouthPanel.add(new JButton("b2-2"));
bottomPanel.add(bottomSouthPanel, BorderLayout.SOUTH);
container.add(bottomPanel, BorderLayout.SOUTH);
window.setSize(320, 240);
window.setVisible(true);
}
}
I suppose you're asking for things on Java Swing. You can use drawLine(), and drawRect(), and you've to take control of painting over component. Once you understand this well, and create basic classes that suit your need, you can you do really well.
For info: refer to Schildt's examples on Swing: A Beginner's Guide. on page 495.
For listing- http://www.mhprofessional.com/getpage.php?c=computing_downloads.php&cat=112 (go to bottom)
Hope this helps..