Reputation: 21
I am trying to write a program with swing such that there is a JList on the left and five JButtons on the right. So I wrote code for one JButton, but I am unable to resize or move it. Any help would be appreciated. Thanks so much!! Here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GenericFrame {
private JFrame mainFrame;
private JPanel controlPanel;
public GenericFrame(){
prepareGUI();
}
private void prepareGUI(){
mainFrame = new JFrame("Generic Frame");
mainFrame.setSize(800,400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new FlowLayout());
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.setSize(800,400);
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
}
public void showButtons(){
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
showButton.setLayout(new BorderLayout());
showButton.setLocation(0, 200);
JButton viewButton = new JButton("view");
viewButton.setLocation(showButton.getX(), showButton.getY() + 100);
controlPanel.add(showButton);
controlPanel.add(viewButton);
}
public static void main(String[] args){
GenericFrame swingControlDemo = new GenericFrame();
swingControlDemo.showButtons();
}
}
For the record, I'm using IntelliJ. I tried this on multiple machines with different operating systems but this error persists. Please help me.
Upvotes: 0
Views: 588
Reputation: 324197
I am trying to write a program with swing such that there is a JList on the left and five JButtons on the right.
So when using layout managers you will often need to use nested panels. So in your case I would suggest you keep the default BorderLayout of the frame and add the JList to the frame and a panel containing the 5 buttons to the frame. The basic code would be:
JList list = new JList(...);
frame.add(new JScrollPane( list ), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(...);
buttonPanel.add( button1 );
frame.add(buttonPanel, BorderLayout, BorderLayout.LINE_END);
So know your next choice is the layout manager to use for the "button panel". Maybe a vertical BoxLayout? Read the section from the Swing tutorial on Layout Manager for more information and example of each layout manager.
Don't attempt to use setSize() or setLocation() on a component. It is the job of the layout manager to set those properties.
Upvotes: 1