I'm trying to add a JList to a GUI, but am wondering how to position it? I want it to appear on the right hand side of the TextArea for data that will be sent to the GUI for selection.
Can anyone suggest how to do this? Here is the code (note: very new to Java and GUI's)
protected static void createAndShowGUI() {
GUI predict = new GUI();
JFrame frame = new JFrame("Phone V1.0");
frame.setContentPane(predict.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setMinimumSize(new Dimension(300, 400));
frame.setVisible(true); // Otherwise invisible window
}
private JPanel createContentPane() {
JPanel pane = new JPanel();
TextArea = new JTextArea(5, 10);
TextArea.setEditable(false);
TextArea.setLineWrap(true);
TextArea.setWrapStyleWord(true);
TextArea.setWrapStyleWord(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
//Adds the buttons from Top to Bottom
String[] items = {"dsfsdfd"};
list = new JList(items);
JScrollPane scrollingList = new JScrollPane(list);
int orient = list.getLayoutOrientation();
JPanel window = new JPanel();
pane.add(window);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 3));
JButton[] buttons = new JButton[] {
new JButton("Yes"),
new JButton(""),
new JButton("Clr"),
new JButton("1"),
new JButton("2abc"),
new JButton("3def"),
new JButton("4ghi"),
new JButton("5jkl"),
new JButton("6mno"),
new JButton("7pqrs"),
new JButton("8tuv"),
new JButton("9wxyz"),
new JButton("*+"),
new JButton("0_"),
new JButton("^#")
}; // Array Initialiser
for (int i = 0; i < buttons.length; i++) {
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
pane.add(TextArea);
pane.add(list);
pane.add(buttonPanel);
return pane;
}
Read the section from the Swing tutorial on Using Layout Mananger. There is no need to only use a single layout manager. You can nest layout managers to get the desired effect.
Wrap your TextArea and list in a new panel with a BorderLayout manager. Basically the BorderLayout manager lets you arrange components using north, south, east, west and center coordinates. The components at the center takes all available space as the parent container has more space available to it.
private JPanel createContentPane() {
JPanel pane = new JPanel(); //this is your main panel
JPanel textAreaPanel = new JPanel(new BorderLayout()); //the wrapper
//Some more code...
//Then at the end
//Make your TextArea take the center
textAreaPanel.add(TextArea, BorderLayout.CENTER);
//And the list to the east
textAreaPanel.add(list, BorderLayout.EAST);
pane.add(textAreaPanel);
pane.add(buttonPanel);
return pane;
}
The cool thing is that you can nest panels inside other panels, adding them different layout managers to get your desired layout.
On an unrelated note, try to follow Java naming conventions. Instead of JTextArea TextArea use JTextArea textArea. It makes it easier for you and people reading your code to understand it.
You could use a layout manager like Mig Layout for that kind of positionning.
(source: miglayout.com)
I could recommend you FormLayout. Before I found this layout I had a real pain with GridBagLayout. FormLayout is more powerful and much more convenient to learn and use and it is free. Give it a chance.
As others suggested, familiarize yourself with the concept of layout managers. There are several that come with the standard Swing API and several good 3rd party ones out there.
In addition, you will want to add the JList to a scroll pane (JScrollPane). You may want to consider adding it to a split pane (JSplitPane). And by consider I don't mean "do it because some guy on the net said so" I mean "do it if it makes sense for your end users".
Related
When i increase the window size to full, my components goes back to standard layout(jtable,button1,button2,button3) and so on. so i wonder if my code is right and how i can decrease the window size.
JTabbedPane jtabbed = new JTabbedPane(JTabbedPane.TOP);
JPanel panel=new JPanel();
tabellinnhold = new DefaultTableModel(defaulttabell,kolonnenavn);
posttabell = new JTable(tabellinnhold);
rullefelt = new JScrollPane(posttabell);
koble = new JButton("koble til");
lukke = new JButton("lukke");
hente = new JButton("Hente data");
avslutt = new JButton("Avslutt");
panel.add(rullefelt,BorderLayout.CENTER);
panel.add(koble,BorderLayout.SOUTH);
panel.add(lukke,BorderLayout.SOUTH);
panel.add(hente,BorderLayout.SOUTH);
panel.add(avslutt,BorderLayout.SOUTH);
//action listener
koble.addActionListener(this);
lukke.addActionListener(this);
hente.addActionListener(this);
avslutt.addActionListener(this);
jtabbed.add("se post",panel);
add(jtabbed);
//////////////////////////////////////////////////
Grensesnitt p = new Grensesnitt();
p.setDefaultCloseOperation(EXIT_ON_CLOSE);
p.GUIcode();
p.setTitle("title");
p.setSize(500,700);
p.setVisible(true);
JPanel panel=new JPanel();
...
panel.add(rullefelt,BorderLayout.CENTER);
panel.add(koble,BorderLayout.SOUTH);
panel.add(lukke,BorderLayout.SOUTH);
panel.add(hente,BorderLayout.SOUTH);
panel.add(avslutt,BorderLayout.SOUTH);
The default layout manager for a JPanel is a FlowLayout which will simply display all the components on a single line.
You can't just use the BorderLayout constraints and expect it to work.
If you want to use a BorderLayout then the code should be:
//JPanel panel=new JPanel();
JPanel panel=new JPanel( new BorderLayout() );
Also, you can't add 4 components to the "SOUTH" of the BorderLayout. You can only add a single component. So you need to create a child panel and add your components to that first:
JPanel south = new JPanel();
south.add(koble);
south.add(lukke);
south.add(hente);
south.add(avslutt);
panel.add(south, Borderlayout.SOUTH);
Read the section from the Swing tutorial on Using Layout Manager for more information and working examples to get you started.
Keep a link to the tutorial handy for examples of all Swing basics.
===================
Game Name
Play
Exit
===================
the above is what my previous game menu looked like. I used the Box Layout to create it but it was very tedious. Is there there a better layout manager that I could use?
here is the code for those that asked of the main pane.
private JButton JB;
private JButton EB;
private JOptionPane JO;
public StartUpWindow(){
super("Pong");
JPanel outside = new JPanel();
JPanel inside = new JPanel();
setLayout(new BorderLayout());
outside.setLayout(new BoxLayout(outside, BoxLayout.LINE_AXIS));
inside.setLayout(new BoxLayout(inside, BoxLayout.PAGE_AXIS));
outside.add(Box.createHorizontalStrut(280));
outside.add(inside);
outside.add(Box.createHorizontalStrut(20));
inside.add(Box.createVerticalStrut(20));
JLabel title = new JLabel(" "+"Pong");
title.setFont( new Font("Serif", Font.BOLD, 40));
inside.add(title);
inside.add(Box.createVerticalStrut(20));
JButton btt1 = new JButton("Start");
Dimension d = new Dimension(200,40);
btt1.setSize(d);
btt1.setMinimumSize(d);
btt1.setMaximumSize(d);
btt1.setPreferredSize(d);
JButton btt2 = new JButton("Credits");
btt2.setSize(d);
btt2.setMinimumSize(d);
btt2.setMaximumSize(d);
btt2.setPreferredSize(d);
JButton btt3 = new JButton("Exit");
btt3.setSize(d);
btt3.setMinimumSize(d);
btt3.setMaximumSize(d);
btt3.setPreferredSize(d);
inside.add(btt1);
btt1.addActionListener(this);
btt1.setActionCommand("start");
inside.add(Box.createVerticalStrut(5));
inside.add(btt2);
btt2.addActionListener(this);
btt2.setActionCommand("credits");
inside.add(Box.createVerticalStrut(5));
inside.add(btt3);
btt3.addActionListener(this);
btt3.setActionCommand("exit");
inside.add(Box.createVerticalStrut(20));
add(outside);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
this.setResizable(false);
this.setLocation(450,200);
inside.setBackground(Color.GRAY);
outside.setBackground(Color.GRAY);
}
I agree that BoxLayout is tedious but I admire its relative simplicity.
Another quick and easy option is to use the "javax.swing.Box" class instead of using a layout manager directly.
Box box = Box.createVerticalBox();
box.add(new JLabel("Game"));
box.add(Box.createVerticalStrut(20));
box.add(new JLabel("Button 1"));
box.add(new JLabel("Button 2"));
JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setVisible(true);
Box offers a number of useful methods. You can use it to create vertical and horizontal boxes, create "struts" to reserve horizontal and vertical space, and create "glue" to fill in available space when the layout grows.
Of course you could also use GridBagLayout, but I tend to reserve it for more complex layouts. Box and his cousin BoxLayout are often good enough for simple layouts and are easy for new programmers who are maintaining the application to understand and debug.
Why not simply use no layout and instead draw everything using a Graphics object?
You could easily achieve this by creating a BufferStrategy bound to the Window object (invoke createBufferStrategy on the latter) then call a few simple methods to easily redraw the screen.
This also means it's simpler to then code the game's display when you're playing it.
BufferStrategy also allows the use of page flipping and other forms of buffering when the application is in fullscreen exclusive mode, allowing it to refresh the screen very rapidly in many applications.
I need to do an assignment and create a calculator. It's a beginner Java course, so keep in mind that I'm no expert. It shouldn't look spectacular, so the easiest way to achieve the below would be great.
The inner workings of it is fine, but drawing it has been a real headache.
We've only gotten exposure to flowlayout so far...and in this instance it's not what I want at all. Let me start of by telling you what layout I'm looking for:
At the top a heading spreading across the calculator, with perhaps a
background fill.
Then below that, 2 buttons next to each other.
Below that, two labels next to each other.
Then two text field next to each other.
Below that, two labels next to each other.
Then two text field next to each other.
I tried drawing it here, but it doesn't format correctly. If I can put it in HTML it would basically be a simple table, with 6 rows and 2 columns. But the top row must span across both columns.
Flowlayout just put everything next to each other from left to right.
After that I tried using GridLayout, but the top heading was the problem here, as it didn't span across both columns.
Here is my code so far:
public class TripCalculator extends JFrame implements ActionListener {
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public static final int NUMBER_OF_CHAR = 4;
public JTextField stopTime, distance, tripTime, speed;
public TripCalculator() {
setSize(WIDTH, HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JLabel heading = new JLabel("HEADING");
contentPane.add(heading);
contentPane.setLayout(new FlowLayout());
JButton addStop = new JButton("BUTTON1");
addStop.addActionListener(this);
JButton addLeg = new JButton("BUTTON2");
addLeg.addActionListener(this);
contentPane.add(addStop);
contentPane.add(addLeg);
JLabel subHead1 = new JLabel("LABEL1");
contentPane.add(subHead1);
JLabel subHead2 = new JLabel("LABEL2");
contentPane.add(subHead2);
stopTime = new JTextField(NUMBER_OF_CHAR);
contentPane.add(stopTime);
distance = new JTextField(NUMBER_OF_CHAR);
contentPane.add(distance);
JLabel subHead3 = new JLabel("LABEL3");
contentPane.add(subHead3);
JLabel subHead4 = new JLabel("LABEL4");
contentPane.add(subHead4);
tripTime = new JTextField(NUMBER_OF_CHAR);
contentPane.add(tripTime);
speed = new JTextField(NUMBER_OF_CHAR);
contentPane.add(speed);
}
}
I would greatly appreciate if anyone can show me in the right direction.
Flowlayout or Gridlayout by themselves won't help you. Either you can use Gridbaglayout, or a combination of layouts such as FlowLaout+Gridlayout.
If you are drawing a calculator, I am assuming you are drawing something like this :
Where you have title information at the top, a calculator keypad in the middle, and some other buttons at the bottom :
This could be achieved with a vertical box layout, with flowlayouts at the top and bottom, and in the middle a grid layout with all the number keys.
But... without you showing a diagram of what you want its very difficult to say.
Here's an example of using multiple Layout Managers as you can see you can use more than one, but you should use more than one JPanel to achieve what you want.
Also a recommendation is: Don't extend from JFrame, instead create a JFrame object as I did in this example and here's why you shouldn't do that.
import java.awt.*;
import javax.swing.*;
public class LayoutManagersExample {
public static void main(String args[]) {
new LayoutManagersExample();
}
public LayoutManagersExample() {
JFrame frame = new JFrame("Layout Managers Example");
JPanel topPane = new JPanel();
JPanel midPane = new JPanel();
JPanel panesHolder = new JPanel();
JLabel label = new JLabel("Top label");
JTextField field = new JTextField();
field.setColumns(5);
topPane.setLayout(new FlowLayout());
midPane.setLayout(new GridLayout(3, 2));
topPane.add(label);
topPane.add(field);
midPane.add(new JButton("Button 1"));
midPane.add(new JButton("Button 2"));
midPane.add(new JButton("Hello I'm a button"));
midPane.add(new JButton("HEY! Click me :)"));
midPane.add(new JButton("I love you"));
midPane.add(new JButton("This is another button"));
panesHolder.setLayout(new BoxLayout(panesHolder, BoxLayout.Y_AXIS));
panesHolder.add(topPane);
panesHolder.add(midPane);
frame.add(panesHolder);
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
}
And this is how it looks like:
I'm developing a Java application for homework. This is my code
JLabel queryHandlerL = new JLabel("Create php to handle query results", JLabel.CENTER);
final JCheckBox queryHandlerCB = new JCheckBox();
JPanel checkBoxPanel = new JPanel(new FlowLayout());
checkBoxPanel.add(queryHandlerL);
checkBoxPanel.add(queryHandlerCB);
// Query Panel
// set image
picLabelQuery = new JLabel("",JLabel.LEFT);
picLabelQuery.setIcon(currentPicForm);
JPanel queryPanel = new JPanel();
final JButton queryButton = new JButton("Insert a query");
queryPanel.add(queryButton);
queryPanel.add(picLabelQuery);
// Panel create
final JButton createButton = new JButton("Create");
JPanel createPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
createPanel.add(createButton);
JPanel finalPanel = new JPanel(new GridLayout(0, 1,5,2));
finalPanel.add(queryPanel);
finalPanel.add(checkBoxPanel);
finalPanel.add(createPanel);
finalPanel.setBorder(BorderFactory.createTitledBorder("SQL connection"));
setLayout(new GridBagLayout());
add(finalPanel);
I have a CardLayout and this is a Window inside this CardLayout. The last add(finalPanel) refers to the panel of the CardLayout.
This piece of code works but this is the result
How do I remove the space that is automatically created between the panels?
How do I remove the space that is automatically created between the panels?
Use a different layout manager for the panel. The GridLayout will always resize components to take up all the space in the panel.
Maybe you can use a BoxLayout or a GridBagLayout. You can also nest panels with different layout managers to get your desired effect.
Read the section from the Swing tutorial on Layout Managers for more information and examples.
You should pack() your surrounding panel or set the height to a desired value.
So my buttons are overwriting each other, instead of all going up North like a tool bar..
I'm trying to get the buttons to go up North if that makes sense. I know my GUI is awful, and I'll rewire it once I get this prototype done.
// panels
mainPuzzlerPanel = new Panel();
mainPuzzlerPanel.setLayout(new BorderLayout());
puzzlePanel = new Panel();
//mainPuzzlerPanel.setLayout(null);
puzzlePanel.setLocation(100, 120);
// text fields
debugTxt = new TextArea(null,6,40,1);
debugTxt.setEditable(false);
mainPuzzlerPanel.add(debugTxt,BorderLayout.NORTH);
// buttons
Button newPuzzle = new Button("New Puzzle");
Button loadImage = new Button("Load Image");
Button assignLocation = new Button("Assign Location");
Button assignTimestamp = new Button("Assign Timestamp");
Button savePuzzle = new Button("Save Puzzle");
Button clearPuzzleCreator = new Button("Clear");
newPuzzle.addActionListener(this);
loadImage.addActionListener(this);
assignLocation.addActionListener(this);
assignTimestamp.addActionListener(this);
savePuzzle.addActionListener(this);
clearPuzzleCreator.addActionListener(this);
mainPuzzlerPanel.add(assignLocation,BorderLayout.NORTH);
mainPuzzlerPanel.add(assignTimestamp,BorderLayout.NORTH);
mainPuzzlerPanel.add(loadImage,BorderLayout.NORTH);
mainPuzzlerPanel.add(savePuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(clearPuzzleCreator,BorderLayout.NORTH);
mainPuzzlerPanel.add(newPuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(puzzlePanel,BorderLayout.CENTER);
add(mainPuzzlerPanel, "Controls");
setSize(1200, 700);
setVisible(true);
You can't add all the components BorderLayout.NORTH, makes no sense. Instead, add the JButtons to a JPanel that uses a different layout, say GridLayout, and then add that JPanel BorderLayout.NORTH. But most important -- read a tutorial on how to use the layout managers. It looks like you're guessing at this and that's not an efficient way to learn how to use these complex tools.
Regading,
I know my GUI is awful, and I'll rewire it once I get this prototype done.
Also not a good plan. It's much easier to write it well the first time through.
e.g.,
// after creating all of your JButtons, put them in an array...
JButton[] btnArray = {newPuzzle, loadImage, assignLocation, assignTimestamp,
savePuzzle, clearPuzzleCreator};
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (JButton btn : btnArray) {
buttonPanel.add(btn);
}
mainPuzzlerPanel.add(buttonPanel, BorderLayout.NORTH);
Edit: Oops, I notice now you're using Buttons and Panels, not JButtons and JPanels. I urge you to change your app to be a Swing app not an AWT app.
Layout manager tutorial: Laying Out Components Within a Container