JTabbedPane Not working with Button and ComboBox as expected - java

I am having a problem with Java's Swing library. I added an Admission Class to JTabbedPane. The Button and ComboBox components on the first tab appear not to be working but, but when I remove setLayout(null) it seems to work, but this leads to other problems with the layout...
Below is what I have tried thus far:
DBProjectPractice.java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class DBProjectPractice extends JFrame {
private Container contentPane;
private String User = null;
public String getUser() {
String user = this.User;
return user;
}
public DBProjectPractice() {
// TODO Auto-generated constructor stub
init();
}
JTabbedPane pane = new JTabbedPane();
JTabbedPane createTabbedPane() { // tab pane init
pane.addTab("text", new Admission()); // 입사 탭의 레이아웃.
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
return pane;
}
public void init() {
contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout(30, 30));
setTitle("text");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane jtabbedpane = createTabbedPane();
contentPane.add(new Top(), BorderLayout.NORTH);
contentPane.add(jtabbedpane, BorderLayout.CENTER);
setLocationByPlatform(true);
setSize(1600, 1000); // 사이즈 설정 // 가로 세로
setVisible(true); // 표시
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DBProjectPractice();
}
}
Top.java
import java.awt.Font;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
class Top extends JPanel{
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Date date = new Date();
SimpleDateFormat text = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString("text : " , 100, 25);
g.drawString("text : " + text.format(date), 1200, 25);
this.setSize(1600, 30);
}
}
Admission.java
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
public class Admission extends JPanel {
private Container pane;
public Admission() {
// TODO Auto-generated constructor stub
setLayout(null);
Admission_Button();
FixLable_JLabel();
ComboBox();
}
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15); // 글꼴 설정
g.setFont(f); // 글꼴 지정
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30);
}
private void Admission_Button() { // 입사 탭의 레이아웃의 버튼
JButton[] Button = new JButton[3];
Button[0] = new JButton(" text ");
Button[1] = new JButton(" text ");
Button[2] = new JButton(" text ");
for(int i = 0; i < 3; i++) {
Button[i].setSize(100,40);
Button[i].setLocation(1065 + i * 120, 130);
add(Button[i]);
}
}
private void FixLable_JLabel() {
JLabel[] FixLabel = new JLabel[15]; // 고정된 label;
String[] FixLabelName = { "text", "text", "text","text","text","text","text","text","text","text",
"text","text","text","text","text"};
EtchedBorder eb = new EtchedBorder(Color.BLACK, Color.GRAY); // 테두리를 넣는다.
int FixLableIndex = 0;
for (String name : FixLabelName) {
FixLabel[FixLableIndex] = new JLabel(name);
FixLabel[FixLableIndex].setHorizontalAlignment(SwingConstants.CENTER); // 가운대 정렬
FixLabel[FixLableIndex].setBorder(eb); // 테두리 추가
FixLabel[FixLableIndex++].setSize(120, 30);
}
for(int i = 0 ; i < 7 ; i++) {
FixLabel[i].setLocation(100,200 + i * 30);
}
int t = 0;
for(int i = 7 ; i < 10 ; i++) {
FixLabel[i].setLocation(550,230 + t++ * 30);
}
FixLabel[10].setLocation(550, 350);
t = 0;
for(int i = 11 ; i < 14 ; i++) {
FixLabel[i].setLocation(1050,230 + t++ * 30);
}
FixLabel[14].setLocation(1050, 350);
for(int i = 0 ; i < 15; i++) {
add(FixLabel[i]);
}
}
private void ComboBox() {
String[] type = {"text", "text","text","text"};
JComboBox<String> typeCombo = new JComboBox<String>();
int num = type.length;
for(int i = 0 ; i < num ; i++) {
typeCombo.addItem(type[i]);
}
typeCombo.setBounds(220, 200, 1200, 30);
typeCombo.setSelectedItem(2);
add(typeCombo);
setVisible(true);
}
}

Your biggest problem (to me) seems to be that you're calling setSize(...) on your component within its own paintComponent method, a painting method:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30); // **** HERE ****
}
This is not correct and in fact dangerous, because it may try to change the component's size on any repaint, which then calls repaint almost recursively. Also the size that you're setting it to is unreasonable as a height of 30 can't possibly display the GUI that this JPanel holds. Don't do this.
Better:
to set size once via setSize(...) within the components constructor.
Better still to instead set preferred size by calling setPreferredSize(Dimension d) within the constructor.
Even better still is to instead override the component class's getPreferredSize().
Your other problem is that you're using null layouts. Again, while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

Related

How to center buttons in my java game menu

So, basically, I've never really worked with windows in java, and I need help centering things. I tried a bunch of things, but no matter what, I can't center my buttons on my java menu.
Here's my main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class window extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage canvas;
public window(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public Dimension getPreferredSize() {
return new Dimension(canvas.getWidth(), canvas.getHeight());
}
public void paint(Graphics g){
// double CanvasTileHeight = (canvas.getHeight()/16)+1;
// double CanvasTileWidth = (canvas.getWidth()/16)+1;
//
// OpenSimplexNoise noise = new OpenSimplexNoise();
//
// for(int j=0;j<CanvasTileWidth;j++) {
// double NoiseForCurrentLoopPos;
// if (((noise.eval(j,2)+1)*2)+16 < CanvasTileHeight) {
// NoiseForCurrentLoopPos = ((noise.eval(j,2)+1)*2)+16;
// } else {
// NoiseForCurrentLoopPos = CanvasTileHeight;
// }
// for(int i=(int) CanvasTileHeight;i>NoiseForCurrentLoopPos;i--) {
// Image sand = Toolkit.getDefaultToolkit().getImage("src/images/misc/sand.png");
// g.drawImage(sand, j*16, i*16, this);
// }
// }
//
// Image image = Toolkit.getDefaultToolkit().getImage("src/images/misc/Player_Placeholder1.png");
//
// ImageObserver paintingChild = null;
// g.drawImage(image, canvas.getWidth()/2-image.getWidth(paintingChild)/2, canvas.getHeight()/2-image.getHeight(paintingChild)/2, this);
//
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
int width = 640;
int height = 480;
JFrame frame = new JFrame("Example Frame");
window panel = new window(width, height);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel buttons = new JPanel();
BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
buttons.setLayout(boxlayout);
buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
buttons.add(bottomLabel);
JButton jb1 = new JButton("Button 1");
JButton jb2 = new JButton("Button 2");
JButton jb3 = new JButton("Button 3");
jb1.setAlignmentX(SwingConstants.CENTER);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb1);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb2);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb3);
frame.add(buttons);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// loadtest();
// System.out.println(Arrays.toString(((String) test1).split(",")));
//
// savetest();
dirtest();
}
public static void savetest() {
String TestArray[] = {"hi87er629087029648276540982", "hi2", "hi3", "hi4", "Not gonna keep going on like this lol"};
String Test = TestArray[0];
String world = "testworld101022";
for (int k = 0; k < TestArray.length-1; k++) {
Test = Test + "," + TestArray[k+1];
}
new File("src\\saves\\" + world).mkdir();
try(FileOutputStream f = new FileOutputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectOutput s = new ObjectOutputStream(f)) {
s.writeObject(Test);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
static Object test1 = null;
public static void loadtest() {
String world = "testworld101022";
try(FileInputStream in = new FileInputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectInputStream s = new ObjectInputStream(in)) {
test1 = s.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void dirtest() {
File dir = new File("src\\saves");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("No saves yet!");
} else {
for (int i = 0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
My problem is when I run it, this is what happens:
So, the buttons and/or test are not centered. I don't understand why.
My problem is, the buttons should be about where the red line on the image is, but no matter what I do, I can't get it to work.
I tried centering it with SwingConstants.CENTER, but that diden't work, so I also tried Component.CENTER_ALIGNMENT, but that did the exact same thing. I found that doing multiple different things like changing the code to
jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
makes it like this:
so basically it makes it so the 2 that are different from the one I changed are correctly centered, but the one I changed it not. All the images and stuff are probably unnecessary, but I hope I got across what I need help with! thanks =)
You can use BoxLayout to do that, take a look at the following code:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;
public class Main
{
public static void main(final String[] args)
{
final JLabel label = new JLabel("GAME NAME HERE");
final JButton button1 = new JButton("Button 1");
final JButton button2 = new JButton("Button 2");
final JButton button3 = new JButton("Button 3");
final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);
final JFrame frame = new JFrame();
frame.add(centerPanel);
frame.setVisible(true);
frame.pack();
}
private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
{
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Arrays.stream(components).forEach(component -> {
component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
panel.add(component);
panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
});
return panel;
}
}
If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

Animation Constructor not working in Java GUI

Hello I am new to Java GUI I made a second.java which is as below:
package theproject;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class second extends JPanel implements ActionListener {
private Timer animator;
private ImageIcon imageArray[];
private int delay=50, totalFrames=8, currentFreames=1;
public second()
{
imageArray= new ImageIcon[totalFrames];
System.out.println(imageArray.length);
for(int i=0; i<imageArray.length;i++)
{
imageArray[i]=new ImageIcon(i+1+".png");
System.out.println(i+1);
}
animator= new Timer(delay, this);
animator.start();
}
public void paintComponent(Graphics g )
{
super.paintComponent(g);
if(currentFreames<8)
{
imageArray[currentFreames].paintIcon(this, g, 0, 0);
currentFreames++;
System.out.println(currentFreames);
}
else{
currentFreames=0;
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
}
And a Gui calling the constructor second and output is not showing . Can you please guide me what should I do and the gui is given below:
package theproject;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
public class Sav {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sav window = new Sav();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Sav() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 0, 261, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
second s= new second();
frame.add(s);
}
});
btnNewButton.setBounds(273, -1, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
The gui has to basically call the constructor and which will showcase the animation on the screen If someone what i am doing wrong or if something that has to be done please let me know .
First, don't update the state within the paintComponent method, paint can occur for a number of reasons at any time, mostly without your interaction. Painting should simple paint the current state. In your ActionListener, you should advance the frame and make decisions about what should occur (like resetting the frame value)
Second, you never actually add second to anything, so it will never be displayed.
Third, you don't override getPreferredSize in second, so the layout managers will have no idea what size the component should be and will simply be assigned 0x0, making it as good as invisible as makes no difference
Fourth, you're using null layouts. This is going to make you life impossibly hard. Swing has been designed and optimised around the use of layout managers, they do important work in deciding how best to deal with differences in font metrics across different rendering systems/pipelines, I highly recommend that you take the time to learn how to use them
Fifthly, paintComponent has no business been public, no one should ever call it directly
Example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class Sav {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sav window = new Sav();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Sav() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(20);
frame.getContentPane().add(textField, gbc);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
second s = new second();
frame.add(s, gbc);
frame.getContentPane().revalidate();
frame.pack();
frame.setLocationRelativeTo(null);
}
});
frame.getContentPane().add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class second extends JPanel implements ActionListener {
private Timer animator;
private ImageIcon imageArray[];
private int delay = 50, totalFrames = 8, currentFreames = 1;
public second() {
imageArray = new ImageIcon[totalFrames];
for (int i = 0; i < imageArray.length; i++) {
imageArray[i] = new ImageIcon(getImage(i));
}
animator = new Timer(delay, this);
animator.start();
}
protected Image getImage(int index) {
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
FontMetrics fm = g2d.getFontMetrics();
g2d.dispose();
String text = Integer.toString(index);
int height = fm.getHeight();
int width = fm.stringWidth(text);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setColor(getForeground());
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
return img;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imageArray[0].getIconWidth(), imageArray[1].getIconHeight());
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
imageArray[currentFreames].paintIcon(this, g, 0, 0);
}
#Override
public void actionPerformed(ActionEvent arg0) {
currentFreames++;
if (currentFreames >= imageArray.length) {
currentFreames = 0;
}
repaint();
}
}
}
Your code is also not working. It increment the values of image set but do not displays the images
Works just fine for me...
imageArray[i]=new ImageIcon(i+1+".png"); will not generate any errors if the image can't be loaded for some reason (and it will load the images in the background thread, which is just another issue).
Instead, I would recommend using ImageIO.read instead, which will throw a IOException if the image can't be read for some reason, which is infinitely more useful. See Reading/Loading an Image for more details

How to add two panels with different layouts in one frame? [duplicate]

This question already exists:
How to set size for custom-made panel that will work with gridbaglayout?
Closed 6 years ago.
I have one panel whit gridBagLayout and second with null gridlayout. When I add that to main panel, and main panel to frame one panel disappears. Why is that? And how to add two panels with different layouts setings in one frame?
Here is the code main #Beowolve:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PrikazGUI {
JFrame frejm;
JPanel k;
JButton b1,b2;
public PrikazGUI(){
frejm = new JFrame("Lala");
k = new JPanel();
KvadratPravi p = new KvadratPravi();
JPanel grid = new JPanel();
grid.setLayout(new GridBagLayout());
grid.add(p);
// Kvadrat l = new Kvadrat();
JosJedanKvadrat jos = new JosJedanKvadrat();
// k.setLayout(null);
// k.setBounds(0, 444,444, 445);
k.add(jos);
k.add(grid);
JPanel main = new JPanel();
main.setLayout(null);
k.setBounds(0, 0,1000, 1900);
main.setBounds(0, 0,1000, 1900);
main.add(k);
frejm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frejm.setSize(1900, 1000);
frejm.getContentPane().add(main);
// frejm.getContentPane().add(k);
// frejm.pack();
frejm.setVisible(true);
}
public static void main(String[] args) {
PrikazGUI a = new PrikazGUI();
}
}
Second class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
public class KvadratPravi extends JPanel {
int sizeH = 60;
int sizeW = 60;
public GridBagConstraints cst = new GridBagConstraints();
public KvadratPravi() {
JPanel j = new JPanel();
j.setLayout(new GridBagLayout());
cst.gridx = 0;
cst.gridy = 0;
add(j,cst);
}
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(Color.PINK);
g.drawRect(0, 0, sizeH, sizeW);
g.fillRect(0, 0, sizeH, sizeW);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(sizeH,sizeW);
}
}
Third class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;
public class JosJedanKvadrat extends JPanel {
int sizeH = 60;
int sizeW = 60;
int x,y;
public JosJedanKvadrat() {
setBounds(33, 44,444, 445);
JPanel j = new JPanel();
setLayout(null);
add(j);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(!e.isMetaDown()){
x = e.getX();
y = e.getY();
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!e.isMetaDown()){
Point p = getLocation();
setLocation(p.x + e.getX() - x,
p.y + e.getY() - y);
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawOval(0, 0, sizeH, sizeW);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(sizeH,sizeW);
}
}
So I whant second class be in center of panel,and to have gridBagLayout, and third class I whant to move around the objects,so that class dont have gridlayout...when I and that two panels to main pane its seems that second class whit gridBagLayout does not working.
You are currently adding two JPanel into a JFrame.
JFrame f = new JFrame();
This frame, by default, use a BorderLayout. So if you call f.add(new Panel()); multiple time only the last one will be visible since the center area of this layout can only show one JComponent. You need to use a different layout.

Swing splash screen not working, Unexpected result

Downloaded some code to display Splash Screen from O'Reilly, but When I do some modified some text to display as per need.
I did some investigation, and debug the program but found nothing.
Is that any windows platform issue?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class SplashScreen extends JWindow {
private int duration;
byte[] msg = new byte[]{65,112,114,105,108,32,70, 111, 111,108};
String text = "";
public SplashScreen(int d) {
duration = d;
}
// A simple little method to show a title screen in the center
// of the screen for the amount of time given in the constructor
public void showSplash() throws Exception {
JPanel content = (JPanel)getContentPane();
content.setBackground(Color.white);
// Set the window's bounds, centering the window
int width = 450;
int height =300;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width-width)/2;
int y = (screen.height-height)/2;
setBounds(x,y,width,height);
JLabel txt = new JLabel
(new String(msg), JLabel.CENTER);
txt.setFont(new Font("Sans-Serif", Font.BOLD, 32));
// Build the splash screen
JLabel label = new JLabel(new ImageIcon("oreilly.gif"));
JLabel copyrt = new JLabel
(new String(msg), JLabel.CENTER);
URL url = new URL("http://findicons.com/files/icons/360/emoticons/128/satisfied.png");
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
JLabel iconL = new JLabel(icon);
copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
content.add(label, BorderLayout.CENTER);
content.add(txt, BorderLayout.CENTER);
content.add(iconL, BorderLayout.CENTER);
content.add(copyrt, BorderLayout.SOUTH);
Color oraRed = new Color(156, 20, 20, 255);
content.setBorder(BorderFactory.createLineBorder(oraRed, 10));
// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
try { Thread.sleep(duration); } catch (Exception e) {}
setVisible(false);
}
public void showSplashAndExit() {
try {
showSplash();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
public static void main(String[] args) {
// Throw a nice little title page up on the screen first
SplashScreen splash = new SplashScreen(10000);
// Normally, we'd call splash.showSplash() and get on with the program.
// But, since this is only a test...
splash.showSplashAndExit();
}
}

why can't I draw any stuffs on Frame in java?

Coding is here.
I can't create any rectangle or circle inside frame.
the object of this project is to create converting celcius 2 Farenheit & Farenheit 2 Celcius.
so what I want is, please teach me to how to draw rectangle or oval in side the frame.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class C2F extends JComponent{
private double input1, output1;
private double input2, output2;
JPanel center = new JPanel();
JPanel top = new JPanel();
JPanel east = new JPanel();
JPanel south = new JPanel();
//for giving input & output
C2F(){
JFrame frame = new JFrame();
frame.setTitle("C2F");
frame.setSize(700,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(top,BorderLayout.NORTH);
frame.getContentPane().add(center,BorderLayout.CENTER);
frame.getContentPane().add(south,BorderLayout.SOUTH);
frame.getContentPane().add(east,BorderLayout.EAST);
frame.setVisible(true);
CC2F();
}
public void CC2F(){
//making frame
//give specific location
JLabel L1 = new JLabel("Please input Celcius or Fahrenheit to Convert");
top.add(L1);
JLabel l1 = new JLabel("Cel -> Fah");
south.add(l1);
JTextField T1 = new JTextField(12);
south.add(T1);
JButton B1 = new JButton("Convert");
south.add(B1);
JLabel l2 = new JLabel("Fah -> Cel");
south.add(l2);
JTextField T2 = new JTextField(12);
south.add(T2);
JButton B2 = new JButton("Convert");
south.add(B2);
//to create buttons and labels to give an answer
B1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input1 = Double.parseDouble(T1.getText());
output1 = input1 *(9/5) + 32;
T2.setText(""+output1);
repaint();
}
});
B2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input2 = Double.parseDouble(T2.getText());
output2 = (input2 - 32)/9*5;
T1.setText(""+output2);
}
});
//making events
//placing the buttons and labels
output1 = 0;
output2 = 0;
//initialize the value
}
public void paintComponent(Graphics g) {
//error spots. it compiles well. But this is not what I want.
super.paintComponent(g);
Graphics2D gg = (Graphics2D) g;
gg.setColor(Color.BLACK);
gg.drawOval(350, 500,12,12);
gg.setColor(Color.RED);
gg.fillRect(350, 500, 10,(int) output1);
gg.fillOval(350, 500, 10, 10);
gg.setColor(Color.RED);
gg.fillRect(350, 500, 10,(int) output2);
gg.fillOval(350, 500, 10, 10);
//to draw stuffs
}
public static void main(String[] args)
{//to run the program
new C2F();
}
}
You never actually add C2F to anything that would be able to paint it, therefore your paint method will never be called.
You should override paintComponent instead of paint, as you've broken the paint chain for the component which could cause no end of issues with wonderful and interesting paint glitches. Convention would also suggest that you should call super.paintComponent (when overriding paintComponent) as well before you perform any custom painting
See Painting in AWT and Swing and Performing Custom Painting for more details
As a general piece of advice, I'd discourage you from creating a frame within the constructor of another component, this will make the component pretty much unusable again (if you wanted to re-use it on another container for example)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class C2F extends JComponent {
public C2F() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
TestPane center = new TestPane();
JPanel top = new JPanel();
JPanel east = new JPanel();
JPanel south = new JPanel();
//give specific location
JLabel L1 = new JLabel("Please input Celcius or Fahrenheit to Convert");
top.add(L1);
JLabel l1 = new JLabel("Cel -> Fah");
south.add(l1);
JTextField T1 = new JTextField(12);
south.add(T1);
JButton B1 = new JButton("Convert");
south.add(B1);
JLabel l2 = new JLabel("Fah -> Cel");
south.add(l2);
JTextField T2 = new JTextField(12);
south.add(T2);
JButton B2 = new JButton("Convert");
south.add(B2);
//to create buttons and labels to give an answer
B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double input1 = Double.parseDouble(T1.getText());
double output1 = input1 * (9 / 5) + 32;
T2.setText("" + output1);
center.setOutput1(output1);
}
});
B2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double input2 = Double.parseDouble(T2.getText());
double output2 = (input2 - 32) / 9 * 5;
T1.setText("" + output2);
center.setOutput2(output2);
}
});
//making events
frame.getContentPane().add(top, BorderLayout.NORTH);
frame.getContentPane().add(center, BorderLayout.CENTER);
frame.getContentPane().add(south, BorderLayout.SOUTH);
frame.getContentPane().add(east, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private double output1, output2;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 600);
}
public void setOutput1(double output1) {
this.output1 = output1;
repaint();
}
public void setOutput2(double output2) {
this.output2 = output2;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawOval(350, 500, 12, 12);
g2d.setColor(Color.RED);
g2d.fillRect(350, 0, 10, (int) output1);
g2d.fillOval(350, 0, 10, 10);
g2d.setColor(Color.BLUE);
g2d.fillRect(350, 0, 10, (int) output2);
g2d.fillOval(350, 0, 10, 10);
g2d.dispose();
}
}
public static void main(String[] args) {//to run the program
new C2F();
}
}

Categories