I have a problem with setting position for one of the elements (the image). I cannot align it to right-bottom of the screen. I tried to use different layouts but I can't make it to work exactly like I want it.
Below is the url to view how it looks now. The image is in the right-bottom but it's a new BorderLayout and it creates extra space on the bottom so I would prefer it to fit with the rest. Red square shows where image should be placed.
Below is the code of my program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server extends JFrame implements ActionListener{
public static final int PORT = 8060;
private JButton reset, exit;
private JEditorPane messages;
private ImageIcon logo = new ImageIcon("C:src\\images\\logo.png");
private JLabel logoSpot;
Container box = getContentPane();
public static void main(String args[]){
new Server().Networking();
}
public void makeMenu(){
JPanel menu = new JPanel();
reset = new JButton("Reset messages");
exit = new JButton("Exit");
menu.add(reset);
menu.add(exit);
reset.addActionListener(this);
exit.addActionListener(this);
box.add(menu, BorderLayout.EAST);
}
public void setLogo(){
JPanel logoSpace = new JPanel(new BorderLayout());
logoSpot= new JLabel();
logoSpot.setIcon(logo);
logoSpace.add(logoSpot, BorderLayout.EAST);
box.add(logoSpace, BorderLayout.SOUTH);
}
public void makeScreen(){
JPanel screen = new JPanel();
messages = new JEditorPane();
messages.setPreferredSize(new Dimension(800,590));
screen.add(messages);
box.add(screen, BorderLayout.WEST);
}
public Server(){
makeMenu();
makeScreen();
setLogo();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(1024, 680);
setTitle("Emergency system");
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == exit){
super.dispose();
}
if(e.getSource() == reset){
messages.setText(" ");
}
}
public void Networking(){
String received=" ";
try{
ServerSocket ss = new ServerSocket(PORT);
while(true){
Socket sock = ss.accept();
BufferedReader in =
new BufferedReader(new InputStreamReader(
sock.getInputStream()));
received = in.readLine();
messages.setText(messages.getText() + received +
" \n\n");
OutputStreamWriter out =
new OutputStreamWriter(sock.getOutputStream());
BufferedWriter bw = new BufferedWriter(out);
bw.write(received);
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This should do the trick. It just needed some more panels to constrain the 2nd image (160x160px) to the PAGE_END and LINE_END of some BorderLayout instances.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server extends JFrame implements ActionListener{
public static final int PORT = 8060;
private JButton reset, exit;
private JEditorPane messages;
private ImageIcon logo = new ImageIcon(
new BufferedImage(140,140,BufferedImage.TYPE_INT_RGB));
private JLabel logoSpot;
Container box = getContentPane();
public static void main(String args[]){
new Server();
}
public void makeMenu(){
JPanel menu = new JPanel(new BorderLayout(5,5));
menu.setBackground(Color.RED);
reset = new JButton("Reset messages");
exit = new JButton("Exit");
JPanel buttons = new JPanel();
buttons.setBackground(Color.GREEN);
menu.add(buttons, BorderLayout.PAGE_START);
buttons.add(reset);
buttons.add(exit);
reset.addActionListener(this);
exit.addActionListener(this);
JLabel l = new JLabel(new ImageIcon(new BufferedImage(
160,160,BufferedImage.TYPE_INT_RGB)));
JPanel forceRight = new JPanel(new BorderLayout());
forceRight.add(l, BorderLayout.LINE_END);
forceRight.setBackground(Color.BLUE);
menu.add(forceRight, BorderLayout.PAGE_END);
box.add(menu, BorderLayout.EAST);
}
public void setLogo(){
JPanel logoSpace = new JPanel(new BorderLayout());
logoSpot= new JLabel();
logoSpot.setIcon(logo);
logoSpace.add(logoSpot, BorderLayout.EAST);
box.add(logoSpace, BorderLayout.SOUTH);
}
public void makeScreen(){
JPanel screen = new JPanel();
screen.setBackground(Color.YELLOW);
messages = new JEditorPane();
messages.setPreferredSize(new Dimension(800,590));
screen.add(messages);
box.add(screen, BorderLayout.WEST);
}
public Server(){
makeMenu();
makeScreen();
setLogo();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(1024, 680);
setTitle("Emergency system");
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == exit){
super.dispose();
}
if(e.getSource() == reset){
messages.setText(" ");
}
}
}
You should organize the structure of your code better. The constructor is typically found at the start of the class.
Instead of having 3 methods to create the GUI components you could probably have one. You don't need to use the getContentPane() method. When you use the add(...) method of a JFrame the components are added to the content pane. I would also use a JTextArea to display message. a JEdtitorPane should only be used for HTML. You also should add the text area to a JScrollPane so scrollbars will appear as more messages are added.
So the basic code would be something like:
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane( textArea );
add(scrollPane, BorderLayout.CENTER);
JPanel east = new JPanel( new BorderLayout() );
east.add(menuPanel, BorderLayout.NORTH);
east.add(logo, BorderLayout.SOUTH);
add(east, BorderLayout.EAST);
Related
I am creating a java chat application and am having issues with a TextArea and a list in the client GUI. I am using a cardlayout to have the login on one panel and the chat on another.
For some reason though, the TextArea and List are not filling up the center and east of the panel respectively leaving a lot of extra space below them all the way to the button panel I have.
I've tried to mess with the borderlayout for both the TextArea and the list but no success.
Id appreciate any help.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;
public class ChatFrame extends Frame{
public ChatFrame(){
//setTitle("Chat Frame");
setSize(700,700);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
add(new ChatPanel(), BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args){
ChatFrame ch = new ChatFrame();
}
}
class ChatPanel extends Panel implements ActionListener, Runnable{
Button connect;
Button disconnect;
int currentCard = 1;
CardLayout cl;
Panel cardPanel;
TextField tf2;
String name;
List l1 = new List();
TextField tf;
TextArea ta;
Socket s;
BufferedReader in;
PrintWriter out;
Thread t;
public ChatPanel(){
setLayout(new BorderLayout());
cardPanel = new Panel();
cl = new CardLayout();
cardPanel.setLayout(cl);
tf = new TextField(" ");
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
ta = new TextArea();
add(ta, BorderLayout.CENTER);
connect = new Button("Connect");
connect.addActionListener(this);
disconnect = new Button ("Disconnect");
disconnect.addActionListener(this);
disconnect.setEnabled(false);
Panel buttonPanel = new Panel();
buttonPanel.add(connect);
buttonPanel.add(disconnect);
add(buttonPanel, BorderLayout.SOUTH);
l1.addActionListener(this);
//l1.setSize(new Dimension(150, 400));
add(l1,BorderLayout.EAST);
Panel p1 = new Panel();
Panel p2 = new Panel();
tf2 = new TextField(" ");
tf2.addActionListener(this);
add(tf2, BorderLayout.NORTH);
p1.add(tf2);
p2.add(tf);
p2.add(ta);
p2.add(l1);
cardPanel.add(p1, BorderLayout.CENTER);
cardPanel.add(p2, BorderLayout.CENTER);
add(cardPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae){
if((ae.getSource()==connect)){
try{
s = new Socket("localhost", 3000);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream(), true);
t = new Thread(this,"Whatever");
t.start();
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
connect.setEnabled(false);
disconnect.setEnabled(true);
cl.last(cardPanel);
name = tf2.getText();
out.println(name + " has entered the chat");
ChatFrame ch = (ChatFrame) SwingUtilities.getWindowAncestor(this);
ch.setTitle(name);
//l1.add(name);
}
else if(ae.getSource()== disconnect){
out.println(name + " has left the chat");
try{
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
disconnect.setEnabled(false);
connect.setEnabled(true);
cl.first(cardPanel);
}
else if (ae.getSource()== tf){
String temp = tf.getText();
tf.setText("");
out.println(name + ": " + temp);
}
}
public void run(){
try{
for(;;){
ta.append(in.readLine() + "\n");
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
This section of code is incorrect.
add(l1,BorderLayout.EAST);
Panel p1 = new Panel();
Panel p2 = new Panel();
tf2 = new TextField(" ");
tf2.addActionListener(this);
add(tf2, BorderLayout.NORTH);
p1.add(tf2);
p2.add(tf);
p2.add(ta);
p2.add(l1);
A component (l1) can only have a single parent container. Try adding a background color to each panel to more easily check that components are added to a container with the expected layout.
I have a JTextArea named as txtChat which is used as the chatting area in my chatbot. I have created a JScrollPane scroll = new JScrollPane(txtChat) and added my txtChat inside the JScrollPane. My JTextArea is being put inside a Panel which has BorderLayout, so I have added my scroll to the panel which contains my JTextArea chatPanel.add(scroll, BorderLayout.East). BUT IT IS NOT WORKING! Like when my conversation go longer, the scroll does not appear!
Sorry the code is quite long, so I just pasted the essential parts here.
public class GUI_V3 extends JFrame {
//mainPanel into Frame
private JPanel mainPanel = new JPanel();
//clock component
private JTextField timeF = new JTextField(8);
//Button component
private Box btnBox = Box.createHorizontalBox();
private JButton button1 = new JButton("Add Keywords");
private JButton button2 = new JButton("Help");
//Top menu bar
private JPanel topPanel = new JPanel();
//Typing Area
private JTextField txtEnter = new JTextField();
//Typing Panel
private JPanel typingPanel = new JPanel();
//Chat Area
private JTextArea txtChat = new JTextArea();
private JPanel chatPanel = new JPanel();
//Scroll
private JScrollPane scroll = new JScrollPane(txtChat);
private String name;
private Conversation_V3 convo = new Conversation_V3();
public GUI_V3(){
//Frame attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,1000);
this.setVisible(true);
//this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("Welcome to Haidilao");
//clock attributes
timeF.setEditable(false);
timeF.setFont(new Font("Arial",Font.BOLD,48));
timeF.setBackground(new Color(228,224,199));
timeF.setHorizontalAlignment(SwingConstants.RIGHT);
//button attributes
button1.setFont(new Font("Arial",Font.PLAIN,38));
button2.setFont(new Font("Arial",Font.PLAIN,38));
btnBox.add(button1);
btnBox.add(Box.createRigidArea(new Dimension(10,70)));
btnBox.add(button2);
//Add ActionListener to buttons
Button1Handler handlerB1 = new Button1Handler();
button1.addActionListener(handlerB1);
Button2Handler handlerB2 = new Button2Handler();
button2.addActionListener(handlerB2);
//Top menu bar
topPanel.setLayout(new BorderLayout());
topPanel.add(btnBox, BorderLayout.WEST);
topPanel.add(timeF, BorderLayout.EAST);
topPanel.setBackground(new Color(228,224,199));
//Typing Area Attribute
txtEnter.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
typingPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
typingPanel.setLayout(new BorderLayout());
typingPanel.setBackground(new Color(228,224,199));
typingPanel.add(txtEnter);
//Add action listener for typing area
TypingHandler handlerT = new TypingHandler();
txtEnter.addActionListener(handlerT);
//Chat Area Attribute
txtChat.setEditable(false);
txtChat.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
chatPanel.setBorder(BorderFactory.createEmptyBorder(5,20,10,20));
chatPanel.setLayout(new BorderLayout());
chatPanel.setBackground(new Color(228,224,199));
chatPanel.add(txtChat, BorderLayout.CENTER);
chatPanel.add(scroll, BorderLayout.EAST);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//mainPanel Layout
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(typingPanel, BorderLayout.SOUTH);
mainPanel.add(chatPanel, BorderLayout.CENTER);
//Add components to the JFrame
this.add(mainPanel);
//Add actionListener to clock
ClockHandler handlerC = new ClockHandler();
Timer t = new Timer(500, handlerC);
t.start();
//display greetings and ask for name
name = greetings();
addText(botSays("Welcome! " + name + ", you can ask me anything about the menu by providing keywords."));
}
//Action handler for txtEnter
private class TypingHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//grab input
String input = txtEnter.getText();
//add to chat area
txtChat.append(name + ": " + input + "\n");
//set input field to empty
txtEnter.setText("");
SoundEffect.music();
convo.setInput(input);
addText(botSays(convo.getReply()));
//set the chat area to bottom of scroll
txtChat.setCaretPosition(txtChat.getDocument().getLength());
}
}
Please find a working solution and tweak this as per your requirements.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
Hope this will be helpful. :-)
So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:
I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.
I'm kind of new to java and I experienced this little problem on every computer I run my program.
My code is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FrameTest2 {
public static void main(String[] args){
String s = "Catch Torchic";
MainMenu m = new MainMenu(s);
}
}
class MainMenu extends JFrame {
JButton autoa, manualb, createc, exitd;
public MainMenu(String s){
super(s);
setBackground(new Color(247,247,111));
setSize(640,600);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
CustomPanel panel = new CustomPanel();
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setMinimumSize(new Dimension(600,365));
panel.setPreferredSize(new Dimension(600,365));
panel.setMaximumSize(new Dimension(600,365));
panel.setBackground(new Color(247,247,111));
contentPane.add(panel);
JPanel btnPanel = new JPanel();
btnPanel.setLayout( new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
btnPanel.setBackground(new Color(247,247,111));
autoa = new JButton("AutoPlay");
autoa.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(autoa);
manualb = new JButton("Manual Play");
manualb.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(manualb);
createc = new JButton("Create Maze");
createc.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(createc);
exitd = new JButton("Exit");
exitd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(exitd);
btnPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(btnPanel);
setContentPane(contentPane);
ButtonHandler handler = new ButtonHandler(this);
autoa.addActionListener(handler);
manualb.addActionListener(handler);
createc.addActionListener(handler);
exitd.addActionListener(handler);
}
}
class ButtonHandler implements ActionListener{
MainMenu mm;
public ButtonHandler(MainMenu mm){
this.mm = mm;
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == mm.autoa)
System.out.println("Clicked on Auto");
else if(e.getSource() == mm.manualb)
System.out.println("Clicked on Manual");
else if(e.getSource() == mm.createc)
System.out.println("Clicked on Create");
else
System.exit(0);
}
}
class CustomPanel extends JPanel{
public void paintComponent (Graphics painter){
Image pic = Toolkit.getDefaultToolkit().getImage("logo.png");
if(pic != null) painter.drawImage(pic, 105, 30, this);
}
}
This code results into this: http://a3.sphotos.ak.fbcdn.net/hphotos-ak-ash4/318155_424290814251286_100000111130260_1871937_131988334_n.jpg
where there is always the extra button on the upper left corner, My question is, how do I remove this? the button appears at random intervals, sometimes it does not.
Try this variant. Many comments, the most important in SHOUTING. Note that by the time I had got it to being working code (or rather, code that worked here for loading the image), I never once saw the problem you describe.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.imageio.ImageIO;
public class FrameTest2 {
public static void main(String[] args) throws Exception {
final String s = "Catch Torchic";
URL url = new URL("http://pscode.org/media/stromlo2.jpg");
final Image image = ImageIO.read(url);
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new MainMenu(s, image);
}
});
}
}
class MainMenu extends JFrame {
JButton autoa, manualb, createc, exitd;
public MainMenu(String s, Image image) {
super(s);
// do this after pack (if at all)
//setSize(640,600);
// do this after pack/setSize
//setVisible(true);
// don't do this in broken code
//setResizable(false);
// If you're going to spend space on GUI position..
// setLocationRelativeTo(null);
// ..do it like this.
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
CustomPanel panel = new CustomPanel(image);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel.setMinimumSize(new Dimension(600,365));
//panel.setPreferredSize(new Dimension(600,365));
//panel.setMaximumSize(new Dimension(600,365));
contentPane.add(panel);
JPanel btnPanel = new JPanel();
btnPanel.setBorder(new EmptyBorder(5,5,100,5));
btnPanel.setLayout( new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
// not needed for an SSCCE
//btnPanel.setBackground(new Color(247,247,111));
autoa = new JButton("AutoPlay");
autoa.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(autoa);
manualb = new JButton("Manual Play");
manualb.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(manualb);
createc = new JButton("Create Maze");
createc.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(createc);
exitd = new JButton("Exit");
exitd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(exitd);
// you already said that
//btnPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(btnPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
ButtonHandler handler = new ButtonHandler(this);
autoa.addActionListener(handler);
manualb.addActionListener(handler);
createc.addActionListener(handler);
exitd.addActionListener(handler);
// CAUSE THE COMPONENTS TO BE PROPERLY LAID OUT.
pack();
setSize(640,600);
setVisible(true);
}
}
class ButtonHandler implements ActionListener{
MainMenu mm;
public ButtonHandler(MainMenu mm){
this.mm = mm;
}
public void actionPerformed(ActionEvent e){
// for clarity, even single line statements
// in these should be enclosed in {}
if(e.getSource() == mm.autoa)
System.out.println("Clicked on Auto");
else if(e.getSource() == mm.manualb)
System.out.println("Clicked on Manual");
else if(e.getSource() == mm.createc)
System.out.println("Clicked on Create");
else
System.exit(0);
}
}
class CustomPanel extends JPanel{
Image pic;
CustomPanel(Image pic) {
this.pic = pic;
}
public void paintComponent (Graphics painter){
// DO NOT TRY TO READ IMAGES IN PAINT!
//Image pic = Toolkit.getDefaultToolkit().getImage("logo.png");
if(pic != null) painter.drawImage(pic, 105, 30, this);
}
}
I think it is the missing contentPane.:
//setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));//
Also there is a superfluous setting of the content pane.
//setContentPane(contentPane);
After "nope:"
Difficult.
Move setVisible(true) to the end, to invoke only one layouting.
Try it without two panels (only one) inside the content pane:
Container contentPane0 = getContentPane();
Container contentPane = new JPanel();
contentPane0.add(contentPane);