I have added some code for scrollbar which I got from questions asked by some other people on stackoverflow but I am not getting any scrollbar added to my JTextArea. I want to add scrollbar to JTextArea area2 in f2 frame.
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener {
JFrame f1 = new JFrame("INPUT WINDOW");
JFrame f2 = new JFrame("FILE DATA OUTPUT");
JTextArea area1;
JTextArea area2;
JButton b;
TextAreaExample() {
area1 = new JTextArea();
area2 = new JTextArea();
JScrollPane scroll = new JScrollPane (area2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
b = new JButton("click Me");
b.setBounds(100, 95, 80, 30);
f1.add(b);
area1.setBounds(10, 30, 200, 60);
area2.setBounds(5, 5, 480, 480);
f1.add(area1);
f2.add(area2);
f2.add(scroll);
f1.setSize(300,140);
f2.setSize(510, 510);
f1.setLayout(null);
f2.setLayout(null);
f1.setVisible(true);
f2.setVisible(true);
b.addActionListener(this);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b) {
String s1 = area1.getText();
String s2 = "";
try {
FileInputStream fin = new FileInputStream(s1);
BufferedInputStream bin = new BufferedInputStream(fin);
int i;
while((i = bin.read()) != -1) {
s2 = s2 + (char)i;
}
bin.close();
fin.close();
}catch(Exception a) {
System.out.println(a);
}
area2.setText(s2);
}
}
public static void main(String args[]) {
new TextAreaExample();
}
}
JScrollPane scroll = new JScrollPane (area2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
b = new JButton("click Me");
b.setBounds(100, 95, 80, 30);
f1.add(b);
area1.setBounds(10, 30, 200, 60);
area2.setBounds(5, 5, 480, 480);
f1.add(area1);
f2.add(area2);
First you create a JScrollPane using the JTextArea as a parameter, which is correct.
But then you add the text area to the frame, which is incorrect. Swing components can only have a single parent so the text area is removed from the scroll pane.
The scroll pane must be added to the frame.
f1.add(scroll);
Also, get rid of all the null layouts and setBounds() statements. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Layout Manager for more information and examples to get your started.
Now when you create the text area you can use:
JTextArea textArea = new JTextArea(5, 20);
to suggest the original size for the text area. Scrollbars will then appear when more than 5 lines of data is added.
Related
i have problem with my JTextArea i java. When i print output in the text area, it doesn't automatically scroll to the bottom. And when it reaches the bottom of text area i cannot scroll it with scroll panel. Here is my GUI Code:
public void initializeWindow()
{
JPanel pan;
JPanel colorBox;
JPanel consolePanel;
JLabel panText;
JFrame frame = new JFrame();
JScrollPane scroll;
gridPanels = new JPanel[sizeX][sizeY];
boardPanel = new JPanel();
legend = new JPanel();
consolePanel = new JPanel();
consoleOutput = new JTextArea(25,20);
consoleOutput.setEditable(false);
consoleOutput.setPreferredSize(new Dimension( 200,300));
consoleOutput.setAutoscrolls(true);
scroll = new JScrollPane(this.consoleOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
consolePanel.setBorder(BorderFactory.createLineBorder(Color.black));
consolePanel.add(consoleOutput);
consolePanel.add(scroll);
boardPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
boardPanel.setLayout(new GridLayout(sizeX,sizeY));
legend.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
legend.setPreferredSize( new Dimension(300,boardPanel.getHeight()));
PrintStream printStream = new PrintStream(new CustomOutputStream(consoleOutput));
for (Organizm org: legendOrgs)
{
pan = new JPanel();
colorBox = new JPanel();
panText = new JLabel();
pan.setMaximumSize(new Dimension(100,70));
pan.setAlignmentX(Component.LEFT_ALIGNMENT);
pan.setLayout(new FlowLayout(FlowLayout.LEADING));
colorBox.setBackground(org.getOrgColor());
colorBox.setAlignmentX(Component.LEFT_ALIGNMENT);
colorBox.setPreferredSize(new Dimension(30,30));
colorBox.setMaximumSize(new Dimension(30,30));
panText.setPreferredSize(new Dimension(100,15));
panText.setText(" - " + org.getName());
panText.setAlignmentX(Component.RIGHT_ALIGNMENT);
pan.add(colorBox);
pan.add(panText);
legend.add(pan);
}
legend.add(consolePanel);
for(int i=0; i<sizeY; i++)
{
for(int j=0; j<sizeX; j++)
{
gridPanels[i][j] = new JPanel();
if(organizmy[i][j]!=null)
gridPanels[i][j].setBackground(organizmy[i][j].getOrgColor());
else gridPanels[i][j].setBackground(Color.white);
boardPanel.add(gridPanels[i][j]);
}
}
System.setOut(printStream);
System.setErr(printStream);
frame.add(boardPanel);
frame.add(legend,BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Wirtualny świat");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
worldFrame = frame;
}
And here is my Custom output Stream class which is used to print everything i print via System.out.println to my text Area:
public class CustomOutputStream extends OutputStream
{
private final JTextArea textArea;
public CustomOutputStream(JTextArea textArea)
{
this.textArea = textArea;
}
#Override
public void write(int b)
{
textArea.append(String.valueOf((char)b));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
Here is link to image what it looks like in GUI:
You need to remove this line from your code:
consoleOutput.setPreferredSize(new Dimension( 200,300));
Unfortunately, it prevents your JTextArea from being scrollable because you set static size to that element.
P.S. Stay away from Swing - there are better options in Java
It works for me.
import javax.swing.*;
public class Scrollin{
public static void main(String[] args){
JFrame frame = new JFrame("scrolling");
JTextArea area = new JTextArea(20, 20);
frame.add(new JScrollPane(area));
frame.setVisible(true);
frame.pack();
Timer t = new Timer( 150, evt->{
area.setCaretPosition( area.getDocument().getLength() );
area.append("word is born\n");
});
t.start();
}
}
As text is added, the window will scroll to the end provided the cursor is at the end of the document.
Maybe you can start with something as short as this to demonstrate your issue?
Hello Everyone I am new to Java so I am sure I am doing something obviously wrong here but I just keep going in circles.
I am trying to add a scroll to a JTextarea. Here is what I have tried but it doesn't show up.
textarea1 = new JTextArea();
textarea1.setBounds(251,26,795,345);
textarea1.setBackground(new Color(255,255,255));
textarea1.setForeground(new Color(0,0,0));
textarea1.setEnabled(true);
textarea1.setFont(new Font("sansserif",0,12));
textarea1.setText("");
textarea1.setBorder(BorderFactory.createBevelBorder(1));
textarea1.setVisible(true);
JScrollPane ScrollPane1 = new JScrollPane(textarea1);
ScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//adding components to contentPane panel
contentPane.add(browseFileOne);
contentPane.add(browseOutput);
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button4);
contentPane.add(fileOneText);
contentPane.add(fileTwoText);
contentPane.add(label1);
contentPane.add(label2);
contentPane.add(label3);
contentPane.add(outputTextFile);
contentPane.add(textarea1);
see working example:
https://repl.it/repls/DimpledDefensiveSourcecode
Code:
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
this.setSize(400, 400);
this.setLocation(0, 0);
this.setResizable(false);
this.setTitle("Application");
JPanel painel = new JPanel(null);
// Creating the Input
JTextField tf1 = new JTextField("Some random text", 15);
tf1.setBounds(5, 5, this.getWidth() - 120, 20);
tf1.setColumns(10);
tf1.setText("Omg");
// resultsTA,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
painel.add(tf1);
// Creating the button
JButton button1 = new JButton("Send");
button1.setBounds(290, 5, 100, 19);
painel.add(button1);
// Creating the TextArea
JTextArea ta1 = new JTextArea(15, 20);
JScrollPane scr = new JScrollPane(ta1,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);// Add your text area to scroll pane
ta1.setBounds(5, 35, 385, 330);
ta1.setLineWrap(true);
ta1.setWrapStyleWord(true);
scr.setBounds(20, 30, 100, 40);// You have to set bounds for all the controls and containers incas eof null layout
painel.add(scr);// Add you scroll pane to container
this.add(painel);
this.setVisible(true);
}
}
For some reason my scrollbar is appearing but it is not working. What is suppose to happen is using the scrollbar to scroll through the text of the textarea. Can somebody please explain why this isnt working?
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class App extends JFrame{
private JPanel paneel;
public App(){
paneel = new AppPaneel();
setContentPane(paneel);
}
public static void main(String args[]){
JFrame frame = new App();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setTitle("Auto Clicker");
frame.setVisible(true);
}
}
class AppPaneel extends JPanel{
private JTextField delayField, xLocation, yLocation;
private JTextArea listArea;
private JButton addButton, saveButton, runButton;
private JScrollPane scroll;
public AppPaneel(){
setLayout(null);
delayField = new JTextField();
delayField.setBounds(10, 10, 85, 25);
delayField.setText("delay in ms");
xLocation = new JTextField();
xLocation.setBounds(105, 10, 85, 25);
xLocation.setText("X position");
yLocation = new JTextField();
yLocation.setBounds(200, 10, 85, 25);
yLocation.setText("Y position");
addButton = new JButton("Add");
addButton.setBounds(295, 10, 75, 24);
addButton.addActionListener(new AddHandler());
listArea = new JTextArea();
listArea.setBounds(10, 45, 360, 180);
scroll = new JScrollPane(listArea);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(370, 45, 20, 180);
saveButton = new JButton("Save");
saveButton.setBounds(10, 230, 85, 24);
runButton = new JButton("Run (F1)");
runButton.setBounds(105, 230, 85, 24);
runButton.addActionListener(new RunHandler());
add(delayField);
add(xLocation);
add(yLocation);
add(addButton);
add(listArea);
add(saveButton);
add(runButton);
add(scroll);
}
class AddHandler implements ActionListener{
public void actionPerformed(ActionEvent a){
listArea.setText(listArea.getText() + delayField.getText() + ", " + xLocation.getText() + ", " + yLocation.getText() + ", " + "click;" + "\n");
}
}
class RunHandler implements ActionListener{
private Robot bot;
private String text;
int foo = Integer.parseInt("1234");
public void actionPerformed(ActionEvent b) {
try{
text = listArea.getText();
bot = new Robot();
for(String line : text.split("\\n")){
int delay = Integer.parseInt((line.substring(0, 4)));
int xpos = Integer.parseInt((line.substring(6, 10)));
int ypos = Integer.parseInt((line.substring(12, 16)));
bot.mouseMove(xpos, ypos);
Thread.sleep(delay);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
catch (AWTException | InterruptedException e){
e.printStackTrace();
}
}
}
}
Don't use null layouts and setBounds as it is messing up your program. We tell folks time and time again not to do this for a reason -- by setting the JTextArea's bound you constrain its size so it won't grow when it needs to. The solution, as always -- learn and use the layout managers. Set the JTextArea's column and row properties but not its bounds, its size, or its preferred size.
Next don't do this: Thread.sleep(delay); in your Swing application as it will put the entire application to sleep. Use a Swing Timer instead for any delays. The tutorials can help you use this.
For a non-functional layout example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class App2 extends JPanel {
private static final int GAP = 5;
private JTextField textField1 = new JTextField(GAP);
private JTextField textField2 = new JTextField(GAP);
private JTextField textField3 = new JTextField(GAP);
private JTextArea textArea = new JTextArea(15, 30);
public App2() {
JPanel topPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
topPanel.add(textField1);
topPanel.add(textField2);
topPanel.add(textField3);
topPanel.add(new JButton("Add"));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
bottomPanel.add(new JButton("Save"));
bottomPanel.add(new JButton("Run (F1)"));
bottomPanel.add(new JLabel(""));
bottomPanel.add(new JLabel(""));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Auto Clicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new App2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your whole approach is wrong. You should not be using a null layout. For example:
scroll.setBounds(370, 45, 20, 180);
you are setting the width to 20. Well how to you expect the text area to display in 20 pixels? This is the problem with using setBounds(...), the random numbers you use have no meaning. Let a layout manager do its job. Also:
add(listArea);
The problem is that a component can only have a single parent. You originally created the JScrollPane with the text area which is correct.
But then you add the text area directly to the frame which removes it from the scroll pane so the scroll panel will no longer function.
Get rid of that statement and just add the scroll pane to the frame.
However, I don't recommend you use this as your final solution. I just wanted to mention the current problems so you hopefully understand the benefits of using layout managers and so that you don't try to share components again.
The proper solution is to use layout managers as has been suggested by the "Community Wiki". Then the layout manager will determine the size and location of each component so you don't need to worry about calculating your pixel values correctly.
I have a scenario like, when user clicks on a button a pop window will be opened with a text area. The text area will have some contents with scroll bar when need. To achieve this i have used JDialog and added a text area to the JDialog. In my case i am able to show the dialog on button click and the text area on dialog with contents. But i could not get the scroll bar for the text area. I have used JScrollPane for text area too.
public class DialogPanel {
public void createDialog() {
final JFrame mainFrame = new JFrame();
mainFrame.setVisible(true);
mainFrame.setSize(500, 600);
mainFrame.setLayout(new BorderLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Open Dialog");
mainFrame.add(btn, BorderLayout.SOUTH);
JTextField txtField = new JTextField();
mainFrame.add(txtField, BorderLayout.NORTH);
btn.setPreferredSize(new Dimension(100, 100));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JDialog dialog = new JDialog(mainFrame);
dialog.setLocationByPlatform(true);
JTextArea txtArea = new JTextArea();
txtArea.setAutoscrolls(true);
txtArea.setPreferredSize(new Dimension(900, 500));
txtArea.setBorder(BorderFactory.createLineBorder(Color.BLACK));
txtArea.setFont(new Font("courier new", Font.PLAIN, 12));
txtArea.setLineWrap(true);
JScrollPane txtAreaScroll = new JScrollPane();
txtAreaScroll.setViewportView(txtArea);
txtAreaScroll.setAutoscrolls(true);
File file;
String line = null;
StringBuilder fileContents = new StringBuilder();
try {
file = new File(
"D:\\Softwares\\Apache\\apache-tomcat-7.0.47\\RUNNING.txt");
BufferedReader reader = new BufferedReader(new FileReader(
file));
while ((line = reader.readLine()) != null) {
fileContents.append(line + "\n");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtArea.setText(fileContents.toString());
dialog.add(txtAreaScroll);
dialog.pack();
dialog.setVisible(true);
}
});
}
public static void main(String[] args) {
DialogPanel dialogPanel = new DialogPanel();
dialogPanel.createDialog();
}
}
Essentially, txtArea.setPreferredSize(new Dimension(900, 500)); is removing the automatic calculations employed by JTextArea that it uses to determine the amount of space it needs to display all the text. You are effectivly saying, there is only 500 pixels worth of height that will ever be needed.
You "could" set the preferred size of the scroll pane, but that's not really recommended. Instead, you want to change the value returned by getPreferredScrollableViewportSize in the JTextArea
This tells the scroll pane how big to make the viewable area ... if it can...
JTextArea txtArea = new JTextArea() {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(900, 500);
}
};
Take a look at Scrollable for more details
Updated
As AndrewThompson has pointed out, a better (and preferred way) would be to simply specify the rows and columns for the JTextArea and let it figure out what that means based on the platforms rendering capabilities...
JTextArea txtArea = new JTextArea(40, 100);
Yea for simplicity...
You are using dialog.pack() see here and define own size for dialog
This way youu can use text area with scroll :
JTextArea txtArea = new JTextArea(40,100);
txtArea.setAutoscrolls(true);
txtArea.setBorder(BorderFactory.createLineBorder(Color.BLACK));
txtArea.setFont(new Font("courier new", Font.PLAIN, 12));
txtArea.setLineWrap(true);
txtArea.setText(j);
JScrollPane txtAreaScroll = new JScrollPane (txtArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
txtAreaScroll.setViewportView(txtArea);
txtAreaScroll.setAutoscrolls(true);
// now add scroll pane in frame
I recently tried out an online tutorial of Swing and Java GUI's and I decided to replicate the tutorial code but add in a third button. I tried to add in a red one, and I successfully did (it doesn't do anything yet), but i'm having some coordinate issues. Whenever I try to run it, something like this comes up:
All I really need help with is with coordinates or the size of the frames. I really don't know where to go from here. I'm sure this is a relatively simple question but, thanks!
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Test1 implements ActionListener
{
// Definition of global values and items that are part of the GUI.
int blackScoreAmount = 0;
int greenScoreAmount = 0;
int redScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel blackLabel, greenLabel, redLabel, blackScore, greenScore, redScore;
JButton blackButton, greenButton, redButton, resetButton;
public JPanel createContentPane ()
{
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 0);
titlePanel.setSize(180, 30);
totalGUI.add(titlePanel);
blackLabel = new JLabel("Black Team");
blackLabel.setLocation(0, 0);
blackLabel.setSize(120, 30);
blackLabel.setHorizontalAlignment(0);
blackLabel.setForeground(Color.black);
titlePanel.add(blackLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(130, 0);
greenLabel.setSize(120, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(250, 0);
redLabel.setSize(120, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(180, 30);
totalGUI.add(scorePanel);
blackScore = new JLabel(""+blackScoreAmount);
blackScore.setLocation(0, 0);
blackScore.setSize(120, 30);
blackScore.setHorizontalAlignment(0);
scorePanel.add(blackScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(130, 0);
greenScore.setSize(120, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(250, 0);
redScore.setSize(120, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(380, 80);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
blackButton = new JButton("Black Score");
blackButton.setLocation(0, 0);
blackButton.setSize(120, 30);
blackButton.addActionListener(this);
buttonPanel.add(blackButton);
greenButton = new JButton("Green Score");
greenButton.setLocation(130, 0);
greenButton.setSize(120, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
redButton = new JButton("Red Score");
redButton.setLocation(250, 0);
redButton.setSize(120, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 40);
resetButton.setSize(250, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == blackButton)
{
blackScoreAmount = blackScoreAmount + 1;
blackScore.setText(""+blackScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
blackScoreAmount = 0;
greenScoreAmount = 0;
blackScore.setText(""+blackScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Black and Green");
//Create and set up the content pane.
Test1 demo = new Test1();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Your frame is 280x190:
frame.setSize(280, 190);
and you try to place a red button with an x origin of 250 and a width size of 120 -> 370. Just adjust the window frame size accordingly if you add new elements.
And for that kind of task it may be better (at least simpler) to use layouts.
The size of your window is "hardcoded" :
frame.setSize(280, 190);
and so are the size and positions of your buttons:
redButton.setLocation(250, 0);
redButton.setSize(120, 30);
Your putting a button with a Width of 120 at the position 250 of a frame that is 280 large so only 25% of you button can be visible.
You have to adapt the size of your frame and the position of your buttons to get it to be fully visible and pretty..
EDIT
Now, has suggested by many other repliers, if you want to improve your application, try getting rid of all the hard-coded values and use Layout Managers instead.
Here are some good explanations about them :
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html